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

The owner can see one repository's spend per day for the last 14 days as a table #13355

Merged opened this

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

Merged

torque/forge:torque/13330-the-owner-can-see-one-repository-s-spend → main 4 commits fork 1 thread · 1 unresolved

  • Merged. torque/13330-the-owner-can-see-one-repository-s-spend was merged into main as b8946df.

Review

Sign in to review this change.
7 files changed +309 −6
docs/features/README.md +1
@@ -344,6 +344,7 @@ Read with the guide page [Bring your own AI](../guide-own-ai.md).
344344 - [A parent funds a child's crew](child-credit.md)
345345 - [An org's model account](org-model-grant.md)
346346 - [Cost ledger](cost-ledger.md)
347 - [Cost by day](cost-days.md)
347348 - [Economics: the profit slider, its prices and what the month costs](economics.md)
348349 - [Escalate to Opus by need](model-escalation.md)
349350 - [Issue cost: what an issue and its pulls spent](issue-cost.md)
docs/features/cost-days.md added +10
@@ -0,0 +1,10 @@
1 # Cost by day
2
3 A repository's owner (anyone `canSeeOwnerFacts` names) reads what the crew spent on it in each of the last 14 days as a table: date, dollars, runs. The page is `/:owner/:name/cost`; the terminal's "Usage of a repository" screen opens with the same rows in the same words. Anyone else gets the page's not-found.
4
5 - **Source**: the usage ledger (`src/core/usage.ts`), one line per ended agent run, read in one grouped query over `usage_repo(repo_id, at)` (`src/core/cost_days.ts`).
6 - **Days are UTC.** The column header says so. A run is counted on the day it ended.
7 - **Dollars** are the provider's list price, to the cent.
8 - **A day with no run shows an em dash** (—) for dollars and runs, never `$0.00`.
9
10 Tests: `test/cost-days.test.ts` (fixtures across a month boundary, the page, the terminal).
src/core/cost_days.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * One repository's spend per day for the last 14 days (#13330): the usage
3 * ledger (`usage.ts`, one line per ended agent run) summed in one grouped
4 * query that walks `usage_repo(repo_id, at)`. The page and the terminal read
5 * this module for the rows and the words, so they never disagree.
6 *
7 * Units, stated once: `usd` is US dollars of the provider's list price, as
8 * Claude Code reports it; `runs` is ledger lines; a day is a UTC calendar day
9 * (`at` is written by `toISOString()`, so its first ten characters name it).
10 * A day with no ledger line has `usd` and `runs` null, never zero: nothing
11 * ran is not the same as nothing cost.
12 */
13
14 import type { Database } from "bun:sqlite";
15
16 export const COST_DAYS = 14;
17
18 export interface CostDay {
19 /** `YYYY-MM-DD`, UTC. */
20 readonly day: string;
21 readonly usd: number | null;
22 readonly runs: number | null;
23 }
24
25 const DAY_MS = 86_400_000;
26
27 /** The 14 days ending with the UTC day of `now`, newest first, gaps null. */
28 export function costDays(db: Database, repoId: string, now: Date = new Date()): CostDay[] {
29 const midnight = Date.parse(`${now.toISOString().slice(0, 10)}T00:00:00.000Z`);
30 const from = new Date(midnight - (COST_DAYS - 1) * DAY_MS).toISOString();
31 // Up to the next midnight: a clock a little ahead never hides a line.
32 const to = new Date(midnight + DAY_MS).toISOString();
33 const rows = new Map(
34 db
35 .query<{ day: string; usd: number; runs: number }, [string, string, string]>(
36 `SELECT substr(at, 1, 10) AS day, SUM(cost_usd) AS usd, COUNT(*) AS runs
37 FROM usage
38 WHERE repo_id = ?1 AND at >= ?2 AND at < ?3
39 GROUP BY day`,
40 )
41 .all(repoId, from, to)
42 .map((r) => [r.day, r] as const),
43 );
44 const out: CostDay[] = [];
45 for (let i = 0; i < COST_DAYS; i++) {
46 const day = new Date(midnight - i * DAY_MS).toISOString().slice(0, 10);
47 const r = rows.get(day);
48 out.push({ day, usd: r?.usd ?? null, runs: r?.runs ?? null });
49 }
50 return out;
51 }
52
53 export const EM_DASH = "—";
54
55 /** Dollars to the cent, or an em dash for a day nothing ended. */
56 export const dayUsd = (d: CostDay): string => (d.usd === null ? EM_DASH : `$${d.usd.toFixed(2)}`);
57 export const dayRuns = (d: CostDay): string => (d.runs === null ? EM_DASH : String(d.runs));
58
59 /** The terminal's line for a day, aligned: `2026-11-15 $3.20 2 runs`. */
60 export function dayLine(d: CostDay): string {
61 const runs = d.runs === null ? EM_DASH : `${d.runs} ${d.runs === 1 ? "run" : "runs"}`;
62 return `${d.day} ${dayUsd(d).padStart(9)} ${runs}`;
63 }
src/http/server.ts +2
@@ -278,6 +278,7 @@ import { spaceJson, spacePage } from "../web/pages/space.ts";
278278 import { firstSubmit } from "../web/pages/first.ts";
279279 import { nextPage, nextSubmit } from "../web/pages/next.ts";
280280 import { weekPage, weekSubmit } from "../web/pages/week.ts";
281 import { costPage } from "../web/pages/cost.ts";
281282 import {
282283 appMilestonesFragment,
283284 liveMilestonesFragment,
@@ -1405,6 +1406,7 @@ export function buildRouter(): Router<Handler> {
14051406 router.add("GET", "/:owner/:name/next", nextPage);
14061407 router.add("POST", "/:owner/:name/next", nextSubmit);
14071408 router.add("GET", "/:owner/:name/week", weekPage);
1409 router.add("GET", "/:owner/:name/cost", costPage);
14081410 router.add("POST", "/:owner/:name/week", weekSubmit);
14091411 router.add("POST", "/:owner/:name/issues/:number/first", firstSubmit);
14101412 router.add("GET", "/:owner/:name/flows", flowsPage);
src/tui/screens/usage.ts +19 −6
@@ -16,8 +16,9 @@ import { readForgeUsage, type ForgeUsage } from "../../actions/usage.ts";
1616 import { readReturns } from "../../actions/returns.ts";
1717 import { mayManageFlags } from "../../core/flags.ts";
1818 import { ROLES, SURFACES } from "../../core/usage_count.ts";
19 import { COST_DAYS, costDays, dayLine } from "../../core/cost_days.ts";
1920 import { usd } from "../../core/money.ts";
20 import type { Repo } from "../../core/repos.ts";
21 import { canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
2122 import type { Returns } from "../../core/returns.ts";
2223 import { routeUsage, WINDOW_DAYS, type RouteUsage } from "../../core/usage_report.ts";
2324 import { knownPatterns } from "../../http/server.ts";
@@ -56,7 +57,10 @@ export function returnsLine(r: Returns, days: number): string {
5657 }`;
5758 }
5859
59 /** The forge-wide block: today, the last 24 h, then each subscription's headroom in percent on its own line. */
60 /**
61 * The forge-wide block: today, the last 24 h, then each subscription's headroom in percent on its
62 * own line.
63 */
6064 export function forgeSpendLines(r: ForgeUsage): string[] {
6165 const span = (x: { costUsd: number; runs: number }) => `${usd(x.costUsd)} over ${plural(x.runs, "run", "runs")}`;
6266 const room = r.subscriptions.map((s) => {
@@ -71,19 +75,28 @@ export function forgeSpendLines(r: ForgeUsage): string[] {
7175 export function usageScreen(f: Session, ctx: Ctx, repo?: Repo): Screen {
7276 const state = new ListState();
7377 const allowed = repo === undefined && mayManageFlags(f.user);
74 // Read once when the screen opens: the report scans the whole table, so a frame or a key never re-runs it.
78 // Read once when the screen opens: the report scans the whole table, so a frame or a key never
79 // re-runs it.
7580 const rows: RouteUsage[] = allowed ? routeUsage(f.db, knownPatterns(), new Date()) : [];
7681 const scope = repo === undefined ? {} : { repo: `${repo.ownerName}/${repo.name}` };
7782 let span = RETURNS_SPANS.indexOf(7);
78 // Read when the window moves, never per frame; undefined is a refusal, and then there is no block.
83 // Read when the window moves, never per frame; undefined is a refusal, and then there is no
84 // block.
7985 const read = (): string | undefined => {
8086 const days = RETURNS_SPANS[span]!;
8187 const r = readReturns(f.app, f.user, { ...scope, days });
8288 return r.ok ? returnsLine(r.value, days) : undefined;
8389 };
8490 let returns = read();
85 // Forge-wide only, read once when the screen opens; readForgeUsage narrows to what this user can see.
86 const spend = repo === undefined && f.user !== undefined ? forgeSpendLines(readForgeUsage(f.app, f.user)) : [];
91 // Forge-wide only, read once when the screen opens; readForgeUsage narrows to what this user can
92 // see. A repository's: the last 14 UTC days, the page's table in the page's words (#13330), owner
93 // facts only.
94 const spend =
95 repo === undefined
96 ? f.user !== undefined ? forgeSpendLines(readForgeUsage(f.app, f.user)) : []
97 : canSeeOwnerFacts(f.db, repo, f.user)
98 ? [`Cost, last ${COST_DAYS} days`, ...costDays(f.db, repo.id).map(dayLine)]
99 : [];
87100 return {
88101 title: repo === undefined ? "Usage" : `Usage · ${repo.ownerName}/${repo.name}`,
89102 keys: [
src/web/pages/cost.ts added +56
@@ -0,0 +1,56 @@
1 /**
2 * `/:owner/:name/cost` (#13330): what the crew spent on this repository each
3 * of the last 14 UTC days, date, dollars and runs, from the usage ledger.
4 * Spend is the owner's own fact (`canSeeOwnerFacts`): anyone else gets the
5 * same not-found a missing repository does. Every figure is formatted in
6 * `core/cost_days.ts`, the module the terminal reads too.
7 */
8 import { COST_DAYS, costDays, dayRuns, dayUsd } from "../../core/cost_days.ts";
9 import { canSeeOwnerFacts } from "../../core/repos.ts";
10 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
11 import type { Ctx } from "../../http/context.ts";
12 import { crumbsFor, loadRepo, notFoundPage, repoHeader, repoPalette } from "../chrome.ts";
13 import { html } from "../html.ts";
14 import { page } from "../layout.ts";
15
16 // GET /:owner/:name/cost
17 export function costPage(ctx: Ctx): Response {
18 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
19 const repo = loadRepo(ctx);
20 if (!repo || !canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user)) return notFoundPage(ctx);
21 const days = timePhase(ctx.request, "cost", () => costDays(ctx.app.db, repo.id));
22 const rendering = performance.now();
23 const body = html`${repoHeader(ctx, repo, "issues")}
24 <div class="page-head mt">
25 <h1>Cost, last ${String(COST_DAYS)} days</h1>
26 </div>
outdated

Principle 1 (and attention rule 2, No notes): a <p class="muted small"> under the heading explaining the table is the DESIGN.md 'Don't'. The header already says 'Date (UTC)' and the em dash needs no key. Remove the caption here and COST_CAPTION in cost_days.ts and the terminal block.

27 <div class="table-scroll">
28 <table class="table" aria-label="Spend per day">
29 <thead>
30 <tr>
31 <th scope="col">Date (UTC)</th>
32 <th scope="col" class="num">Dollars</th>
33 <th scope="col" class="num">Runs</th>
34 </tr>
35 </thead>
36 <tbody>
37 ${days.map(
38 (d) => html`<tr data-day="${d.day}">
39 <th scope="row" class="mono">${d.day}</th>
40 <td class="num mono">${dayUsd(d)}</td>
41 <td class="num mono">${dayRuns(d)}</td>
42 </tr>`,
43 )}
44 </tbody>
45 </table>
46 </div>`;
47 const response = page({
48 ctx,
49 title: `Cost · ${repo.name}`,
50 crumbs: crumbsFor(repo),
51 palette: repoPalette(ctx, repo),
52 body,
53 });
54 notePhase(ctx.request, "render", performance.now() - rendering);
55 return response;
56 }
test/cost-days.test.ts added +158
@@ -0,0 +1,158 @@
1 /**
2 * Cost by day (#13330): 14 UTC days from the usage ledger in one grouped
3 * query, an em dash for a day no run ended, the owner's alone, on the page
4 * and in the terminal in the same words.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRun } from "../src/core/runs.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App as Forge } from "../src/app.ts";
13 import { COST_DAYS, costDays, dayLine } from "../src/core/cost_days.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { recordUsage } from "../src/core/usage.ts";
16 import { createUser, getUserByName } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { createForgeApp } from "../src/tui/forge.ts";
19 import { headlessTerminal } from "../src/tui/term/terminal.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { settleApp } from "./helpers/tui.ts";
22
23 quietLogs();
24
25 describe("cost by day", () => {
26 let dataDir: string;
27 let forge: Forge;
28 let servers: Servers;
29 let repo: Repo;
30 let other: Repo;
31
32 const line = (r: Repo, at: string, costUsd: number) =>
33 recordUsage(forge.db, {
34 runId: createRun(forge.db, { repoId: r.id, kind: "agent" }).id, repoId: r.id, issueId: null, agentId: null, subscriptionId: null,
35 tokensIn: 1, tokensOut: 1, costUsd, wallMs: 1, outcome: "ok", at,
36 });
37
38 const signIn = async (username: string): Promise<string> => {
39 const res = await fetch(`${servers.url}/signin`, {
40 method: "POST",
41 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
42 redirect: "manual",
43 });
44 return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
45 };
46
47 beforeAll(async () => {
48 dataDir = await mkdtemp(join(tmpdir(), "forge-cost-days-"));
49 forge = createApp({ dataDir, port: 0 });
50 servers = await serve(forge);
51 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
52 const made = await createUser(forge.db, {
53 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
54 password: "a-good-passphrase", adminIfFirst,
55 });
56 if (!made.ok) throw new Error(made.error);
57 }
58 const alice = getUserByName(forge.db, "alice")!;
59 const a = await createRepo(forge, alice, { name: "plan", visibility: "public" });
60 const b = await createRepo(forge, alice, { name: "elsewhere", visibility: "public" });
61 if (!a.ok || !b.ok) throw new Error("repo");
62 repo = a.value;
63 other = b.value;
64 }, 60_000);
65
66 afterAll(async () => {
67 await servers.stop?.();
68 forge.close();
69 await rm(dataDir, { recursive: true, force: true });
70 });
71
72 test("14 rows newest first across a month boundary, a gap is an em dash, sums are by UTC day", () => {
73 const now = new Date("2026-03-02T10:00:00.000Z");
74 line(repo, "2026-02-28T23:59:59.999Z", 1.25); // last instant of February
75 line(repo, "2026-03-01T00:00:00.000Z", 2); // first instant of March
76 line(repo, "2026-03-01T13:00:00.000Z", 0.5);
77 line(repo, "2026-03-02T09:00:00.000Z", 0.1);
78 line(repo, "2026-02-16T12:00:00.000Z", 9); // 14 days back: outside
79 line(repo, "2026-02-17T00:00:00.000Z", 3); // the 14th day: inside
80 line(other, "2026-03-01T12:00:00.000Z", 99); // another repository's
81 const days = costDays(forge.db, repo.id, now);
82 expect(days).toHaveLength(COST_DAYS);
83 expect(days[0]!.day).toBe("2026-03-02");
84 expect(days[13]!.day).toBe("2026-02-17");
85 const by = Object.fromEntries(days.map((d) => [d.day, d]));
86 expect(by["2026-03-02"]).toEqual({ day: "2026-03-02", usd: 0.1, runs: 1 });
87 expect(by["2026-03-01"]).toEqual({ day: "2026-03-01", usd: 2.5, runs: 2 });
88 expect(by["2026-02-28"]).toEqual({ day: "2026-02-28", usd: 1.25, runs: 1 });
89 expect(by["2026-02-27"]).toEqual({ day: "2026-02-27", usd: null, runs: null });
90 expect(by["2026-02-17"]!.usd).toBe(3);
91 expect(by["2026-02-16"]).toBeUndefined();
92 expect(dayLine(by["2026-02-27"]!)).toBe("2026-02-27 — —");
93 expect(dayLine(by["2026-03-01"]!)).toBe("2026-03-01 $2.50 2 runs");
94 // One grouped query: the plan walks the repo index.
95 const plan = forge.db
96 .query<{ detail: string }, [string]>(
97 `EXPLAIN QUERY PLAN SELECT substr(at, 1, 10) AS day, SUM(cost_usd), COUNT(*) FROM usage
98 WHERE repo_id = ?1 AND at >= '2026' AND at < '2027' GROUP BY day`,
99 )
100 .all(repo.id)
101 .map((r) => r.detail)
102 .join("\n");
103 expect(plan).toContain("usage_repo");
104 expect(plan).not.toMatch(/SCAN usage/);
105 });
106
107 test("a day with runs but zero cost reads $0.00, not an em dash", () => {
108 const at = new Date().toISOString();
109 line(other, at, 0);
110 const today = costDays(forge.db, other.id)[0]!;
111 expect(today.runs).toBe(1);
112 expect(dayLine(today)).toContain("$0.00");
113 expect(dayLine(today)).toContain("1 run");
114 });
115
116 test("the page shows the table and the table to the owner; anyone else is not told", async () => {
117 line(repo, new Date().toISOString(), 4.2);
118 const owner = await fetch(`${servers.url}/alice/plan/cost`, { headers: { cookie: await signIn("alice") } });
119 expect(owner.status).toBe(200);
120 const text = await owner.text();
121 expect((text.match(/data-day="/g) ?? []).length).toBe(COST_DAYS);
122 expect(text).toContain("$4.20");
123 expect(text).toContain("Date (UTC)");
124 expect(text).toContain("—");
125 expect(text).not.toContain("$0.00");
126 expect((await fetch(`${servers.url}/alice/plan/cost`, { headers: { cookie: await signIn("bob") } })).status).toBe(404);
127 expect((await fetch(`${servers.url}/alice/plan/cost`)).status).toBe(404);
128 });
129
130 test("the terminal's repository usage screen carries the same rows", async () => {
131 const terminal = headlessTerminal(140, 40);
132 const user = getUserByName(forge.db, "alice")!;
133 const { app } = createForgeApp(forge, { sshUsername: "t", remoteAddress: "127.0.0.1", user }, { terminal, exitHooks: false });
134 app.start();
135 const press = async (...keys: string[]) => {
136 for (const key of keys) {
137 const ctrl = key.startsWith("ctrl+");
138 app.dispatch({ type: "key", key: ctrl ? key.slice(5) : key, ctrl, alt: false, shift: false });
139 }
140 await settleApp(app);
141 };
142 const type = async (text: string) => {
143 for (const ch of text) app.dispatch({ type: "key", key: ch, ctrl: false, alt: false, shift: false });
144 await settleApp(app);
145 };
146 await settleApp(app);
147 await press("ctrl+k");
148 await type("Usage of a repository");
149 await press("enter");
150 await type("alice/plan");
151 await press("enter");
152 const screen = app.screen.toText();
153 app.stop();
154 expect(screen).toContain(`Cost, last ${COST_DAYS} days`);
155 expect(screen).toContain("$4.20");
156 expect(screen).toContain(new Date().toISOString().slice(0, 10));
157 });
158 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs