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 #16615
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/8718-a-repository-has-a-wallet-its-balance-is → main 0 commits fork 3 threads · 3 unresolved
27 files
changed +1546
−2
- docs/features/allocation.md
- src/actions/allocation.ts
- src/core/account_purge.ts
- src/core/allocation.ts
- src/core/empty_words.ts
- src/core/event_audience.ts
- src/core/migration-pins/20261128210000-allocation.pin
- src/core/migrations/20261128210000-allocation.ts
- src/crew/conversation_ask.ts
- src/crew/conversation_confirm.ts
- src/crew/dispatch.ts
- src/design/activity.ts
- src/http/mcp/tools/allocation.ts
- src/http/mcp/tools/index.ts
- src/http/server.ts
- src/main.ts
- src/tui/screens/allocation.ts
- src/tui/screens/workspace.ts
- src/web/pages/allocation.ts
- src/web/studio/crew.ts
- test/allocation-dispatch.test.ts
- test/allocation.test.ts
- test/conversation-ask.test.ts
- test/job-slices.test.ts
- test/llms-budget.test.ts
- test/mcp-forge-protocol.test.ts
- test/refusals-lead-somewhere.test.ts
docs/features/allocation.md added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: A repository's allocation — its balance, weekly sum and ledger | |
| 4 | --- | |
| 5 | # Repository allocation (#8718) | |
| 6 | ||
| 7 | Each repository has an allocation at `/<owner>/<name>/allocation` and in the MCP `allocation` tool: an append-only ledger in integer units (millionths of a list-price dollar) whose entries always total the balance. It is an allocation, not money; no cash or payment provider exists. | |
| 8 | ||
| 9 | - The weekly allocation refills the subscription fund each Monday 00:00 UTC; what is left expires and is spent first. Cash funds keep. Until the owner sets a weekly sum, it is seven days of the repository's old daily ceiling (the `autonomy_ceiling_usd` column, which outlives the setting). | |
| 10 | - Every run that starts needs allocation (`queueAgentRun`, assigned and directed runs too; one already going finishes). A run on a scope of a backed bet that holds an envelope asks that envelope and is paid from it (`envelopeOf`); `mayStart` says why not in one line. The autonomous week's share (`crew/week_read.ts`) still holds on top. | |
| 11 | - Reads write nothing. The ledger is settled at dispatch, on each move or weekly set, and hourly (`settleAll`). A run is entered at the time it ended, so one from last week is paid before the reset expires that week's fund. | |
| 12 | - Setting the weekly sum takes effect now, as a signed grant for the difference. An admin may lower it or raise it up to what it holds; more is the forge owner's word. Funds move only into a repository the actor administers. | |
| 13 | - The admin moves funds between repositories or into a bet in one action (`actions/allocation.ts`); the confirmation step asks first when an agent does it. | |
| 14 | - It sits beside the monthly wallet cap (`docs/features/wallet.md`, dollars, `/wallet`), which is a separate, older setting. No dependency. | |
| 15 | - Doors: the page `src/web/pages/allocation.ts`, the terminal `src/tui/screens/allocation.ts` (`m` moves funds and `w` sets the week, for an admin; the palette's "Allocation" while a repository is open), and the MCP tool. |
src/actions/allocation.ts added +128
| @@ -0,0 +1,128 @@ | ||
| 1 | /** | |
| 2 | * A repository's allocation, 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 { canAdmin, getRepo, type Repo } from "../core/repos.ts"; | |
| 13 | import { | |
| 14 | type Balance, | |
| 15 | bets, | |
| 16 | ceilingUsd, | |
| 17 | balanceOf, | |
| 18 | type Entry, | |
| 19 | ledger, | |
| 20 | type MoveError, | |
| 21 | moveUnits, | |
| 22 | nextReset, | |
| 23 | setWeekly, | |
| 24 | settle, | |
| 25 | WEEKLY_MAX, | |
| 26 | MOVE_MAX, | |
| 27 | UNIT, | |
| 28 | weeklyUnits, | |
| 29 | } from "../core/allocation.ts"; | |
| 30 | import { requireReader, requireRepoAdmin } from "./access.ts"; | |
| 31 | ||
| 32 | export interface AllocationView { | |
| 33 | readonly balance: Balance; | |
| 34 | readonly weeklyUnits: number; | |
| 35 | readonly resetsAt: string; | |
| 36 | readonly bets: { bet: string; balance: Balance }[]; | |
| 37 | readonly entries: Entry[]; | |
| 38 | } | |
| 39 | ||
| 40 | /** Said at the top of every surface that shows an allocation. */ | |
| 41 | export const ALLOCATION_SAYS = | |
| 42 | "An allocation, not money: list-price units the crew and bets spend; subscription funds refill each Monday (UTC) and expire, cash funds keep."; | |
| 43 | ||
| 44 | export function readAllocation(app: App, actor: User | undefined, repo: Repo, now = new Date()): Result<AllocationView, "not_found"> { | |
| 45 | const reader = requireReader(app, actor, repo); | |
| 46 | if (!reader.ok) return reader; | |
| 47 | // A pure read: settling is the dispatcher's, the schedule's and the mutations' (`settleAll`). | |
| 48 | return ok({ | |
| 49 | balance: balanceOf(app.db, repo.id), | |
| 50 | weeklyUnits: weeklyUnits(app.db, repo.id, ceilingUsd(app.db, repo.id)), | |
| 51 | resetsAt: nextReset(now).toISOString(), | |
| 52 | bets: bets(app.db, repo.id), | |
| 53 | entries: ledger(app.db, repo.id), | |
| 54 | }); | |
| 55 | } | |
| 56 | ||
| 57 | /** | |
| 58 | * Move allocation from this repository's pool (or one of its bets) to another | |
| 59 | * repository's pool, or into one of that repository's bets. `toRepo` is | |
| 60 | * `owner/name`; the actor must administer the repository the funds leave and | |
| 61 | * the one they reach: funds are not pushed into another owner's repository. | |
| 62 | */ | |
| 63 | export function moveFunds( | |
| 64 | app: App, | |
| 65 | actor: User | undefined, | |
| 66 | repo: Repo, | |
| 67 | o: { units: number; fromBet: string | null; toRepo: string | null; toBet: string | null }, | |
| 68 | now = new Date(), | |
| 69 | ): Result<{ id: string }, "not_found" | MoveError | "no_such_repo"> { | |
| 70 | const admin = requireRepoAdmin(app, actor, repo); | |
| 71 | if (!admin.ok) return admin; | |
| 72 | let target = repo; | |
| 73 | if (o.toRepo !== null && o.toRepo !== `${repo.ownerName}/${repo.name}`) { | |
| 74 | const [owner, name, ...rest] = o.toRepo.split("/"); | |
| 75 | const found = owner && name && rest.length === 0 ? getRepo(app.db, owner, name) : undefined; | |
| 76 | if (!found || !canAdmin(app.db, found, actor)) return err("no_such_repo"); | |
| 77 | target = found; | |
| 78 | } | |
| 79 | settle(app.db, repo.id, ceilingUsd(app.db, repo.id), now); | |
| 80 | settle(app.db, target.id, ceilingUsd(app.db, target.id), now); | |
| 81 | const moved = moveUnits(app.db, { | |
| 82 | from: { repoId: repo.id, bet: o.fromBet }, | |
| 83 | to: { repoId: target.id, bet: o.toBet }, | |
| 84 | units: o.units, | |
| 85 | actorId: admin.value.id, | |
| 86 | now, | |
| 87 | }); | |
| 88 | if (!moved.ok) return err(moved.error); | |
| 89 | app.bus.append({ | |
| 90 | kind: "allocation.moved", | |
| 91 | actorId: admin.value.id, | |
| 92 | repoId: repo.id, | |
| 93 | payload: { id: moved.id, units: o.units, to: `${target.ownerName}/${target.name}`, toBet: o.toBet, fromBet: o.fromBet }, | |
| 94 | }); | |
| 95 | return ok({ id: moved.id }); | |
| 96 | } | |
| 97 | ||
| 98 | /** The forge owner sets how much the repository's subscription fund refills each week. */ | |
| 99 | export function setWeeklyAllocation( | |
| 100 | app: App, | |
| 101 | actor: User | undefined, | |
| 102 | repo: Repo, | |
| 103 | units: number, | |
| 104 | now = new Date(), | |
| 105 | ): Result<{ weeklyUnits: number }, "not_found" | "invalid_amount" | "not_granted"> { | |
| 106 | const admin = requireRepoAdmin(app, actor, repo); | |
| 107 | if (!admin.ok) return admin; | |
| 108 | const ceiling = ceilingUsd(app.db, repo.id); | |
| 109 | // The allocation is what the forge's owner hands out: a repository's admin may lower it, and | |
| 110 | // may raise it only up to what it already holds; more is the forge owner's word. | |
| 111 | if (units > weeklyUnits(app.db, repo.id, ceiling) && !admin.value.isAdmin) return err("not_granted"); | |
| 112 | if (!setWeekly(app.db, repo.id, ceiling, units, admin.value.id, now)) return err("invalid_amount"); | |
| 113 | app.bus.append({ kind: "allocation.weekly_set", actorId: admin.value.id, repoId: repo.id, payload: { units } }); | |
| 114 | return ok({ weeklyUnits: units }); | |
| 115 | } | |
| 116 | ||
| 117 | export const MOVE_SAYS: Record<MoveError | "no_such_repo", string> = { | |
| 118 | invalid_amount: `The amount is a positive number of dollars up to ${MOVE_MAX / UNIT}.`, | |
| 119 | invalid_bet: "A bet's name is lowercase letters, digits and dashes.", | |
| 120 | same_place: "That is where the funds already are.", | |
| 121 | insufficient: "The allocation does not hold that much.", | |
| 122 | no_such_repo: "No repository by that name that you administer.", | |
| 123 | }; | |
| 124 | ||
| 125 | export const WEEKLY_SAYS: Record<"invalid_amount" | "not_granted", string> = { | |
| 126 | invalid_amount: `The weekly allocation is a number of dollars from 0 up to ${WEEKLY_MAX / UNIT}.`, | |
| 127 | not_granted: "Raising the weekly allocation above what it holds is the forge owner's word; an admin may lower it.", | |
| 128 | }; |
src/core/account_purge.ts +2
| @@ -51,6 +51,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 51 | 51 | "access_link.user_id": DELETE, |
| 52 | 52 | "access_link.created_by": FORMER, |
| 53 | 53 | "account_ceiling.set_by": FORMER, |
| 54 | "allocation_entry.actor_id": FORMER, | |
| 55 | "allocation_weekly.set_by": FORMER, | |
| 54 | 56 | "cloud_watch_ack.by": FORMER, |
| 55 | 57 | "account_notice.user_id": DELETE, |
| 56 | 58 | "account_request.decided_by": FORMER, |
src/core/allocation.ts added +413
| @@ -0,0 +1,413 @@ | ||
| 1 | /** | |
| 2 | * A repository's allocation (#8718): units 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/allocation.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 may be: 10 000 list-price dollars. */ | |
| 20 | export const MOVE_MAX = 10_000 * UNIT; | |
| 21 | /** The most a weekly allocation may be: 100 000 list-price dollars. */ | |
| 22 | export const WEEKLY_MAX = 100_000 * UNIT; | |
| 23 | ||
| 24 | export type Fund = "subscription" | "cash"; | |
| 25 | export type EntryKind = "weekly" | "expiry" | "run" | "move_out" | "move_in" | "grant"; | |
| 26 | ||
| 27 | export interface Entry { | |
| 28 | readonly id: number; | |
| 29 | readonly repoId: string; | |
| 30 | readonly bet: string | null; | |
| 31 | readonly kind: EntryKind; | |
| 32 | readonly fund: Fund; | |
| 33 | readonly units: number; | |
| 34 | readonly at: string; | |
| 35 | readonly runId: string | null; | |
| 36 | readonly note: string; | |
| 37 | } | |
| 38 | ||
| 39 | export interface Balance { | |
| 40 | readonly subscription: number; | |
| 41 | readonly cash: number; | |
| 42 | readonly total: number; | |
| 43 | } | |
| 44 | ||
| 45 | /** A bet's name in the ledger: lowercase letters, digits and dashes. */ | |
| 46 | export const validBet = (s: string): boolean => /^[a-z0-9][a-z0-9-]{0,39}$/.test(s); | |
| 47 | ||
| 48 | /** List-price dollars to whole units; the one place a float becomes an integer. */ | |
| 49 | export const toUnits = (usd: number): number => (Number.isFinite(usd) && usd > 0 ? Math.round(usd * UNIT) : 0); | |
| 50 | ||
| 51 | /** | |
| 52 | * Typed list-price dollars ("12", "12.5", "0.000001") to units by digits alone, or undefined: no | |
| 53 | * float is ever formed. | |
| 54 | */ | |
| 55 | export function parseUnits(text: string): number | undefined { | |
| 56 | const m = /^(\d{1,7})(?:\.(\d{1,6}))?$/.exec(text.trim()); | |
| 57 | if (!m) return undefined; | |
| 58 | return Number(m[1]) * UNIT + Number((m[2] ?? "").padEnd(6, "0")); | |
| 59 | } | |
| 60 | ||
| 61 | /** Units as exact dollars text ("12.50", "0.000001"): at least cents, never a digit dropped. */ | |
| 62 | export function unitsExact(units: number): string { | |
| 63 | const whole = Math.trunc(units / UNIT); | |
| 64 | const frac = String(Math.abs(units) % UNIT).padStart(6, "0").replace(/0+$/, "").padEnd(2, "0"); | |
| 65 | return `${whole}.${frac}`; | |
| 66 | } | |
| 67 | ||
| 68 | /** What each kind of entry is called, on every surface. */ | |
| 69 | export const KIND_WORDS: Record<EntryKind, string> = { | |
| 70 | weekly: "weekly allocation", | |
| 71 | expiry: "expired at the weekly reset", | |
| 72 | run: "run", | |
| 73 | move_out: "moved out", | |
| 74 | move_in: "moved in", | |
| 75 | grant: "granted", | |
| 76 | }; | |
| 77 | ||
| 78 | /** Units with their sign shown: "+$1.50", "-$0.25". */ | |
| 79 | export const signed = (units: number): string => `${units > 0 ? "+" : ""}${unitsText(units)}`; | |
| 80 | ||
| 81 | /** Units as dollars-and-cents text from integer math, truncated toward zero. */ | |
| 82 | export function unitsText(units: number): string { | |
| 83 | const cents = Math.trunc(units / (UNIT / 100)); | |
| 84 | const abs = Math.abs(cents); | |
| 85 | return `${cents < 0 ? "-" : ""}$${Math.trunc(abs / 100)}.${String(abs % 100).padStart(2, "0")}`; | |
| 86 | } | |
| 87 | ||
| 88 | /** The UTC Monday 00:00 that opens the week holding `now`. */ | |
| 89 | export function weekStart(now: Date): Date { | |
| 90 | const day = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())); | |
| 91 | day.setUTCDate(day.getUTCDate() - ((day.getUTCDay() + 6) % 7)); | |
| 92 | return day; | |
| 93 | } | |
| 94 | ||
| 95 | /** The next reset, when subscription funds expire. */ | |
| 96 | export function nextReset(now: Date): Date { | |
| 97 | const next = weekStart(now); | |
| 98 | next.setUTCDate(next.getUTCDate() + 7); | |
| 99 | return next; | |
| 100 | } | |
| 101 | ||
| 102 | /** | |
| 103 | * The daily ceiling the repository carried before allocations (#8718): the | |
| 104 | * column outlives the setting, so every existing ceiling carries over as | |
| 105 | * seven days of weekly allocation. | |
| 106 | */ | |
| 107 | export function ceilingUsd(db: Database, repoId: string): number { | |
| 108 | return db.query<{ c: number }, [string]>("SELECT autonomy_ceiling_usd AS c FROM repo WHERE id = ?1").get(repoId)?.c ?? 0; | |
| 109 | } | |
| 110 | ||
| 111 | /** | |
| 112 | * The weekly allocation: what the owner set, else seven of the repository's | |
| 113 | * old daily ceilings, so every existing ceiling carries over unchanged. | |
| 114 | */ | |
| 115 | export function weeklyUnits(db: Database, repoId: string, dailyCeilingUsd: number): number { | |
| 116 | const row = db | |
| 117 | .query<{ w: number }, [string]>("SELECT weekly_units AS w FROM allocation_weekly WHERE repo_id = ?1") | |
| 118 | .get(repoId); | |
| 119 | return row ? row.w : toUnits(dailyCeilingUsd) * 7; | |
| 120 | } | |
| 121 | ||
| 122 | const weeklySet = (db: Database, repoId: string): boolean => | |
| 123 | db.query("SELECT 1 FROM allocation_weekly WHERE repo_id = ?1").get(repoId) !== null; | |
| 124 | ||
| 125 | /** The pool's allocation entered since the week began: the refill and any grants that moved it. */ | |
| 126 | const allocatedSince = (db: Database, repoId: string, start: Date): number => | |
| 127 | db | |
| 128 | .query<{ n: number }, [string, string]>( | |
| 129 | `SELECT COALESCE(SUM(units), 0) AS n FROM allocation_entry | |
| 130 | WHERE repo_id = ?1 AND bet IS NULL AND fund = 'subscription' AND at >= ?2 | |
| 131 | AND (kind = 'weekly' OR (kind = 'grant' AND (note LIKE 'daily ceiling changed%' OR note LIKE 'weekly allocation set%')))`, | |
| 132 | ) | |
| 133 | .get(repoId, start.toISOString())?.n ?? 0; | |
| 134 | ||
| 135 | const scopeSum = (db: Database, repoId: string, bet: string | null, fund: Fund): number => | |
| 136 | db | |
| 137 | .query<{ n: number }, [string, string | null, string]>( | |
| 138 | `SELECT COALESCE(SUM(units), 0) AS n FROM allocation_entry | |
| 139 | WHERE repo_id = ?1 AND bet IS ?2 AND fund = ?3`, | |
| 140 | ) | |
| 141 | .get(repoId, bet, fund)?.n ?? 0; | |
| 142 | ||
| 143 | /** | |
| 144 | * The balance of the repository's pool (`bet` null) or of one bet's envelope: the sum of its | |
| 145 | * entries. | |
| 146 | */ | |
| 147 | export function balanceOf(db: Database, repoId: string, bet: string | null = null): Balance { | |
| 148 | const subscription = scopeSum(db, repoId, bet, "subscription"); | |
| 149 | const cash = scopeSum(db, repoId, bet, "cash"); | |
| 150 | return { subscription, cash, total: subscription + cash }; | |
| 151 | } | |
| 152 | ||
| 153 | function append( | |
| 154 | db: Database, | |
| 155 | e: { | |
| 156 | repoId: string; | |
| 157 | bet?: string | null; | |
| 158 | kind: EntryKind; | |
| 159 | fund: Fund; | |
| 160 | units: number; | |
| 161 | at: Date; | |
| 162 | week?: string; | |
| 163 | runId?: string; | |
| 164 | moveId?: string; | |
| 165 | actorId?: string | null; | |
| 166 | note?: string; | |
| 167 | }, | |
| 168 | ): void { | |
| 169 | db.query( | |
| 170 | `INSERT INTO allocation_entry (repo_id, bet, kind, fund, units, at, week, run_id, move_id, actor_id, note) | |
| 171 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)`, | |
| 172 | ).run( | |
| 173 | e.repoId, | |
| 174 | e.bet ?? null, | |
| 175 | e.kind, | |
| 176 | e.fund, | |
| 177 | e.units, | |
| 178 | e.at.toISOString(), | |
| 179 | e.week ?? null, | |
| 180 | e.runId ?? null, | |
| 181 | e.moveId ?? null, | |
| 182 | e.actorId ?? null, | |
| 183 | e.note ?? "", | |
| 184 | ); | |
| 185 | } | |
| 186 | ||
| 187 | /** A bet's name as its envelope is keyed: lowercase letters, digits and dashes. */ | |
| 188 | export const betKey = (name: string): string => | |
| 189 | name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+/, "").slice(0, 40).replace(/-+$/, ""); | |
| 190 | ||
| 191 | /** | |
| 192 | * The envelope a run on this issue draws from: the backed bet the issue is a scope of, when that | |
| 193 | * bet holds an envelope here (funds were moved into it). None: the repository's pool pays. | |
| 194 | */ | |
| 195 | export function envelopeOf(db: Database, repoId: string, issueId: string | null): string | null { | |
| 196 | if (issueId === null) return null; | |
| 197 | const names = db | |
| 198 | .query<{ name: string }, [string, string]>( | |
| 199 | `SELECT b.name FROM bet_issue bi JOIN bet b ON b.id = bi.bet_id | |
| 200 | WHERE bi.issue_id = ?1 AND b.repo_id = ?2 AND b.state = 'backed' ORDER BY b.id`, | |
| 201 | ) | |
| 202 | .all(issueId, repoId); | |
| 203 | for (const { name } of names) { | |
| 204 | const key = betKey(name); | |
| 205 | if (validBet(key) && db.query("SELECT 1 FROM allocation_entry WHERE repo_id = ?1 AND bet = ?2 LIMIT 1").get(repoId, key) !== null) return key; | |
| 206 | } | |
| 207 | return null; | |
| 208 | } | |
| 209 | ||
| 210 | /** Which scopes (the pool and each bet) hold a subscription remainder. */ | |
| 211 | const subscriptionScopes = (db: Database, repoId: string): { bet: string | null; n: number }[] => | |
| 212 | db | |
| 213 | .query<{ bet: string | null; n: number }, [string]>( | |
| 214 | `SELECT bet, SUM(units) AS n FROM allocation_entry | |
| 215 | WHERE repo_id = ?1 AND fund = 'subscription' GROUP BY bet HAVING SUM(units) != 0`, | |
| 216 | ) | |
| 217 | .all(repoId); | |
| 218 | ||
| 219 | /** | |
| 220 | * Bring the ledger up to `now`, appending what is owed and nothing else, so | |
| 221 | * the same state gives the same entries: the week's refill (after expiring | |
| 222 | * what the last week left), and each finished run's cost not yet entered, | |
| 223 | * drawn from the subscription fund first and from cash for the rest. | |
| 224 | */ | |
| 225 | export function settle(db: Database, repoId: string, dailyCeilingUsd: number, now: Date): void { | |
| 226 | const start = weekStart(now); | |
| 227 | const week = start.toISOString().slice(0, 10); | |
| 228 | // Runs that began in the week before still settle; older ones are history. | |
| 229 | const since = new Date(start.getTime() - 7 * 86_400_000); | |
| 230 | const owed = db | |
| 231 | .query<{ id: string; cost: number; issue: string | null; at: string }, [string, string]>( | |
| 232 | `SELECT r.id AS id, r.cost_usd AS cost, r.issue_id AS issue, | |
| 233 | COALESCE(r.finished_at, r.started_at, r.created_at) AS at FROM run r | |
| 234 | WHERE r.repo_id = ?1 AND r.id >= ?2 AND r.kind = 'agent' AND r.cost_usd > 0 | |
| 235 | AND NOT EXISTS (SELECT 1 FROM allocation_entry w WHERE w.run_id = r.id) | |
| 236 | ORDER BY r.id`, | |
| 237 | ) | |
| 238 | .all(repoId, idFloor(since.getTime())); | |
| 239 | const refilled = | |
| 240 | db | |
| 241 | .query<{ n: number }, [string, string]>( | |
| 242 | "SELECT COUNT(*) AS n FROM allocation_entry WHERE repo_id = ?1 AND kind = 'weekly' AND week = ?2", | |
| 243 | ) | |
| 244 | .get(repoId, week)?.n === 1; | |
| 245 | const weekly = weeklyUnits(db, repoId, dailyCeilingUsd); | |
| 246 | // With no weekly allocation set, the week's allocation follows the daily ceiling as it is | |
| 247 | // changed: the drift between seven of it and what was refilled is entered as one signed grant. | |
| 248 | const drift = refilled && !weeklySet(db, repoId) ? weekly - allocatedSince(db, repoId, start) : 0; | |
| 249 | if (owed.length === 0 && drift === 0 && (refilled || weekly === 0)) return; | |
| 250 | // A run's entry is stamped when the run ended, and a run that ended before this week opened is | |
| 251 | // paid before the reset expires what that week left, never from this week's fresh fund. | |
| 252 | const stamp = (at: string): Date => { | |
| 253 | const t = Date.parse(at); | |
| 254 | return Number.isFinite(t) ? new Date(Math.min(t, now.getTime())) : now; | |
| 255 | }; | |
| 256 | const before = (run: { at: string }): boolean => stamp(run.at).getTime() < start.getTime(); | |
| 257 | const charge = (run: { id: string; cost: number; issue: string | null; at: string }): void => { | |
| 258 | const cost = toUnits(run.cost); | |
| 259 | if (cost === 0) return; | |
| 260 | // A bet that holds an envelope pays its runs' cost from it; the pool pays the rest. | |
| 261 | const bet = envelopeOf(db, repoId, run.issue); | |
| 262 | const at = stamp(run.at); | |
| 263 | const fromSub = Math.max(0, Math.min(cost, scopeSum(db, repoId, bet, "subscription"))); | |
| 264 | const fromCash = cost - fromSub; | |
| 265 | if (fromSub > 0) append(db, { repoId, bet, kind: "run", fund: "subscription", units: -fromSub, at, runId: run.id, note: "run cost at list price" }); | |
| 266 | if (fromCash > 0) | |
| 267 | // The unique run index allows one entry per run: a run that spans both funds records the | |
| 268 | // subscription part under its id and the cash part under none. | |
| 269 | append(db, { repoId, bet, 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" }); | |
| 270 | }; | |
| 271 | transact(db, () => { | |
| 272 | for (const run of owed) if (before(run)) charge(run); | |
| 273 | if (drift !== 0) | |
| 274 | append(db, { repoId, kind: "grant", fund: "subscription", units: drift, at: now, note: "daily ceiling changed: the week's allocation follows" }); | |
| 275 | if (!refilled && weekly > 0) { | |
| 276 | for (const s of subscriptionScopes(db, repoId)) | |
| 277 | if (s.n > 0) | |
| 278 | append(db, { repoId, bet: s.bet, kind: "expiry", fund: "subscription", units: -s.n, at: start, note: "the week's reset" }); | |
| 279 | try { | |
| 280 | append(db, { repoId, kind: "weekly", fund: "subscription", units: weekly, at: start, week, note: "weekly allocation" }); | |
| 281 | } catch { | |
| 282 | // A second process refilled this week first (the unique index); the allocation stands once. | |
| 283 | } | |
| 284 | } | |
| 285 | for (const run of owed) if (!before(run)) charge(run); | |
| 286 | }); | |
| 287 | } | |
| 288 | ||
| 289 | /** The balance after settling to `now`: what a page shows. */ | |
| 290 | export function balanceNow(db: Database, repoId: string, dailyCeilingUsd: number, now: Date): Balance { | |
| 291 | settle(db, repoId, dailyCeilingUsd, now); | |
| 292 | return balanceOf(db, repoId); | |
| 293 | } | |
| 294 | ||
| 295 | export type MoveError = "invalid_amount" | "invalid_bet" | "same_place" | "insufficient"; | |
| 296 | ||
| 297 | /** | |
| 298 | * Move `units` from one place to another in one transaction: each place is a | |
| 299 | * repository pool or one of its bets. The receiving side gets the same funds | |
| 300 | * the giving side gave, subscription first, so a move cannot turn an | |
| 301 | * expiring allocation into keeping cash. Returns the move's id. | |
| 302 | */ | |
| 303 | export function moveUnits( | |
| 304 | db: Database, | |
| 305 | o: { | |
| 306 | from: { repoId: string; bet: string | null }; | |
| 307 | to: { repoId: string; bet: string | null }; | |
| 308 | units: number; | |
| 309 | actorId: string; | |
| 310 | now: Date; | |
| 311 | note?: string; | |
| 312 | }, | |
| 313 | ): { ok: true; id: string } | { ok: false; error: MoveError } { | |
| 314 | const { from, to, units } = o; | |
| 315 | if (!Number.isSafeInteger(units) || units <= 0 || units > MOVE_MAX) return { ok: false, error: "invalid_amount" }; | |
| 316 | if ((from.bet !== null && !validBet(from.bet)) || (to.bet !== null && !validBet(to.bet))) return { ok: false, error: "invalid_bet" }; | |
| 317 | if (from.repoId === to.repoId && from.bet === to.bet) return { ok: false, error: "same_place" }; | |
| 318 | return transact(db, () => { | |
| 319 | const sub = Math.max(0, scopeSum(db, from.repoId, from.bet, "subscription")); | |
| 320 | const cash = Math.max(0, scopeSum(db, from.repoId, from.bet, "cash")); | |
| 321 | if (sub + cash < units) return { ok: false as const, error: "insufficient" as const }; | |
| 322 | const takeSub = Math.min(sub, units); | |
| 323 | const takeCash = units - takeSub; | |
| 324 | const moveId = newId(); | |
| 325 | for (const [fund, n] of [["subscription", takeSub], ["cash", takeCash]] as const) { | |
| 326 | if (n === 0) continue; | |
| 327 | const base = { fund, at: o.now, moveId, actorId: o.actorId, note: o.note ?? "" }; | |
| 328 | append(db, { ...base, repoId: from.repoId, bet: from.bet, kind: "move_out", units: -n }); | |
| 329 | append(db, { ...base, repoId: to.repoId, bet: to.bet, kind: "move_in", units: n }); | |
| 330 | } | |
| 331 | return { ok: true as const, id: moveId }; | |
| 332 | }); | |
| 333 | } | |
| 334 | ||
| 335 | /** | |
| 336 | * Set the weekly allocation, effective now: the week already refilled is brought to the new sum by | |
| 337 | * one signed grant (the way a changed ceiling is), so the balance moves at once rather than on | |
| 338 | * Monday. False when it is not a whole, sane number of units. | |
| 339 | */ | |
| 340 | export function setWeekly(db: Database, repoId: string, dailyCeilingUsd: number, units: number, by: string, now: Date): boolean { | |
| 341 | if (!Number.isSafeInteger(units) || units < 0 || units > WEEKLY_MAX) return false; | |
| 342 | settle(db, repoId, dailyCeilingUsd, now); | |
| 343 | transact(db, () => { | |
| 344 | const start = weekStart(now); | |
| 345 | const refilled = | |
| 346 | db | |
| 347 | .query<{ n: number }, [string, string]>("SELECT COUNT(*) AS n FROM allocation_entry WHERE repo_id = ?1 AND kind = 'weekly' AND week = ?2") | |
| 348 | .get(repoId, start.toISOString().slice(0, 10))?.n === 1; | |
| 349 | const diff = units - allocatedSince(db, repoId, start); | |
| 350 | db.query( | |
| 351 | `INSERT INTO allocation_weekly (repo_id, weekly_units, set_by, set_at) VALUES (?1, ?2, ?3, ?4) | |
| 352 | ON CONFLICT(repo_id) DO UPDATE SET weekly_units = ?2, set_by = ?3, set_at = ?4`, | |
| 353 | ).run(repoId, units, by, now.toISOString()); | |
| 354 | if (refilled && diff !== 0) | |
| 355 | append(db, { repoId, kind: "grant", fund: "subscription", units: diff, at: now, actorId: by, note: "weekly allocation set: the week's allocation follows" }); | |
| 356 | }); | |
| 357 | // Not yet refilled this week (it was empty): the refill takes the new sum. | |
| 358 | settle(db, repoId, dailyCeilingUsd, now); | |
| 359 | return true; | |
| 360 | } | |
| 361 | ||
| 362 | /** Settle every repository that is open to work: the schedule that keeps reads free of writes. */ | |
| 363 | export function settleAll(db: Database, now: Date): number { | |
| 364 | const rows = db.query<{ id: string; c: number }, []>("SELECT id, autonomy_ceiling_usd AS c FROM repo WHERE archived_at IS NULL").all(); | |
| 365 | for (const r of rows) settle(db, r.id, r.c, now); | |
| 366 | return rows.length; | |
| 367 | } | |
| 368 | ||
| 369 | /** The newest entries first. */ | |
| 370 | export function ledger(db: Database, repoId: string, limit = 100): Entry[] { | |
| 371 | return db | |
| 372 | .query< | |
| 373 | { id: number; repo_id: string; bet: string | null; kind: EntryKind; fund: Fund; units: number; at: string; run_id: string | null; note: string }, | |
| 374 | [string, number] | |
| 375 | >( | |
| 376 | `SELECT id, repo_id, bet, kind, fund, units, at, run_id, note FROM allocation_entry | |
| 377 | WHERE repo_id = ?1 ORDER BY id DESC LIMIT ?2`, | |
| 378 | ) | |
| 379 | .all(repoId, Math.max(1, Math.min(500, limit))) | |
| 380 | .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 })); | |
| 381 | } | |
| 382 | ||
| 383 | /** The bets that hold an envelope here, with their balances. */ | |
| 384 | export function bets(db: Database, repoId: string): { bet: string; balance: Balance }[] { | |
| 385 | return db | |
| 386 | .query<{ bet: string }, [string]>("SELECT DISTINCT bet FROM allocation_entry WHERE repo_id = ?1 AND bet IS NOT NULL ORDER BY bet") | |
| 387 | .all(repoId) | |
| 388 | .map((r) => ({ bet: r.bet, balance: balanceOf(db, repoId, r.bet) })); | |
| 389 | } | |
| 390 | ||
| 391 | /** | |
| 392 | * Whether a run may start: the bet's envelope has funds, or, with no bet, | |
| 393 | * the repository's pool does. The one line it says otherwise is the reason | |
| 394 | * every surface shows. | |
| 395 | */ | |
| 396 | export function mayStart( | |
| 397 | db: Database, | |
| 398 | repoId: string, | |
| 399 | dailyCeilingUsd: number, | |
| 400 | now: Date, | |
| 401 | bet: string | null = null, | |
| 402 | ): { ok: true } | { ok: false; says: string } { | |
| 403 | settle(db, repoId, dailyCeilingUsd, now); | |
| 404 | const b = balanceOf(db, repoId, bet); | |
| 405 | if (b.total > 0) return { ok: true }; | |
| 406 | return { | |
| 407 | ok: false, | |
| 408 | says: | |
| 409 | bet === null | |
| 410 | ? `No run starts: this repository's allocation is empty (${unitsText(b.total)} allocated); it refills Monday ${nextReset(now).toISOString().slice(0, 10)}, or the owner moves funds in.` | |
| 411 | : `No run starts: bet ${bet} has no funds left (${unitsText(b.total)}); the owner moves funds into it.`, | |
| 412 | }; | |
| 413 | } |
src/core/empty_words.ts +1
| @@ -107,6 +107,7 @@ export const NOTE_WORDS = { | ||
| 107 | 107 | nothingToPropose: "Nothing to propose.", |
| 108 | 108 | nothingFound: "Nothing found.", |
| 109 | 109 | noGateHasRunYet: "No gate has run yet.", |
| 110 | nothingHasHappenedHereYet: "Nothing has happened here yet.", | |
| 110 | 111 | nothingQueuedGatingOrLandedInTheLastHour: "Nothing queued, gating or landed in the last hour.", |
| 111 | 112 | noFileIsTouchedBy3OrMoreOpenPulls: "No file is touched by 3 or more open pulls.", |
| 112 | 113 | noChangeYet: "No change yet.", |
src/core/event_audience.ts +2
| @@ -336,6 +336,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 336 | 336 | kind === "repo.source_added" || |
| 337 | 337 | kind === "repo.source_removed" || |
| 338 | 338 | kind === "repo.crew_outsiders" || |
| 339 | // An allocation is the owner's book-keeping (#8718). | |
| 340 | kind.startsWith("allocation.") || | |
| 339 | 341 | // An outside agent's token and the owner's yes to them are the admins' (#12012). |
| 340 | 342 | kind.startsWith("contribute.") || |
| 341 | 343 | // A valve turn names a repository and the owner's budget: for those who administer it |
src/core/migration-pins/20261128210000-allocation.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 2ad393bf50a1b43725f12daabc2ebe095537b84e81031ca60f556ef51d709571 |
src/core/migrations/20261128210000-allocation.ts added +34
| @@ -0,0 +1,34 @@ | ||
| 1 | // A repository's allocation (#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 allocation_weekly 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 allocation_weekly ( | |
| 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 allocation_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 allocation_entry_repo ON allocation_entry(repo_id, id); | |
| 28 | CREATE UNIQUE INDEX allocation_entry_week ON allocation_entry(repo_id, week) WHERE kind = 'weekly'; | |
| 29 | CREATE UNIQUE INDEX allocation_entry_run ON allocation_entry(run_id) WHERE run_id IS NOT NULL; | |
| 30 | CREATE TRIGGER allocation_entry_no_update BEFORE UPDATE ON allocation_entry | |
| 31 | BEGIN SELECT RAISE(ABORT, 'allocation entries are append only'); END; | |
| 32 | CREATE TRIGGER allocation_entry_no_delete BEFORE DELETE ON allocation_entry | |
| 33 | BEGIN SELECT RAISE(ABORT, 'allocation entries are append only'); END; | |
| 34 | `; |
src/crew/conversation_ask.ts +6
| @@ -128,6 +128,12 @@ function pinnedForge(a: Args): string { | ||
| 128 | 128 | |
| 129 | 129 | export const ASKED_AS: Readonly<Record<string, Form>> = { |
| 130 | 130 | // The everyday work, the fence's undoable list first. |
| 131 | allocation: (a) => | |
| 132 | a["move"] !== undefined | |
| 133 | ? `Move allocation out of ${repo(a)}` | |
| 134 | : a["weekly"] !== undefined | |
| 135 | ? `Set ${repo(a)}'s weekly allocation${clause(" to $", val(a, "weekly"))}` | |
| 136 | : `Read ${repo(a)}'s allocation`, | |
| 131 | 137 | tell: (a) => { |
| 132 | 138 | if (a["undo"] !== undefined) return `Take back your request #${val(a, "undo")}${clause(" in ", val(a, "repo"))}`; |
| 133 | 139 | const said = quote(a, "text"); |
src/crew/conversation_confirm.ts +4
| @@ -77,6 +77,10 @@ export const ASKING: Readonly<Record<string, Asking>> = { | ||
| 77 | 77 | talk_watch: { asks: (a) => a["action"] === "add" }, |
| 78 | 78 | model_grant: { undo: () => "`model_grant` with `usdPerMonth: 0` takes it back" }, |
| 79 | 79 | model_ceiling: { undo: () => "`model_ceiling` with both `null` clears it" }, |
| 80 | // Moving a repository's allocation or setting its weekly sum is the owner's yes (#8718). | |
| 81 | allocation: { | |
| 82 | asks: (a) => a["move"] !== undefined || a["weekly"] !== undefined, | |
| 83 | }, | |
| 80 | 84 | limits: { undo: () => "`limits` with `value: \"\"` restores the default" }, |
| 81 | 85 | // Closing the Later gate's unchosen ideas in one go; reading its proposal asks nothing. |
| 82 | 86 | held: { |
src/crew/dispatch.ts +11
| @@ -18,6 +18,7 @@ import { betCapHold } from "./bet_cap_hold.ts"; | ||
| 18 | 18 | import { weekHold } from "./week_hold.ts"; |
| 19 | 19 | import { personActing } from "../core/acting_via.ts"; |
| 20 | 20 | import { weekFor, weekSpent } from "./week_read.ts"; |
| 21 | import { ceilingUsd, envelopeOf, mayStart } from "../core/allocation.ts"; | |
| 21 | 22 | import { redStreak } from "./red_thrice.ts"; |
| 22 | 23 | import { twinNote, twinOf, type Twin } from "./twin.ts"; |
| 23 | 24 | import { NO_MERGE } from "../checks/merged.ts"; |
| @@ -609,6 +610,16 @@ export function queueAgentRun( | ||
| 609 | 610 | }); |
| 610 | 611 | return undefined; |
| 611 | 612 | } |
| 613 | // The allocation gates every run that starts (#8718): the crew's own, a person's assignment, a | |
| 614 | // directed run, in any autonomy; only one already going (`again`) finishes. A run on a scope of a | |
| 615 | // bet that holds an envelope asks that envelope, and its cost is settled against it. | |
| 616 | if (again === undefined) { | |
| 617 | const may = mayStart(app.db, repo.id, ceilingUsd(app.db, repo.id), new Date(), envelopeOf(app.db, repo.id, issue.id)); | |
| 618 | if (!may.ok) { | |
| 619 | log.info(may.says, { repo: `${repo.ownerName}/${repo.name}`, issue: issue.number, reason }); | |
| 620 | return undefined; | |
| 621 | } | |
| 622 | } | |
| 612 | 623 | // Three failed or declined runs in an hour: parked, until a person speaks. |
| 613 | 624 | if (breakerTripped(app.db, repo, issue.id)) { |
| 614 | 625 | parkForBreaker(app, repo, issue, agent); |
src/design/activity.ts +2
| @@ -212,6 +212,8 @@ const WORDS: Record<string, string> = { | ||
| 212 | 212 | "repo.source_removed": "stopped following a source", |
| 213 | 213 | "repo.origin_follow": "followed, or stopped following, the forge a repository was brought from", |
| 214 | 214 | "repo.following": "turned following an upstream on or off", |
| 215 | "allocation.moved": "moved allocation from a repository", | |
| 216 | "allocation.weekly_set": "set a repository's weekly allocation", | |
| 215 | 217 | "repo.crew_outsiders": "changed who may trigger the crew", |
| 216 | 218 | "repo.mirrored": "mirrored a repository", |
| 217 | 219 | "repo.imported": "imported issues and pulls", |
src/http/mcp/tools/allocation.ts added +56
| @@ -0,0 +1,56 @@ | ||
| 1 | import { MOVE_SAYS, WEEKLY_SAYS, moveFunds, readAllocation, setWeeklyAllocation, ALLOCATION_SAYS } from "../../../actions/allocation.ts"; | |
| 2 | import { parseUnits, unitsText } from "../../../core/allocation.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: "allocation", | |
| 9 | doc: "`{ repo, move?: { amount, fromBet?, toRepo?, toBet? }, weekly? }`: its allocation: balance, bets, ledger; `move`, `weekly` (dollars as text): admin", | |
| 10 | description: | |
| 11 | "Read an allocation; admin moves it or sets the week.", | |
| 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", WEEKLY_SAYS.invalid_amount); | |
| 48 | const set = setWeeklyAllocation(ctx.app, user, repo, units); | |
| 49 | if (!set.ok) return bad(set.error, set.error === "not_found" ? "only an admin of this repository sets its allocation" : WEEKLY_SAYS[set.error]); | |
| 50 | return good({ weeklyUnits: set.value.weeklyUnits, says: `Weekly allocation is ${unitsText(units)}.` }); | |
| 51 | } | |
| 52 | const view = readAllocation(ctx.app, user, repo); | |
| 53 | if (!view.ok) return bad("not_found", "no such repository"); | |
| 54 | return good({ ...view.value, says: ALLOCATION_SAYS }); | |
| 55 | }, | |
| 56 | }; |
src/http/mcp/tools/index.ts +1
| @@ -9,6 +9,7 @@ export { tool as account_verify } from "./account_verify.ts"; | ||
| 9 | 9 | export { tool as accounts } from "./accounts.ts"; |
| 10 | 10 | export { tool as agent } from "./agent.ts"; |
| 11 | 11 | export { tool as agents } from "./agents.ts"; |
| 12 | export { tool as allocation } from "./allocation.ts"; | |
| 12 | 13 | export { tool as app_data_import } from "./app_data_import.ts"; |
| 13 | 14 | export { tool as app_deploy } from "./app_deploy.ts"; |
| 14 | 15 | export { tool as app_domains } from "./app_domains.ts"; |
src/http/server.ts +4
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * verdict. Auth is resolved once per request and handed to handlers as data. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { allocationMove, allocationPage, allocationWeekly } from "../web/pages/allocation.ts"; | |
| 8 | 9 | import { runOwnToken } from "../web/own_token.ts"; |
| 9 | 10 | import { togetherFragment, togetherLine, togethernessOf } from "../web/together.ts"; |
| 10 | 11 | import { outsiderStatusPage } from "./offer_routes.ts"; |
| @@ -1938,6 +1939,9 @@ export function buildRouter(): Router<Handler> { | ||
| 1938 | 1939 | router.add("POST", "/:owner/:name/settings/pillars", pillarUpdate); |
| 1939 | 1940 | router.add("GET", "/:owner/:name/settings/autonomy", autonomySettingsPage); |
| 1940 | 1941 | router.add("POST", "/:owner/:name/settings/autonomy", autonomySettingsUpdate); |
| 1942 | router.add("GET", "/:owner/:name/allocation", allocationPage); | |
| 1943 | router.add("POST", "/:owner/:name/allocation/move", allocationMove); | |
| 1944 | router.add("POST", "/:owner/:name/allocation/weekly", allocationWeekly); | |
| 1941 | 1945 | router.add("POST", "/:owner/:name/settings/holds", fileHoldUpdate); |
| 1942 | 1946 | router.add("POST", "/:owner/:name/settings/upstream", followUpstreamUpdate); |
| 1943 | 1947 | router.add("POST", "/:owner/:name/settings/upstream/check", followUpstreamCheck); |
src/main.ts +6
| @@ -8,6 +8,7 @@ import "./kernel/bun_guard.ts"; | ||
| 8 | 8 | import { join } from "node:path"; |
| 9 | 9 | import { sweepEntitlements } from "./billing/sync.ts"; |
| 10 | 10 | import { sweepDesk } from "./actions/desk.ts"; |
| 11 | import { settleAll } from "./core/allocation.ts"; | |
| 11 | 12 | import { resumePinnedWatches } from "./actions/pinned.ts"; |
| 12 | 13 | import { statusTick } from "./core/status_days.ts"; |
| 13 | 14 | import { scanNightly } from "./checks/scan.ts"; |
| @@ -969,6 +970,10 @@ const staleTimer = setInterval(() => void during("asks", tickAsks, undefined, ap | ||
| 969 | 970 | // A desk note whose time is up goes off the home line at once, over the stream. |
| 970 | 971 | const deskTimer = setInterval(() => void during("desk", () => sweepDesk(app), undefined, app), 30_000); |
| 971 | 972 | // Every paid entitlement is re-read from Stripe once a day, so a missed webhook heals (#11247). |
| 973 | // Allocations are settled here, on a schedule, and at dispatch, never by a read (#8718): the week's | |
| 974 | // refill and the runs finished since are entered once an hour and at boot. | |
| 975 | const allocationTimer = readOnly ? undefined : setInterval(() => void during("allocation", () => settleAll(app.db, new Date()), undefined, app), 3_600_000); | |
| 976 | if (!readOnly) during("allocation", () => settleAll(app.db, new Date()), undefined, app); | |
| 972 | 977 | const entitlementTimer = setInterval(() => void during("entitlements", () => sweepEntitlements(app), undefined, app), 86_400_000); |
| 973 | 978 | void during("entitlements", () => sweepEntitlements(app), undefined, app); |
| 974 | 979 | // While the crew waits on a full window, the provider's meter is read every 15 minutes, so an early |
| @@ -1230,6 +1235,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> { | ||
| 1230 | 1235 | clearInterval(staleTimer); |
| 1231 | 1236 | clearInterval(deskTimer); |
| 1232 | 1237 | clearInterval(entitlementTimer); |
| 1238 | if (allocationTimer !== undefined) clearInterval(allocationTimer); | |
| 1233 | 1239 | clearInterval(meterTimer); |
| 1234 | 1240 | if (ledgerTimer !== undefined) clearInterval(ledgerTimer); |
| 1235 | 1241 | clearInterval(followTimer); |
src/tui/screens/allocation.ts added +175
| @@ -0,0 +1,175 @@ | ||
| 1 | /** | |
| 2 | * A repository's allocation in the terminal (#8718; docs/features/allocation.md): the page | |
| 3 | * (`web/pages/allocation.ts`) from the same read (`actions/allocation.ts` `readAllocation`), so the | |
| 4 | * same gate holds: whoever may read the repository. Its admin moves funds (`m`) or sets the weekly | |
| 5 | * sum (`w`) in a small form, through the same actions as the page and the MCP `allocation` tool. | |
| 6 | * List-price units, UTC. | |
| 7 | */ | |
| 8 | ||
| 9 | import { ALLOCATION_SAYS, MOVE_SAYS, WEEKLY_SAYS, moveFunds, readAllocation, setWeeklyAllocation } from "../../actions/allocation.ts"; | |
| 10 | import { KIND_WORDS, parseUnits, signed, unitsExact, unitsText } from "../../core/allocation.ts"; | |
| 11 | import { canAdmin, type Repo } from "../../core/repos.ts"; | |
| 12 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 13 | import { binding } from "../app/keys.ts"; | |
| 14 | import type { Command } from "../app/palette.ts"; | |
| 15 | import type { Session } from "../session.ts"; | |
| 16 | import { style } from "../term/style.ts"; | |
| 17 | import { truncate } from "../term/width.ts"; | |
| 18 | import { fill, len, split } from "../ui/layout.ts"; | |
| 19 | import { field } from "../ui/widgets.ts"; | |
| 20 | import { ListState, drawList, type ListRow } from "./common.ts"; | |
| 21 | ||
| 22 | /** The lines above the ledger: what it is, the balance, the funds, the weekly sum. */ | |
| 23 | export function allocationLines(f: Session, repo: Repo, now = new Date()): string[] { | |
| 24 | const view = readAllocation(f.app, f.user, repo, now); | |
| 25 | if (!view.ok) return ["No such repository."]; | |
| 26 | const w = view.value; | |
| 27 | return [ | |
| 28 | ALLOCATION_SAYS, | |
| 29 | `Balance ${unitsText(w.balance.total)}: subscription ${unitsText(w.balance.subscription)} (expires ${w.resetsAt.slice(0, 10)} 00:00 UTC), cash ${unitsText(w.balance.cash)}. Weekly ${unitsText(w.weeklyUnits)}.`, | |
| 30 | ]; | |
| 31 | } | |
| 32 | ||
| 33 | interface Form { | |
| 34 | readonly kind: "move" | "weekly"; | |
| 35 | readonly labels: readonly string[]; | |
| 36 | readonly values: string[]; | |
| 37 | index: number; | |
| 38 | } | |
| 39 | ||
| 40 | /** One ledger row, whole: when, what, fund, bet; the signed amount at the right. */ | |
| 41 | export const entryRow = (e: { at: string; kind: keyof typeof KIND_WORDS; fund: string; bet: string | null; units: number; runId: string | null }): ListRow => ({ | |
| 42 | title: `${e.at.slice(0, 16).replace("T", " ")} ${KIND_WORDS[e.kind]}${e.runId !== null ? ` ${e.runId.slice(-6)}` : ""} ${e.fund} ${e.bet ?? "pool"}`, | |
| 43 | meta: signed(e.units), | |
| 44 | }); | |
| 45 | ||
| 46 | export function allocationScreen(f: Session, ctx: Pick<Ctx, "toast" | "setCursor" | "theme">, repo: Repo): Screen { | |
| 47 | const state = new ListState(); | |
| 48 | const admin = (): boolean => canAdmin(f.db, repo, f.user); | |
| 49 | let form: Form | undefined; | |
| 50 | let error: string | undefined; | |
| 51 | const rows = (): ListRow[] => { | |
| 52 | const view = readAllocation(f.app, f.user, repo); | |
| 53 | return view.ok ? view.value.entries.map(entryRow) : []; | |
| 54 | }; | |
| 55 | const open = (kind: Form["kind"]): void => { | |
| 56 | error = undefined; | |
| 57 | const view = readAllocation(f.app, f.user, repo); | |
| 58 | form = | |
| 59 | kind === "move" | |
| 60 | ? { kind, labels: ["Amount (list-price dollars)", "To repository (blank: this one)", "Into bet (blank: the pool)", "From bet (blank: the pool)"], values: ["", "", "", ""], index: 0 } | |
| 61 | : { kind, labels: ["Dollars each week"], values: [view.ok ? unitsExact(view.value.weeklyUnits) : ""], index: 0 }; | |
| 62 | }; | |
| 63 | const submit = (): void => { | |
| 64 | if (form === undefined) return; | |
| 65 | const v = form.values.map((x) => x.trim()); | |
| 66 | const blank = (x: string | undefined): string | null => (x === undefined || x === "" ? null : x); | |
| 67 | const units = parseUnits(v[0] ?? ""); | |
| 68 | if (form.kind === "weekly") { | |
| 69 | const set = units === undefined ? undefined : setWeeklyAllocation(f.app, f.user, repo, units); | |
| 70 | if (set === undefined) error = WEEKLY_SAYS.invalid_amount; | |
| 71 | else if (!set.ok) error = set.error === "not_found" ? "Not allowed." : WEEKLY_SAYS[set.error]; | |
| 72 | else { | |
| 73 | ctx.toast(`Weekly allocation is ${unitsText(set.value.weeklyUnits)}.`, "success"); | |
| 74 | form = undefined; | |
| 75 | } | |
| 76 | return; | |
| 77 | } | |
| 78 | if (units === undefined) { | |
| 79 | error = MOVE_SAYS.invalid_amount; | |
| 80 | return; | |
| 81 | } | |
| 82 | const moved = moveFunds(f.app, f.user, repo, { units, toRepo: blank(v[1]), toBet: blank(v[2]), fromBet: blank(v[3]) }); | |
| 83 | if (!moved.ok) error = moved.error === "not_found" ? "Not allowed." : MOVE_SAYS[moved.error]; | |
| 84 | else { | |
| 85 | ctx.toast(`Moved ${unitsText(units)} of allocation.`, "success"); | |
| 86 | form = undefined; | |
| 87 | } | |
| 88 | }; | |
| 89 | return { | |
| 90 | title: `${repo.ownerName}/${repo.name} — Allocation`, | |
| 91 | get keys() { | |
| 92 | return form !== undefined | |
| 93 | ? [binding(["tab"], "next field"), binding(["enter"], "save"), binding(["esc"], "discard")] | |
| 94 | : [binding(["j", "k"], "move cursor"), ...(admin() ? [binding(["m"], "move funds"), binding(["w"], "set the week")] : [])]; | |
| 95 | }, | |
| 96 | render(area, s) { | |
| 97 | const c = ctx.theme.c; | |
| 98 | const lines = allocationLines(f, repo); | |
| 99 | if (form !== undefined) { | |
| 100 | const [says, rest] = split(area, "v", [len(1), fill(1)]); | |
| 101 | s.text(says!.x, says!.y, truncate(lines[1] ?? "", says!.w), style(c.fg, c.bg), says!.x + says!.w); | |
| 102 | let y = rest!.y; | |
| 103 | let cursor = null; | |
| 104 | form.labels.forEach((label, i) => { | |
| 105 | const at = field(s, { x: rest!.x, y, w: rest!.w, h: 3 }, c, { | |
| 106 | label, | |
| 107 | value: form!.values[i] ?? "", | |
| 108 | focused: i === form!.index, | |
| 109 | ...(i === form!.index ? { cursor: [...(form!.values[i] ?? "")].length } : {}), | |
| 110 | ...(i === form!.labels.length - 1 && error !== undefined ? { error } : {}), | |
| 111 | }); | |
| 112 | if (i === form!.index) cursor = at; | |
| 113 | y += 3; | |
| 114 | }); | |
| 115 | ctx.setCursor(cursor); | |
| 116 | return; | |
| 117 | } | |
| 118 | const [says, bal, list] = split(area, "v", [len(1), len(1), fill(1)]); | |
| 119 | s.text(says!.x, says!.y, truncate(lines[0] ?? "", says!.w), style(c.mutedFg, c.bg), says!.x + says!.w); | |
| 120 | s.text(bal!.x, bal!.y, truncate(lines[1] ?? "", bal!.w), style(c.fg, c.bg), bal!.x + bal!.w); | |
| 121 | drawList(s, list!, c, state, rows()); | |
| 122 | }, | |
| 123 | paste(text) { | |
| 124 | if (form === undefined) return false; | |
| 125 | form.values[form.index] = (form.values[form.index] ?? "") + text.replace(/\s+/g, " ").trim(); | |
| 126 | return true; | |
| 127 | }, | |
| 128 | key(e) { | |
| 129 | if (form === undefined) { | |
| 130 | if (!e.ctrl && !e.alt && admin() && (e.key === "m" || e.key === "w")) { | |
| 131 | open(e.key === "m" ? "move" : "weekly"); | |
| 132 | return true; | |
| 133 | } | |
| 134 | return state.key(e, rows().length); | |
| 135 | } | |
| 136 | if (e.key === "esc") { | |
| 137 | form = undefined; | |
| 138 | return true; | |
| 139 | } | |
| 140 | if (e.key === "tab") { | |
| 141 | form.index = (form.index + 1) % form.labels.length; | |
| 142 | return true; | |
| 143 | } | |
| 144 | if (e.key === "enter") { | |
| 145 | if (form.index < form.labels.length - 1) form.index += 1; | |
| 146 | else submit(); | |
| 147 | return true; | |
| 148 | } | |
| 149 | if (e.key === "backspace") { | |
| 150 | form.values[form.index] = [...(form.values[form.index] ?? "")].slice(0, -1).join(""); | |
| 151 | error = undefined; | |
| 152 | return true; | |
| 153 | } | |
| 154 | if (!e.ctrl && !e.alt && [...e.key].length === 1) { | |
| 155 | form.values[form.index] = (form.values[form.index] ?? "") + e.key; | |
| 156 | error = undefined; | |
| 157 | return true; | |
| 158 | } | |
| 159 | return false; | |
| 160 | }, | |
| 161 | }; | |
| 162 | } | |
| 163 | ||
| 164 | /** "owner/name — Allocation" while a repository is open, to whoever may read it. */ | |
| 165 | export function allocationCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] { | |
| 166 | if (repo === undefined) return []; | |
| 167 | return [ | |
| 168 | { | |
| 169 | id: "allocation", | |
| 170 | title: `${repo.ownerName}/${repo.name} — Allocation`, | |
| 171 | hint: "its balance and ledger; an admin moves funds and sets the week", | |
| 172 | run: () => ctx.push(allocationScreen(f, ctx, repo)), | |
| 173 | }, | |
| 174 | ]; | |
| 175 | } |
src/tui/screens/workspace.ts +2
| @@ -216,6 +216,7 @@ import { cutOverCommands } from "./cutover.ts"; | ||
| 216 | 216 | import { outsideAgentsCommands } from "./outsideagents.ts"; |
| 217 | 217 | import { crewSwitchCommands } from "./crewswitch.ts"; |
| 218 | 218 | import { walletCapCommands } from "./wallet.ts"; |
| 219 | import { allocationCommands } from "./allocation.ts"; | |
| 219 | 220 | import { settingHistoryCommands } from "./settinghistory.ts"; |
| 220 | 221 | import { templateCommands } from "./template.ts"; |
| 221 | 222 | import { buildCacheCommands } from "./buildcache.ts"; |
| @@ -2449,6 +2450,7 @@ export function workspaceScreen( | ||
| 2449 | 2450 | ...cutOverCommands(f, ctx, repo), |
| 2450 | 2451 | ...crewSwitchCommands(f, ctx, repo), |
| 2451 | 2452 | ...walletCapCommands(f, ctx, repo), |
| 2453 | ...allocationCommands(f, ctx, repo), | |
| 2452 | 2454 | ...templateCommands(f, ctx, repo), |
| 2453 | 2455 | ...settingHistoryCommands(f, ctx, repo), |
| 2454 | 2456 | ...buildCacheCommands(f, ctx, repo), |
src/web/pages/allocation.ts added +146
| @@ -0,0 +1,146 @@ | ||
| 1 | /** | |
| 2 | * A repository's allocation 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/allocation; POST …/allocation/move and …/allocation/weekly. | |
| 6 | */ | |
| 7 | ||
| 8 | import { MOVE_SAYS, WEEKLY_SAYS, moveFunds, readAllocation, setWeeklyAllocation, ALLOCATION_SAYS } from "../../actions/allocation.ts"; | |
| 9 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 10 | import { canAdmin, type Repo } from "../../core/repos.ts"; | |
| 11 | import { KIND_WORDS, parseUnits, signed, unitsExact, unitsText, type Entry } from "../../core/allocation.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 { emptyNote } from "../empty_words.ts"; | |
| 16 | import { html, type Html } from "../html.ts"; | |
| 17 | import { flashTo, page } from "../layout.ts"; | |
| 18 | import { btn, field } from "../ui.ts"; | |
| 19 | ||
| 20 | function ledgerTable(entries: readonly Entry[]): Html { | |
| 21 | if (entries.length === 0) return html`${emptyNote("nothingHasHappenedHereYet")}`; | |
| 22 | return html`<div class="table-scroll"> | |
| 23 | <table class="table" data-dense aria-label="Ledger, newest first"> | |
| 24 | <thead> | |
| 25 | <tr> | |
| 26 | <th scope="col">When (UTC)</th> | |
| 27 | <th scope="col">What</th> | |
| 28 | <th scope="col">Fund</th> | |
| 29 | <th scope="col">Bet</th> | |
| 30 | <th scope="col" class="num">Units, list price</th> | |
| 31 | </tr> | |
| 32 | </thead> | |
| 33 | <tbody> | |
| 34 | ${entries.map( | |
| 35 | (e) => html`<tr> | |
| 36 | <td>${e.at.slice(0, 16).replace("T", " ")}</td> | |
| 37 | <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> | |
| 38 | <td>${e.fund}</td> | |
| 39 | <td>${e.bet ?? "—"}</td> | |
| 40 | <td class="num">${signed(e.units)}</td> | |
| 41 | </tr>`, | |
| 42 | )} | |
| 43 | </tbody> | |
| 44 | </table> | |
| 45 | </div>`; | |
| 46 | } | |
| 47 | ||
| 48 | // GET /:owner/:name/allocation | |
| 49 | export function allocationPage(ctx: Ctx): Response { | |
| 50 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 51 | const repo = loadRepo(ctx); | |
| 52 | if (!repo) return repoNotFound(ctx); | |
| 53 | const view = readAllocation(ctx.app, ctx.auth.user, repo); | |
| 54 | if (!view.ok) return repoNotFound(ctx); | |
| 55 | const w = view.value; | |
| 56 | const base = repoBase(repo); | |
| 57 | const admin = canAdmin(ctx.app.db, repo, ctx.auth.user); | |
| 58 | const forms = !admin | |
| 59 | ? null | |
| 60 | : html`<section class="settings-block"> | |
| 61 | <h2>Move allocation</h2> | |
| 62 | <form method="post" action="${base}/allocation/move"> | |
| 63 | ${field({ label: "Amount (list-price dollars)", name: "amount", type: "text", required: true, mono: true })} | |
| 64 | ${field({ label: "From bet (blank: the pool)", name: "from_bet", type: "text", mono: true })} | |
| 65 | ${field({ label: "To repository (blank: this one)", name: "to_repo", type: "text", mono: true, placeholder: `${repo.ownerName}/${repo.name}` })} | |
| 66 | ${field({ label: "Into bet (blank: the pool)", name: "to_bet", type: "text", mono: true })} | |
| 67 | <div class="form-actions">${btn("Move", { variant: "primary" })}</div> | |
| 68 | </form> | |
| 69 | </section> | |
| 70 | <section class="settings-block"> | |
| 71 | <h2>Weekly allocation</h2> | |
| 72 | <form method="post" action="${base}/allocation/weekly"> | |
| 73 | ${field({ label: "Dollars each week", name: "weekly", type: "text", required: true, mono: true, value: unitsExact(w.weeklyUnits) })} | |
| 74 | <div class="form-actions">${btn("Save", { variant: "primary" })}</div> | |
| 75 | </form> | |
| 76 | </section>`; | |
| 77 | const rendering = performance.now(); | |
| 78 | const response = page({ | |
| 79 | ctx, | |
| 80 | title: `Allocation · ${repo.ownerName}/${repo.name}`, | |
| 81 | crumbs: crumbsFor(repo), | |
| 82 | body: html`${repoHeader(ctx, repo, "none", { compact: true })} | |
| 83 | <p class="muted" id="allocation-says">${ALLOCATION_SAYS}</p> | |
| 84 | <section class="settings-block"> | |
| 85 | <h2>Allocation</h2> | |
| 86 | <dl> | |
| 87 | <dt>Balance</dt> | |
| 88 | <dd id="allocation-total"><b>${unitsText(w.balance.total)}</b></dd> | |
| 89 | <dt>Subscription</dt> | |
| 90 | <dd>${unitsText(w.balance.subscription)}, expires ${w.resetsAt.slice(0, 10)}</dd> | |
| 91 | <dt>Cash</dt> | |
| 92 | <dd>${unitsText(w.balance.cash)}</dd> | |
| 93 | <dt>Each week</dt> | |
| 94 | <dd>${unitsText(w.weeklyUnits)}</dd> | |
| 95 | ${w.bets.map((b) => html`<dt>Bet ${b.bet}</dt><dd>${unitsText(b.balance.total)}</dd>`)} | |
| 96 | </dl> | |
| 97 | </section> | |
| 98 | ${forms} | |
| 99 | <section class="settings-block"> | |
| 100 | <h2>Ledger</h2> | |
| 101 | ${ledgerTable(w.entries)} | |
| 102 | </section>`, | |
| 103 | }); | |
| 104 | notePhase(ctx.request, "render", performance.now() - rendering); | |
| 105 | return response; | |
| 106 | } | |
| 107 | ||
| 108 | async function allocationForm(ctx: Ctx): Promise<{ repo: Repo; form: Form } | Response> { | |
| 109 | const repo = loadRepo(ctx); | |
| 110 | if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return repoNotFound(ctx); | |
| 111 | const form = await readForm(ctx, "admin"); | |
| 112 | if (form instanceof Response) return form; | |
| 113 | return { repo, form }; | |
| 114 | } | |
| 115 | ||
| 116 | // POST /:owner/:name/allocation/move | |
| 117 | export async function allocationMove(ctx: Ctx): Promise<Response> { | |
| 118 | const gate = await allocationForm(ctx); | |
| 119 | if (gate instanceof Response) return gate; | |
| 120 | const { repo, form } = gate; | |
| 121 | const back = `${repoBase(repo)}/allocation`; | |
| 122 | const units = parseUnits(formField(form, "amount")); | |
| 123 | if (units === undefined) return flashTo(ctx, back, { tone: "danger", message: MOVE_SAYS.invalid_amount }); | |
| 124 | const blank = (s: string): string | null => (s.trim() === "" ? null : s.trim()); | |
| 125 | const moved = moveFunds(ctx.app, ctx.auth.user, repo, { | |
| 126 | units, | |
| 127 | fromBet: blank(formField(form, "from_bet")), | |
| 128 | toRepo: blank(formField(form, "to_repo")), | |
| 129 | toBet: blank(formField(form, "to_bet")), | |
| 130 | }); | |
| 131 | if (!moved.ok) return flashTo(ctx, back, { tone: "danger", message: moved.error === "not_found" ? "Not allowed." : MOVE_SAYS[moved.error] }); | |
| 132 | return flashTo(ctx, back, { message: `Moved ${unitsText(units)} of allocation.` }); | |
| 133 | } | |
| 134 | ||
| 135 | // POST /:owner/:name/allocation/weekly | |
| 136 | export async function allocationWeekly(ctx: Ctx): Promise<Response> { | |
| 137 | const gate = await allocationForm(ctx); | |
| 138 | if (gate instanceof Response) return gate; | |
| 139 | const { repo, form } = gate; | |
| 140 | const back = `${repoBase(repo)}/allocation`; | |
| 141 | const units = parseUnits(formField(form, "weekly")); | |
| 142 | const set = units === undefined ? undefined : setWeeklyAllocation(ctx.app, ctx.auth.user, repo, units); | |
| 143 | if (set === undefined) return flashTo(ctx, back, { tone: "danger", message: WEEKLY_SAYS.invalid_amount }); | |
| 144 | if (!set.ok) return flashTo(ctx, back, { tone: "danger", message: set.error === "not_found" ? "Not allowed." : WEEKLY_SAYS[set.error] }); | |
| 145 | return flashTo(ctx, back, { message: `Weekly allocation is ${unitsText(set.value.weeklyUnits)}.` }); | |
| 146 | } |
src/web/studio/crew.ts +6
| @@ -36,6 +36,7 @@ import { governorRows, weekCardDl } from "./governor_rows.ts"; | ||
| 36 | 36 | import { crewOffInPreview } from "../../crew/preview.ts"; |
| 37 | 37 | import type { Ctx } from "../../http/context.ts"; |
| 38 | 38 | import { repoBase } from "../chrome.ts"; |
| 39 | import { balanceNow, ceilingUsd, unitsText } from "../../core/allocation.ts"; | |
| 39 | 40 | import { html, type Html } from "../html.ts"; |
| 40 | 41 | import { blockedWay } from "../blocked.ts"; |
| 41 | 42 | import { noAgentsBlocked } from "../../actions/blocked_words.ts"; |
| @@ -351,6 +352,11 @@ function autonomyCard(ctx: Ctx, repo: Repo, base: string, admin: boolean): Html | ||
| 351 | 352 | ${weekCardDl(status.week)} |
| 352 | 353 | <dt>Today</dt> |
| 353 | 354 | <dd>$${status.spentTodayUsd.toFixed(2)} spent</dd> |
| 355 | <dt>Allocation</dt> | |
| 356 | <dd> | |
| 357 | ${unitsText(balanceNow(ctx.app.db, repo.id, ceilingUsd(ctx.app.db, repo.id), new Date()).total)} left | |
| 358 | · <a href="${base}/allocation">allocation and ledger</a> | |
| 359 | </dd> | |
| 354 | 360 | <dt>Slots</dt> |
| 355 | 361 | <dd>${status.active} of ${status.slots} in use</dd> |
| 356 | 362 | ${governorRows(governor)} |
test/allocation-dispatch.test.ts added +86
| @@ -0,0 +1,86 @@ | ||
| 1 | /** | |
| 2 | * The allocation gates every run that starts (#8718): an assignment as much as the crew's own pick, | |
| 3 | * and a run on a scope of a bet that holds an envelope asks that envelope and is paid from it. | |
| 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 { moveFunds } from "../src/actions/allocation.ts"; | |
| 10 | import { addToCrew, createAgent } from "../src/actions/crew.ts"; | |
| 11 | import { openIssue } from "../src/actions/issues.ts"; | |
| 12 | import { createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { getAgent, type Agent } from "../src/core/agents.ts"; | |
| 15 | import { balanceOf, settle, UNIT } from "../src/core/allocation.ts"; | |
| 16 | import { insertBet, markBacked } from "../src/core/bets.ts"; | |
| 17 | import { getIssueById, type Issue } from "../src/core/issues.ts"; | |
| 18 | import { getRepoById, type Repo } from "../src/core/repos.ts"; | |
| 19 | import { claimRun, finishRun } from "../src/core/runs.ts"; | |
| 20 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 21 | import { queueAgentRun } from "../src/crew/dispatch.ts"; | |
| 22 | import { quietLogs } from "./helpers/globals.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | let dir = ""; | |
| 27 | let app: App; | |
| 28 | let alice: User; | |
| 29 | let bot: Agent; | |
| 30 | let repo: Repo; | |
| 31 | let made = 0; | |
| 32 | ||
| 33 | const fresh = (): Repo => getRepoById(app.db, repo.id)!; | |
| 34 | const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => { | |
| 35 | if (!r.ok) throw new Error(JSON.stringify(r.error)); | |
| 36 | return r.value; | |
| 37 | }; | |
| 38 | const issue = (): Issue => { | |
| 39 | const i = ok(openIssue(app, alice, fresh(), { title: `Work ${++made}` })); | |
| 40 | app.db.query("UPDATE issue SET assignee_id = ?1 WHERE id = ?2").run(bot.user.id, i.id); | |
| 41 | return getIssueById(app.db, i.id)!; | |
| 42 | }; | |
| 43 | const ceiling = (usd: number): void => void app.db.query("UPDATE repo SET autonomy_ceiling_usd = ?2 WHERE id = ?1").run(repo.id, usd); | |
| 44 | ||
| 45 | beforeAll(async () => { | |
| 46 | dir = await mkdtemp(join(tmpdir(), "forge-allocation-dispatch-")); | |
| 47 | app = createApp({ dataDir: dir, port: 0 }); | |
| 48 | alice = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true })); | |
| 49 | ok(await createAgent(app, alice, { username: "bot" })); | |
| 50 | repo = ok(await createRepo(app, alice, { name: "gate", visibility: "public" })); | |
| 51 | expect(addToCrew(app, alice, repo, "bot").ok).toBe(true); | |
| 52 | bot = getAgent(app.db, getUserByName(app.db, "bot")!.id)!; | |
| 53 | }, 30_000); | |
| 54 | ||
| 55 | afterAll(async () => { | |
| 56 | app?.close(); | |
| 57 | await rm(dir, { recursive: true, force: true }); | |
| 58 | }); | |
| 59 | ||
| 60 | test("an assignment starts only with allocation: empty, nothing is queued; funded, it is", () => { | |
| 61 | ceiling(0); | |
| 62 | expect(queueAgentRun(app, fresh(), issue(), bot, "assigned", alice.id)).toBeUndefined(); | |
| 63 | ceiling(20); | |
| 64 | expect(queueAgentRun(app, fresh(), issue(), bot, "assigned", alice.id)?.state).toBe("queued"); | |
| 65 | }); | |
| 66 | ||
| 67 | test("a bet's run is paid from its envelope, and an empty envelope stops its scopes though the pool is full", () => { | |
| 68 | ceiling(20); | |
| 69 | settle(app.db, repo.id, 20, new Date()); | |
| 70 | const first = issue(); | |
| 71 | const second = issue(); | |
| 72 | const bet = insertBet(app.db, { repoId: repo.id, name: "Ship It", journeys: "", appetite: 10, leadId: null, issueIds: [first.id, second.id] }, new Date()); | |
| 73 | markBacked(app.db, bet.id, 10, "owner", new Date()); | |
| 74 | expect(moveFunds(app, alice, fresh(), { units: 2 * UNIT, fromBet: null, toRepo: null, toBet: "ship-it" }).ok).toBe(true); | |
| 75 | const pool = balanceOf(app.db, repo.id).total; | |
| 76 | ||
| 77 | const run = queueAgentRun(app, fresh(), first, bot, "assigned", alice.id); | |
| 78 | expect(run?.state).toBe("queued"); | |
| 79 | claimRun(app.db, run!.id); | |
| 80 | finishRun(app.db, run!.id, { state: "ok", summary: "done", costUsd: 2 }); | |
| 81 | settle(app.db, repo.id, 20, new Date()); | |
| 82 | ||
| 83 | expect(balanceOf(app.db, repo.id, "ship-it").total).toBe(0); | |
| 84 | expect(balanceOf(app.db, repo.id).total).toBe(pool); | |
| 85 | expect(queueAgentRun(app, fresh(), second, bot, "assigned", alice.id)).toBeUndefined(); | |
| 86 | }); |
test/allocation.test.ts added +437
| @@ -0,0 +1,437 @@ | ||
| 1 | /** | |
| 2 | * A repository's allocation (#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, readAllocation, setWeeklyAllocation } from "../src/actions/allocation.ts"; | |
| 12 | import { openIssue } from "../src/actions/issues.ts"; | |
| 13 | import { createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import type { Repo } from "../src/core/repos.ts"; | |
| 16 | import { createRun } from "../src/core/runs.ts"; | |
| 17 | import type { User } from "../src/core/users.ts"; | |
| 18 | import type { Database } from "bun:sqlite"; | |
| 19 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 20 | import { | |
| 21 | balanceOf, | |
| 22 | ceilingUsd, | |
| 23 | ledger, | |
| 24 | mayStart, | |
| 25 | moveUnits, | |
| 26 | parseUnits, | |
| 27 | settle, | |
| 28 | toUnits, | |
| 29 | UNIT, | |
| 30 | unitsText, | |
| 31 | unitsExact, | |
| 32 | envelopeOf, | |
| 33 | weekStart, | |
| 34 | } from "../src/core/allocation.ts"; | |
| 35 | import { insertBet, markBacked } from "../src/core/bets.ts"; | |
| 36 | import { Session } from "../src/tui/session.ts"; | |
| 37 | import type { KeyEvent } from "../src/tui/term/input.ts"; | |
| 38 | import { theme } from "../src/tui/ui/theme.ts"; | |
| 39 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 40 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 41 | import { createSession } from "../src/core/sessions.ts"; | |
| 42 | ||
| 43 | // A Wednesday; its week opens Monday 2026-10-05 and the next opens 2026-10-12. | |
| 44 | const WED = new Date("2026-10-07T12:00:00Z"); | |
| 45 | const NEXT_WED = new Date("2026-10-14T12:00:00Z"); | |
| 46 | ||
| 47 | let dataDir = ""; | |
| 48 | let app: App; | |
| 49 | let servers: Servers; | |
| 50 | let alice: User; | |
| 51 | let cookie = ""; | |
| 52 | let n = 0; | |
| 53 | ||
| 54 | const atCeiling = (db: Database, repo: { id: string }, now: Date): boolean => !mayStart(db, repo.id, ceilingUsd(db, repo.id), now).ok; | |
| 55 | ||
| 56 | const mint = async (ceilingUsd: number): Promise<Repo> => { | |
| 57 | const made = await createRepo(app, alice, { name: `w${n++}`, visibility: "private" }); | |
| 58 | if (!made.ok) throw new Error(String(made.error)); | |
| 59 | app.db.query("UPDATE repo SET autonomy_ceiling_usd = ?2 WHERE id = ?1").run(made.value.id, ceilingUsd); | |
| 60 | return made.value; | |
| 61 | }; | |
| 62 | const spend = (repo: Repo, usd: number) => { | |
| 63 | const run = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: alice.id }); | |
| 64 | app.db.query("UPDATE run SET cost_usd = ?2, state = 'ok' WHERE id = ?1").run(run.id, usd); | |
| 65 | }; | |
| 66 | const sum = (repo: Repo): number => | |
| 67 | app.db.query<{ n: number }, [string]>("SELECT COALESCE(SUM(units),0) AS n FROM allocation_entry WHERE repo_id = ?1").get(repo.id)!.n; | |
| 68 | ||
| 69 | beforeAll(async () => { | |
| 70 | dataDir = await mkdtemp(join(tmpdir(), "forge-allocation-")); | |
| 71 | app = createApp({ dataDir, port: 0 }); | |
| 72 | servers = await serve(app); | |
| 73 | const made = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 74 | if (!made.ok) throw new Error(made.error); | |
| 75 | alice = made.value; | |
| 76 | cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 77 | }); | |
| 78 | ||
| 79 | afterAll(async () => { | |
| 80 | servers.stop(); | |
| 81 | app.close(); | |
| 82 | await rm(dataDir, { recursive: true, force: true }); | |
| 83 | }); | |
| 84 | ||
| 85 | describe("units", () => { | |
| 86 | test("dollars become integers by digits, never floats", () => { | |
| 87 | expect(parseUnits("12.5")).toBe(12_500_000); | |
| 88 | expect(parseUnits("0.000001")).toBe(1); | |
| 89 | expect(parseUnits("1e3")).toBeUndefined(); | |
| 90 | expect(parseUnits("-1")).toBeUndefined(); | |
| 91 | expect(parseUnits("1.1234567")).toBeUndefined(); | |
| 92 | expect(toUnits(0.1 + 0.2)).toBe(300_000); | |
| 93 | expect(unitsText(12_345_678)).toBe("$12.34"); | |
| 94 | expect(unitsText(-5 * UNIT)).toBe("-$5.00"); | |
| 95 | }); | |
| 96 | test("the week opens on a UTC Monday", () => { | |
| 97 | expect(weekStart(WED).toISOString()).toBe("2026-10-05T00:00:00.000Z"); | |
| 98 | expect(weekStart(new Date("2026-10-11T23:59:59Z")).toISOString()).toBe("2026-10-05T00:00:00.000Z"); | |
| 99 | }); | |
| 100 | }); | |
| 101 | ||
| 102 | describe("the ledger", () => { | |
| 103 | test("an existing daily ceiling carries over as seven days of allocation", async () => { | |
| 104 | const repo = await mint(20); | |
| 105 | settle(app.db, repo.id, 20, WED); | |
| 106 | expect(balanceOf(app.db, repo.id).total).toBe(140 * UNIT); | |
| 107 | expect(ledger(app.db, repo.id).map((e) => e.kind)).toEqual(["weekly"]); | |
| 108 | }); | |
| 109 | ||
| 110 | test("settling twice appends nothing more: the same state gives the same ledger", async () => { | |
| 111 | const repo = await mint(2); | |
| 112 | spend(repo, 1.5); | |
| 113 | settle(app.db, repo.id, 2, WED); | |
| 114 | const once = ledger(app.db, repo.id); | |
| 115 | settle(app.db, repo.id, 2, WED); | |
| 116 | expect(ledger(app.db, repo.id)).toEqual(once); | |
| 117 | }); | |
| 118 | ||
| 119 | test("each run's cost is an entry at list price, and the balance is the sum of the entries", async () => { | |
| 120 | const repo = await mint(1); | |
| 121 | spend(repo, 1.25); | |
| 122 | spend(repo, 0.5); | |
| 123 | settle(app.db, repo.id, 1, WED); | |
| 124 | const b = balanceOf(app.db, repo.id); | |
| 125 | expect(b.total).toBe(7 * UNIT - 1_250_000 - 500_000); | |
| 126 | expect(b.total).toBe(sum(repo)); | |
| 127 | expect(ledger(app.db, repo.id).filter((e) => e.kind === "run").map((e) => e.units).sort()).toEqual([-1_250_000, -500_000]); | |
| 128 | }); | |
| 129 | ||
| 130 | test("entries are append only", async () => { | |
| 131 | const repo = await mint(1); | |
| 132 | settle(app.db, repo.id, 1, WED); | |
| 133 | expect(() => app.db.query("UPDATE allocation_entry SET units = 1 WHERE repo_id = ?1").run(repo.id)).toThrow(/append only/); | |
| 134 | expect(() => app.db.query("DELETE FROM allocation_entry WHERE repo_id = ?1").run(repo.id)).toThrow(/append only/); | |
| 135 | }); | |
| 136 | ||
| 137 | test("subscription funds expire at the weekly reset; cash keeps", async () => { | |
| 138 | const repo = await mint(1); | |
| 139 | settle(app.db, repo.id, 1, WED); | |
| 140 | app.db | |
| 141 | .query("INSERT INTO allocation_entry (repo_id, kind, fund, units, at) VALUES (?1, 'grant', 'cash', ?2, ?3)") | |
| 142 | .run(repo.id, 3 * UNIT, WED.toISOString()); | |
| 143 | settle(app.db, repo.id, 1, NEXT_WED); | |
| 144 | const b = balanceOf(app.db, repo.id); | |
| 145 | expect(b.subscription).toBe(7 * UNIT); // last week's expired, this week's refilled | |
| 146 | expect(b.cash).toBe(3 * UNIT); | |
| 147 | expect(ledger(app.db, repo.id).some((e) => e.kind === "expiry" && e.units === -7 * UNIT)).toBe(true); | |
| 148 | expect(b.total).toBe(sum(repo)); | |
| 149 | }); | |
| 150 | ||
| 151 | test("a run is paid from the subscription fund first, then cash", async () => { | |
| 152 | const repo = await mint(1); | |
| 153 | settle(app.db, repo.id, 1, WED); | |
| 154 | app.db | |
| 155 | .query("INSERT INTO allocation_entry (repo_id, kind, fund, units, at) VALUES (?1, 'grant', 'cash', ?2, ?3)") | |
| 156 | .run(repo.id, 5 * UNIT, WED.toISOString()); | |
| 157 | spend(repo, 9); | |
| 158 | settle(app.db, repo.id, 1, WED); | |
| 159 | const b = balanceOf(app.db, repo.id); | |
| 160 | expect(b.subscription).toBe(0); | |
| 161 | expect(b.cash).toBe(3 * UNIT); | |
| 162 | }); | |
| 163 | }); | |
| 164 | ||
| 165 | describe("a run starts only with funds", () => { | |
| 166 | test("empty allocation: no run, in one line; refilled by the reset", async () => { | |
| 167 | const repo = await mint(1); | |
| 168 | expect(mayStart(app.db, repo.id, 1, WED).ok).toBe(true); | |
| 169 | spend(repo, 7); | |
| 170 | expect(atCeiling(app.db, repo, WED)).toBe(true); | |
| 171 | const no = mayStart(app.db, repo.id, 1, WED); | |
| 172 | expect(no.ok).toBe(false); | |
| 173 | if (!no.ok) { | |
| 174 | expect(no.says.split("\n")).toHaveLength(1); | |
| 175 | expect(no.says).toContain("allocation is empty"); | |
| 176 | expect(no.says).toContain("2026-10-12"); | |
| 177 | } | |
| 178 | expect(atCeiling(app.db, repo, NEXT_WED)).toBe(false); | |
| 179 | }); | |
| 180 | ||
| 181 | test("a bet runs on its own envelope", async () => { | |
| 182 | const repo = await mint(1); | |
| 183 | settle(app.db, repo.id, 1, WED); | |
| 184 | expect(mayStart(app.db, repo.id, 1, WED, "ship-it").ok).toBe(false); | |
| 185 | const moved = moveFunds(app, alice, repo, { units: 2 * UNIT, fromBet: null, toRepo: null, toBet: "ship-it" }, WED); | |
| 186 | expect(moved.ok).toBe(true); | |
| 187 | expect(mayStart(app.db, repo.id, 1, WED, "ship-it").ok).toBe(true); | |
| 188 | expect(balanceOf(app.db, repo.id, "ship-it").total).toBe(2 * UNIT); | |
| 189 | expect(balanceOf(app.db, repo.id).total).toBe(5 * UNIT); | |
| 190 | }); | |
| 191 | }); | |
| 192 | ||
| 193 | describe("moving funds", () => { | |
| 194 | test("between repositories conserves the total, and keeps the funds' kind", async () => { | |
| 195 | const a = await mint(1); | |
| 196 | const b = await mint(1); | |
| 197 | settle(app.db, a.id, 1, WED); | |
| 198 | settle(app.db, b.id, 1, WED); | |
| 199 | const before = sum(a) + sum(b); | |
| 200 | const moved = moveFunds(app, alice, a, { units: 1_000_001, fromBet: null, toRepo: `${b.ownerName}/${b.name}`, toBet: null }, WED); | |
| 201 | expect(moved.ok).toBe(true); | |
| 202 | expect(sum(a) + sum(b)).toBe(before); | |
| 203 | expect(balanceOf(app.db, a.id).total).toBe(7 * UNIT - 1_000_001); | |
| 204 | expect(balanceOf(app.db, b.id).subscription).toBe(7 * UNIT + 1_000_001); | |
| 205 | expect(balanceOf(app.db, b.id).cash).toBe(0); | |
| 206 | }); | |
| 207 | ||
| 208 | test("refuses more than the allocation holds, nonsense amounts and bad names, changing nothing", async () => { | |
| 209 | const a = await mint(1); | |
| 210 | settle(app.db, a.id, 1, WED); | |
| 211 | const before = sum(a); | |
| 212 | const bad = (units: number, toBet: string | null) => | |
| 213 | moveFunds(app, alice, a, { units, fromBet: null, toRepo: null, toBet }, WED); | |
| 214 | expect(bad(8 * UNIT, "x")).toEqual({ ok: false, error: "insufficient" }); | |
| 215 | expect(bad(0, "x")).toEqual({ ok: false, error: "invalid_amount" }); | |
| 216 | expect(bad(1.5, "x")).toEqual({ ok: false, error: "invalid_amount" }); | |
| 217 | expect(bad(UNIT, "Bad Name")).toEqual({ ok: false, error: "invalid_bet" }); | |
| 218 | expect(bad(UNIT, null)).toEqual({ ok: false, error: "same_place" }); | |
| 219 | expect(sum(a)).toBe(before); | |
| 220 | }); | |
| 221 | ||
| 222 | test("a move is atomic: nothing is left half done when the second entry cannot be written", async () => { | |
| 223 | const a = await mint(1); | |
| 224 | settle(app.db, a.id, 1, WED); | |
| 225 | const before = ledger(app.db, a.id).length; | |
| 226 | expect(() => | |
| 227 | moveUnits(app.db, { from: { repoId: a.id, bet: null }, to: { repoId: a.id, bet: "ok" }, units: UNIT, actorId: alice.id, now: new Date("nope") }), | |
| 228 | ).toThrow(); | |
| 229 | expect(ledger(app.db, a.id)).toHaveLength(before); | |
| 230 | }); | |
| 231 | ||
| 232 | test("only the repository's admin moves or sets, and a stranger sees nothing", async () => { | |
| 233 | const a = await mint(1); | |
| 234 | const bob = await seedAdmin(app, { username: "bob", email: "[email protected]", password: "correct-horse-battery" }); | |
| 235 | if (!bob.ok) throw new Error(bob.error); | |
| 236 | const plain = { ...bob.value, isAdmin: false }; | |
| 237 | expect(moveFunds(app, undefined, a, { units: UNIT, fromBet: null, toRepo: null, toBet: "x" }).ok).toBe(false); | |
| 238 | expect(moveFunds(app, plain, a, { units: UNIT, fromBet: null, toRepo: null, toBet: "x" }).ok).toBe(false); | |
| 239 | expect(setWeeklyAllocation(app, plain, a, UNIT).ok).toBe(false); | |
| 240 | expect(readAllocation(app, plain, a).ok).toBe(false); | |
| 241 | }); | |
| 242 | ||
| 243 | test("the weekly allocation, once set, replaces the carried ceiling", async () => { | |
| 244 | const a = await mint(20); | |
| 245 | expect(setWeeklyAllocation(app, alice, a, 10 * UNIT, WED).ok).toBe(true); | |
| 246 | expect(readAllocation(app, alice, a, WED)).toMatchObject({ ok: true, value: { weeklyUnits: 10 * UNIT } }); | |
| 247 | expect(balanceOf(app.db, a.id).total).toBe(10 * UNIT); | |
| 248 | }); | |
| 249 | }); | |
| 250 | ||
| 251 | describe("reached by a person and an agent", () => { | |
| 252 | test("the page says it is an allocation, shows the ledger, and the form moves funds", async () => { | |
| 253 | const a = await mint(1); | |
| 254 | settle(app.db, a.id, 1, new Date()); | |
| 255 | const base = servers.url; | |
| 256 | const page = await (await fetch(`${base}/${a.ownerName}/${a.name}/allocation`, { headers: { cookie } })).text(); | |
| 257 | expect(page).toContain("An allocation, not money"); | |
| 258 | expect(page).toContain("Each week"); | |
| 259 | const res = await fetch(`${base}/${a.ownerName}/${a.name}/allocation/move`, { | |
| 260 | method: "POST", | |
| 261 | redirect: "manual", | |
| 262 | headers: { cookie, origin: base, "content-type": "application/x-www-form-urlencoded" }, | |
| 263 | body: new URLSearchParams({ amount: "1.5", to_bet: "launch" }), | |
| 264 | }); | |
| 265 | expect(res.status).toBeLessThan(400); | |
| 266 | expect(balanceOf(app.db, a.id, "launch").total).toBe(1_500_000); | |
| 267 | const cross = await fetch(`${base}/${a.ownerName}/${a.name}/allocation/move`, { | |
| 268 | method: "POST", | |
| 269 | redirect: "manual", | |
| 270 | headers: { cookie, origin: "https://evil.example", "content-type": "application/x-www-form-urlencoded" }, | |
| 271 | body: new URLSearchParams({ amount: "1", to_bet: "launch" }), | |
| 272 | }); | |
| 273 | expect(cross.status).toBe(403); | |
| 274 | expect(balanceOf(app.db, a.id, "launch").total).toBe(1_500_000); | |
| 275 | const anon = await fetch(`${base}/${a.ownerName}/${a.name}/allocation`); | |
| 276 | expect(anon.status).toBe(404); | |
| 277 | }); | |
| 278 | ||
| 279 | test("the MCP tool reads, moves and sets", async () => { | |
| 280 | const a = await mint(1); | |
| 281 | settle(app.db, a.id, 1, new Date()); | |
| 282 | const minted = await fetch(`${servers.url}/api/v1/tokens`, { | |
| 283 | method: "POST", | |
| 284 | headers: { "content-type": "application/json" }, | |
| 285 | body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "mcp", scope: "admin" }), | |
| 286 | }); | |
| 287 | const token = ((await minted.json()) as { token: string }).token; | |
| 288 | const repo = `${a.ownerName}/${a.name}`; | |
| 289 | const read = await mcpTool(servers.url, token, "allocation", { repo }); | |
| 290 | expect(read.value.says).toContain("not money"); | |
| 291 | expect(read.value.balance.total).toBe(7 * UNIT); | |
| 292 | const moved = await mcpTool(servers.url, token, "allocation", { repo, move: { amount: "2", toBet: "b1" } }); | |
| 293 | expect(moved.value.says).toBe("Moved $2.00 of allocation."); | |
| 294 | const refused = await mcpTool(servers.url, token, "allocation", { repo, move: { amount: "999" } }); | |
| 295 | expect(refused.error).toBeDefined(); | |
| 296 | const set = await mcpTool(servers.url, token, "allocation", { repo, weekly: "3" }); | |
| 297 | expect(set.value.weeklyUnits).toBe(3 * UNIT); | |
| 298 | }); | |
| 299 | }); | |
| 300 | ||
| 301 | test("changing the daily ceiling mid-week moves the week's allocation, and the ledger still totals the balance", async () => { | |
| 302 | const repo = await mint(10); | |
| 303 | settle(app.db, repo.id, 10, WED); | |
| 304 | expect(balanceOf(app.db, repo.id).total).toBe(70 * UNIT); | |
| 305 | settle(app.db, repo.id, 0, WED); | |
| 306 | expect(balanceOf(app.db, repo.id).total).toBe(0); | |
| 307 | expect(mayStart(app.db, repo.id, 0, WED).ok).toBe(false); | |
| 308 | settle(app.db, repo.id, 20, WED); | |
| 309 | expect(balanceOf(app.db, repo.id).total).toBe(140 * UNIT); | |
| 310 | settle(app.db, repo.id, 20, WED); | |
| 311 | expect(ledger(app.db, repo.id).reduce((t, e) => t + e.units, 0)).toBe(140 * UNIT); | |
| 312 | }); | |
| 313 | ||
| 314 | describe("the review's findings", () => { | |
| 315 | test("a read writes nothing: only settling enters the week", async () => { | |
| 316 | const repo = await mint(1); | |
| 317 | expect(readAllocation(app, alice, repo, WED)).toMatchObject({ ok: true, value: { balance: { total: 0 } } }); | |
| 318 | expect(sum(repo)).toBe(0); | |
| 319 | expect(ledger(app.db, repo.id)).toHaveLength(0); | |
| 320 | }); | |
| 321 | ||
| 322 | test("setting the weekly sum mid-week changes the balance now, as one grant", async () => { | |
| 323 | const a = await mint(20); | |
| 324 | settle(app.db, a.id, 20, WED); | |
| 325 | expect(setWeeklyAllocation(app, alice, a, 10 * UNIT, WED).ok).toBe(true); | |
| 326 | expect(balanceOf(app.db, a.id).total).toBe(10 * UNIT); | |
| 327 | expect(setWeeklyAllocation(app, alice, a, 4 * UNIT, WED).ok).toBe(true); | |
| 328 | expect(balanceOf(app.db, a.id).total).toBe(4 * UNIT); | |
| 329 | settle(app.db, a.id, 20, WED); | |
| 330 | expect(ledger(app.db, a.id).reduce((t, e) => t + e.units, 0)).toBe(4 * UNIT); | |
| 331 | }); | |
| 332 | ||
| 333 | test("an admin who is not the forge owner lowers the weekly sum but cannot raise it", async () => { | |
| 334 | const a = await mint(1); | |
| 335 | const cara = await seedAdmin(app, { username: "cara", email: "[email protected]", password: "correct-horse-battery" }); | |
| 336 | if (!cara.ok) throw new Error(cara.error); | |
| 337 | app.db.query("UPDATE repo SET owner_id = ?2 WHERE id = ?1").run(a.id, cara.value.id); | |
| 338 | app.db.query("UPDATE user SET is_admin = 0 WHERE id = ?1").run(cara.value.id); | |
| 339 | const owner = { ...cara.value, isAdmin: false }; | |
| 340 | const repo = { ...a, ownerId: cara.value.id }; | |
| 341 | expect(setWeeklyAllocation(app, owner, repo, 3 * UNIT, WED)).toMatchObject({ ok: true }); | |
| 342 | expect(setWeeklyAllocation(app, owner, repo, 50 * UNIT, WED)).toMatchObject({ ok: false, error: "not_granted" }); | |
| 343 | expect(setWeeklyAllocation(app, alice, repo, 50 * UNIT, WED).ok).toBe(true); | |
| 344 | }); | |
| 345 | ||
| 346 | test("funds are not pushed into a repository the actor does not administer", async () => { | |
| 347 | const a = await mint(1); | |
| 348 | const dan = await seedAdmin(app, { username: "dan", email: "[email protected]", password: "correct-horse-battery" }); | |
| 349 | if (!dan.ok) throw new Error(dan.error); | |
| 350 | const theirs = await createRepo(app, alice, { name: `theirs${n++}`, visibility: "public" }); | |
| 351 | if (!theirs.ok) throw new Error(String(theirs.error)); | |
| 352 | app.db.query("UPDATE repo SET owner_id = ?2 WHERE id = ?1").run(theirs.value.id, dan.value.id); | |
| 353 | settle(app.db, a.id, 1, WED); | |
| 354 | const plainAlice = { ...alice, isAdmin: false }; | |
| 355 | const moved = moveFunds(app, plainAlice, a, { units: UNIT, fromBet: null, toRepo: `dan/${theirs.value.name}`, toBet: null }, WED); | |
| 356 | expect(moved).toMatchObject({ ok: false, error: "no_such_repo" }); | |
| 357 | }); | |
| 358 | ||
| 359 | test("a run that ended last week is paid from last week's fund, before the reset expires it", async () => { | |
| 360 | const repo = await mint(1); | |
| 361 | settle(app.db, repo.id, 1, WED); | |
| 362 | const run = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: alice.id }); | |
| 363 | app.db.query("UPDATE run SET cost_usd = 2, state = 'ok', finished_at = ?2 WHERE id = ?1").run(run.id, WED.toISOString()); | |
| 364 | settle(app.db, repo.id, 1, NEXT_WED); | |
| 365 | expect(balanceOf(app.db, repo.id).subscription).toBe(7 * UNIT); | |
| 366 | const entry = ledger(app.db, repo.id).find((e) => e.kind === "run")!; | |
| 367 | expect(entry.at).toBe(WED.toISOString()); | |
| 368 | }); | |
| 369 | ||
| 370 | test("a bet that holds an envelope is charged its runs; the pool is not", async () => { | |
| 371 | const repo = await mint(1); | |
| 372 | settle(app.db, repo.id, 1, WED); | |
| 373 | const opened = openIssue(app, alice, repo, { title: "Scope" }); | |
| 374 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 375 | const bet = insertBet(app.db, { repoId: repo.id, name: "Big Idea", journeys: "", appetite: 5, leadId: null, issueIds: [opened.value.id] }, WED); | |
| 376 | markBacked(app.db, bet.id, 5, "owner", WED); | |
| 377 | expect(envelopeOf(app.db, repo.id, opened.value.id)).toBeNull(); // no envelope yet: the pool pays | |
| 378 | expect(moveFunds(app, alice, repo, { units: 3 * UNIT, fromBet: null, toRepo: null, toBet: "big-idea" }, WED).ok).toBe(true); | |
| 379 | expect(envelopeOf(app.db, repo.id, opened.value.id)).toBe("big-idea"); | |
| 380 | const pool = balanceOf(app.db, repo.id).total; | |
| 381 | const run = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: alice.id, issueId: opened.value.id }); | |
| 382 | app.db.query("UPDATE run SET cost_usd = 2, state = 'ok' WHERE id = ?1").run(run.id); | |
| 383 | settle(app.db, repo.id, 1, WED); | |
| 384 | expect(balanceOf(app.db, repo.id, "big-idea").total).toBe(1 * UNIT); | |
| 385 | expect(balanceOf(app.db, repo.id).total).toBe(pool); | |
| 386 | expect(ledger(app.db, repo.id).find((e) => e.kind === "run")?.bet).toBe("big-idea"); | |
| 387 | }); | |
| 388 | ||
| 389 | test("exact dollars never drop a digit", () => { | |
| 390 | expect(unitsExact(1_500_000)).toBe("1.50"); | |
| 391 | expect(unitsExact(1)).toBe("0.000001"); | |
| 392 | }); | |
| 393 | ||
| 394 | test("the page forms are plain sections, with the exact weekly sum", async () => { | |
| 395 | const a = await mint(1); | |
| 396 | setWeeklyAllocation(app, alice, a, 1_234_567, WED); | |
| 397 | const page = await (await fetch(`${servers.url}/${a.ownerName}/${a.name}/allocation`, { headers: { cookie } })).text(); | |
| 398 | expect(page).toContain('value="1.234567"'); | |
| 399 | expect(page).not.toContain('class="card'); | |
| 400 | }); | |
| 401 | }); | |
| 402 | ||
| 403 | describe("the terminal does what the page does", () => { | |
| 404 | const press = (screen: { key(e: KeyEvent): boolean }, key: string): boolean => | |
| 405 | screen.key({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 406 | ||
| 407 | test("an admin sets the weekly sum and moves funds from the screen; a row shows when, fund and bet", async () => { | |
| 408 | const { allocationScreen, entryRow } = await import("../src/tui/screens/allocation.ts"); | |
| 409 | const a = await mint(20); | |
| 410 | settle(app.db, a.id, 20, new Date()); | |
| 411 | const toasts: string[] = []; | |
| 412 | const ctx = { toast: (m: string) => void toasts.push(m), setCursor: () => {}, theme: theme("dark") }; | |
| 413 | const session = new Session(app, { sshUsername: "alice", remoteAddress: "127.0.0.1" }); | |
| 414 | session.user = alice; | |
| 415 | const screen = allocationScreen(session, ctx, a); | |
| 416 | expect(press(screen, "w")).toBe(true); | |
| 417 | for (let i = 0; i < 6; i++) press(screen, "backspace"); | |
| 418 | for (const ch of "5") press(screen, ch); | |
| 419 | press(screen, "enter"); | |
| 420 | expect(balanceOf(app.db, a.id).total).toBe(5 * UNIT); | |
| 421 | expect(toasts.at(-1)).toBe("Weekly allocation is $5.00."); | |
| 422 | press(screen, "m"); | |
| 423 | for (const ch of "2") press(screen, ch); | |
| 424 | press(screen, "tab"); | |
| 425 | press(screen, "tab"); | |
| 426 | for (const ch of "tui-bet") press(screen, ch); | |
| 427 | for (let i = 0; i < 2; i++) press(screen, "tab"); | |
| 428 | press(screen, "enter"); | |
| 429 | press(screen, "enter"); | |
| 430 | press(screen, "enter"); | |
| 431 | press(screen, "enter"); | |
| 432 | expect(balanceOf(app.db, a.id, "tui-bet").total).toBe(2 * UNIT); | |
| 433 | const row = entryRow(ledger(app.db, a.id)[0]!); | |
| 434 | expect(row.title).toMatch(/^\d{4}-\d\d-\d\d \d\d:\d\d {2}moved in {2}subscription {2}tui-bet$/); | |
| 435 | expect(row.meta).toBe("+$2.00"); | |
| 436 | }); | |
| 437 | }); |
test/conversation-ask.test.ts +2
| @@ -496,6 +496,8 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [ | ||
| 496 | 496 | ], |
| 497 | 497 | ["invite", { repo: "marin/cakes", who: "ben" }, "Make ben a contributor on marin/cakes: they can read it, enter its app, ask its crew for changes, and fork it to propose changes; they cannot merge or change settings."], |
| 498 | 498 | ["invite", { repo: "marin/cakes", who: "ben", remove: true }, "Take ben off marin/cakes: they can no longer open it, its app or ask its crew."], |
| 499 | ["allocation", { repo: "marin/cakes", move: { amount: "5" } }, "Move allocation out of marin/cakes."], | |
| 500 | ["allocation", { repo: "marin/cakes", weekly: "20" }, "Set marin/cakes's weekly allocation to $20."], | |
| 499 | 501 | ["wall", { repo: "marin/cakes", number: 2, answer: "allow" }, "Allow pull #2 in marin/cakes at the access wall and merge it."], |
| 500 | 502 | ["wall", { repo: "marin/cakes", number: 2, answer: "send_back" }, "Send pull #2 in marin/cakes back at the access wall."], |
| 501 | 503 | [ |
test/job-slices.test.ts +1
| @@ -262,6 +262,7 @@ function jobs(): Record<string, () => unknown> { | ||
| 262 | 262 | * on. |
| 263 | 263 | */ |
| 264 | 264 | const UNTIMED: Record<string, string> = { |
| 265 | "allocation": "one settle pass hourly over repositories with a wallet (core/allocation.ts settleAll): indexed reads and a write only when a week turned; allocation tests drive settleAll directly", | |
| 265 | 266 | "copies-prune": "two DELETEs on indexed time columns (core/copies.ts pruneCopies), hourly on the outsider prune's own timer; copies-elsewhere.test.ts drives both fades", |
| 266 | 267 | "places-page-wait": "a one-shot timer in the new-forge page that only resolves the race when the Places catalog refresh outlives PAGE_WAIT_MS; no work of its own; new-forge-refresh.test.ts drives the refresh", |
| 267 | 268 | "tell-origin-wait": "a one-shot timer that only resolves the race when an origin has not answered a copy's report in TELL_MS; no work of its own; copies-elsewhere.test.ts tells a forge that answers", |
test/llms-budget.test.ts +3 −2
| @@ -57,9 +57,10 @@ const get = async (token?: string): Promise<string> => | ||
| 57 | 57 | * admin 98,000 (signed-in 84,100 and anonymous 9,250 as they are). Main measured admin 95,899, 101 |
| 58 | 58 | * bytes under 96,000, and four tools in flight (fetch_url, invite, bring, propose_upstream) each |
| 59 | 59 | * add about 40 to 330 bytes to it. Only an agent with an admin token reads this text, and few do, |
| 60 | * so the cost of the room is small. Raised to 98,500 for cut_wave (admin 98,345). | |
| 60 | * so the cost of the room is small. Raised to 98,500 for cut_wave (admin 98,345), then to 98,700 | |
| 61 | * for the allocation tool (#8718; admin 98,516). | |
| 61 | 62 | */ |
| 62 | const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 98_500 } as const; | |
| 63 | const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 98_700 } as const; | |
| 63 | 64 | |
| 64 | 65 | test("/llms.txt stays under its byte budget for each role", async () => { |
| 65 | 66 | const sizes = { |
test/mcp-forge-protocol.test.ts +1
| @@ -114,6 +114,7 @@ describe("the forge over MCP: protocol", () => { | ||
| 114 | 114 | const names = listed.body.result.tools.map((t: { name: string }) => t.name); |
| 115 | 115 | // Listed by name, one file each (#5924), and `report` last. |
| 116 | 116 | expect(names).toEqual(sortedThenReport([ |
| 117 | "allocation", | |
| 117 | 118 | "cut_wave", |
| 118 | 119 | "data", |
| 119 | 120 | "desk", |
test/refusals-lead-somewhere.test.ts +1
| @@ -44,6 +44,7 @@ const TERMINAL: Readonly<Record<string, string>> = { | ||
| 44 | 44 | "src/actions/contribute_token.ts\tthis repository does not take outside contributions": "A door its owner chose to keep shut, said as a fact to a stranger with no account here.", |
| 45 | 45 | "src/crew/bets.ts\tlower the share, or ask a site admin to raise your grant": "The way out itself, shared by the refusal and the card's note beside the share control; the grant is the owner's to raise.", |
| 46 | 46 | "src/web/pages/passkeys.ts\tAsk a site admin of this forge to help": "The reader is signed out and has no account to ask as; the sentence is the recovery page's only way through on a forge that sends no mail.", |
| 47 | "src/actions/allocation.ts\tRaising the weekly allocation above what it holds": "The forge owner's grant is the ceiling, and the owner is the one who raises it; an admin is told so, and may lower the allocation themselves.", | |
| 47 | 48 | "src/actions/spawn.ts\t${name} is already claimed; ask its owner to": "The owner is of another forge (the hosted one), which this forge cannot ask on anyone's behalf.", |
| 48 | 49 | }; |
| 49 | 50 |
new above
offline
Principles 6 and 7: a
cardbox around each form and around the fact list. Use plain sections with a hairline anddlrows.