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

A repository's wallet ledger downloads as a CSV of what was spent, when and on what #14633

Merged opened this

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

Merged

scout/forge:scout/14579-a-repository-s-wallet-ledger-downloads-a → main 4 commits fork 3 threads · 3 unresolved

  • Merged. scout/14579-a-repository-s-wallet-ledger-downloads-a was merged into main as f7f766c.

Review

Sign in to review this change.
5 files changed +47 −18
docs/features/wallet.md +6 −4
@@ -16,11 +16,13 @@ did not end well says so beside what it paid for.
1616 - **Where:** a link beside the statement in the app's settings → App; at the
1717 terminal, `owner/name — Wallet` in the `:` palette while the repository is
1818 open (`j`/`k` move).
19 - **CSV:** `/owner/name/wallet.csv` downloads those same rows (`date_utc,dollars,paid_for,outcome,run`)
19 - **CSV:** `/owner/name/wallet.csv` downloads those same rows (`time_utc,dollars,paid_for,outcome,run`)
2020 through the shared formula-safe writer (`actions/wallet_csv.ts`: a cell starting `=`, `+`, `-` or `@`
21 is written as text). It reads `readWallet`, so the gate and the 20-row cap are the page's: anyone
22 else gets 404. The page links it; the terminal's wallet screen prints the path. It does not go
23 through `exportRows`, which reads a table of an app's own database; the ledger is the forge's.
21 is written as text). It reads `readWallet`, so the gate is the page's; anyone else gets 404.
outdated

Run-on line, and it documents the note row that should go. Wrap like the neighbours.

22 The newest 5,000 spends are listed, one row each and no commentary. When older ones were left
23 out, the response carries `X-Wallet-Rows-Cut: 5000`. The page links it; the terminal's wallet
24 screen prints the path. It does not go through `exportRows`, which reads a table of an app's
25 own database; the ledger is the forge's.
2426 - **Last 30 days:** above the spends, one row per UTC day, today first, each with its dollars and a
2527 server-rendered SVG bar (a share of the largest day; no script, no chart library). A day with no
2628 spend reads `$0.00`, never a gap. One grouped query reads the window and the total is the sum of its
src/actions/wallet.ts +2 −2
@@ -56,9 +56,9 @@ interface Row {
5656 export const LAST_SPENDS_SQL = `SELECT run_id, issue_id, kind, outcome, cost_usd, at FROM usage
5757 WHERE repo_id = ?1 ORDER BY at DESC, rowid DESC LIMIT ?2`;
5858
59 export function readWallet(app: App, actor: User | undefined, repo: Repo): Result<Wallet, "not_found"> {
59 export function readWallet(app: App, actor: User | undefined, repo: Repo, limit = WALLET_ROWS): Result<Wallet, "not_found"> {
6060 if (!canSeeOwnerFacts(app.db, repo, actor)) return err("not_found");
61 const rows = app.db.query<Row, [string, number]>(LAST_SPENDS_SQL).all(repo.id, WALLET_ROWS);
61 const rows = app.db.query<Row, [string, number]>(LAST_SPENDS_SQL).all(repo.id, limit);
6262 const issues = getIssuesByIds(
6363 app.db,
6464 rows.flatMap((r) => (r.issue_id === null ? [] : [r.issue_id])),
src/actions/wallet_csv.ts +16 −3
@@ -6,7 +6,20 @@
66 import { toCsv } from "../text/csv_write.ts";
77 import type { WalletSpend } from "./wallet.ts";
88
9 export const WALLET_CSV_HEADER = ["date_utc", "dollars", "paid_for", "outcome", "run"] as const;
9 export const WALLET_CSV_HEADER = ["time_utc", "dollars", "paid_for", "outcome", "run"] as const;
1010
11 export const walletCsv = (spends: readonly WalletSpend[]): string =>
12 toCsv(WALLET_CSV_HEADER, spends.map((s) => [s.date, Number(s.costUsd.toFixed(2)), s.paidFor, s.outcome, s.runPath]));
11 export const WALLET_CSV_ROWS = 5000;
12 /** Read this many to know whether the ledger holds more than the cap. */
13 export const WALLET_CSV_READ = WALLET_CSV_ROWS + 1;
14
15 /** The newest `WALLET_CSV_ROWS` of a newest-first read, and whether older spends were left out. */
16 export const capSpends = (spends: readonly WalletSpend[]): { spends: readonly WalletSpend[]; cut: boolean } => ({
outdated

Principle 8 / clean: one 200-column line, and the cut-off note is a fake data row (empty time, empty amount) that breaks every consumer of the CSV. Also >= WALLET_CSV_ROWS calls an exactly-5,000 ledger cut. Build the rows in a const, drop the note row, and signal the cut elsewhere.

17 spends: spends.slice(0, WALLET_CSV_ROWS),
18 cut: spends.length > WALLET_CSV_ROWS,
19 });
20
21 /** Newest first, one row per spend and nothing else: a cut is said in a header, never in a row. */
22 export const walletCsv = (spends: readonly WalletSpend[]): string => {
23 const rows = spends.map((s) => [s.at, Number(s.costUsd.toFixed(2)), s.paidFor, s.outcome, s.runPath]);
24 return toCsv(WALLET_CSV_HEADER, rows);
25 };
src/web/pages/wallet.ts +5 −3
@@ -6,7 +6,7 @@
66 * Server-rendered, no script; anyone else gets the not-found page.
77 */
88
9 import { walletCsv } from "../../actions/wallet_csv.ts";
9 import { capSpends, WALLET_CSV_READ, WALLET_CSV_ROWS, walletCsv } from "../../actions/wallet_csv.ts";
1010 import { dayBarSvg, readWalletDays, WALLET_DAYS } from "../../actions/wallet_days.ts";
1111 import { capInvalidWords, capSavedWords, readWallet, saveCap } from "../../actions/wallet.ts";
1212 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
@@ -103,11 +103,13 @@ export function walletPage(ctx: Ctx): Response {
103103 export function walletCsvDownload(ctx: Ctx): Response {
104104 const repo = loadRepo(ctx);
105105 if (!repo) return repoNotFound(ctx);
106 const read = readWallet(ctx.app, ctx.auth.user, repo);
106 const read = readWallet(ctx.app, ctx.auth.user, repo, WALLET_CSV_READ);
107107 if (!read.ok) return repoNotFound(ctx);
108108 const name = `${repo.name}-wallet`.replace(/[^A-Za-z0-9._-]/g, "_");
109 return new Response(walletCsv(read.value.spends), {
109 const { spends, cut } = capSpends(read.value.spends);
110 return new Response(walletCsv(spends), {
110111 headers: {
112 ...(cut ? { "x-wallet-rows-cut": String(WALLET_CSV_ROWS) } : {}),
111113 "content-type": "text/csv; charset=utf-8",
112114 "content-disposition": `attachment; filename="${name}.csv"`,
113115 "x-content-type-options": "nosniff",
test/wallet.test.ts +18 −6
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
1010 import { readWallet, LAST_SPENDS_SQL } from "../src/actions/wallet.ts";
11 import { walletCsv } from "../src/actions/wallet_csv.ts";
11 import { capSpends, walletCsv } from "../src/actions/wallet_csv.ts";
1212 import { createIssue } from "../src/core/issues.ts";
1313 import { createRepo as initRepo, type Repo } from "../src/core/repos.ts";
1414 import { createRun } from "../src/core/runs.ts";
@@ -175,16 +175,28 @@ test("the CSV download is the page's rows, neutralises a formula cell, and is th
175175 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
176176 expect(res.headers.get("content-disposition")).toContain("wallet-app-wallet.csv");
177177 const lines = (await res.text()).split("\r\n").filter((l) => l !== "");
178 const w = readWallet(app, bob, repo);
178 const w = readWallet(app, bob, repo, 5001);
179179 if (!w.ok) throw new Error("refused");
180 expect(lines).toHaveLength(21);
181 expect(lines[0]).toBe("date_utc,dollars,paid_for,outcome,run");
182 expect(lines.slice(1)).toEqual(walletCsv(w.value.spends).split("\r\n").filter((l) => l !== "").slice(1));
183 expect(lines[1]).toBe(`2026-10-07,1.5,build #1 Fix <b>the</b> login,ok,/bob/wallet-app/runs/${issueRun}`);
180 // 10,000 rows in the ledger: the newest 5,000, a header saying so, no note row.
181 expect(lines).toHaveLength(5001);
182 expect(res.headers.get("x-wallet-rows-cut")).toBe("5000");
183 expect(lines[0]).toBe("time_utc,dollars,paid_for,outcome,run");
184 expect(lines.every((l) => !l.startsWith(",,"))).toBe(true);
outdated

The slice(1) comparison against walletCsv of the same spends cannot fail for a wrong order or a wrong cut. Assert concrete rows, and add exactly-5,000 → no note.

185 expect(lines[1]).toBe(`2026-10-07T22:39:00.000Z,1.5,build #1 Fix <b>the</b> login,ok,/bob/wallet-app/runs/${issueRun}`);
186 const times = lines.slice(1).map((l) => l.slice(0, 24));
187 expect(times).toEqual([...times].sort().reverse());
188 expect(times[0]! > times[4999]!).toBe(true);
184189 const page = await (await fetch(`${servers.url}/bob/wallet-app/wallet`, { headers: { cookie: await cookieOf("bob") } })).text();
185190 expect(page).toContain("/bob/wallet-app/wallet.csv");
186191 const evil = { ...w.value.spends[0]!, paidFor: "=HYPERLINK(1)" };
187192 expect(walletCsv([evil]).split("\r\n")[1]).toContain(",'=HYPERLINK(1),");
193 const quoted = walletCsv([{ ...w.value.spends[0]!, at: "2026-01-02T03:04:05.000Z", paidFor: 'say "hi", ok' }]).split("\r\n")[1];
194 expect(quoted).toStartWith('2026-01-02T03:04:05.000Z,1.5,"say ""hi"", ok",');
195 const one = w.value.spends[0]!;
196 const many = (n: number) => Array.from({ length: n }, () => one);
197 expect(capSpends(many(5000)).cut).toBe(false);
198 expect(capSpends(many(5001))).toMatchObject({ cut: true });
199 expect(capSpends(many(5001)).spends).toHaveLength(5000);
188200 for (const headers of [{}, { cookie: await cookieOf("carol") }]) {
189201 const no = await fetch(`${servers.url}/bob/wallet-app/wallet.csv`, { headers, redirect: "manual" });
190202 expect(no.status).toBe(404);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs