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

A cost ledger per delivery: tokens, compute and time per run, hash-chained in git and signed, shown per pull and issue and read through the API and MCP #1391

Closed opened this in answer to
Closed without merging

torque/forge:torque/1386-a-cost-ledger-per-delivery-tokens-comput → main 8 commits fork 8 threads · 8 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
24 files changed +1795 −22
README.md +29
@@ -411,6 +411,35 @@ The terminal has no backups view, so it has no readout.
411411 grew up in switched off: what a host owes it, the moves in order, and what is
412412 given up.
413413
414 ### The cost ledger
415
416 Every run that did work (agent, check, deploy) gets one entry when it ends:
417 tokens and their dollars, the CPU-seconds and GiB-seconds its cell's watch
418 measured (`null` where no cell held it), the seconds it waited for a lane
419 and the seconds it ran, and the compute priced at the forge's rates
420 (`/settings/capacity`: US$ per vCPU-hour and per GB-hour, defaulting to
421 Fargate's list price, written into each entry). Entries are hash-chained
422 (`prev`, `hash` = SHA-256 of the canonical entry) and signed with an
423 Ed25519 key derived from the data directory's `secret.key`, committed a
424 batch at a time to `<data>/ledger.git` beside `forge.pub`. The database is
425 its index. Anyone holding the repository can check it:
426
427 ```sh
428 bun scripts/ledger-verify.ts data/ledger.git # ok: N entries, tip …
429 bun scripts/ledger-verify.ts ledger.git --key <pub> # trust a key you were given, not forge.pub
430 ```
431
432 A pull and an issue show `cost: $… tokens · $… compute · N lane-min · … waiting`
433 to their owner; the board's forge line shows the day's totals to an admin.
434 The same numbers, behind the same gates, are at
435 `GET /api/v1/repos/:owner/:name/issues/:number/cost` (anyone who can write
436 the repository) and `GET /api/v1/admin/cost?day=YYYY-MM-DD` (a site admin;
437 UTC, today when absent), and through the MCP `cost` tool (`repo` and `issue`,
438 or neither for the day). In the terminal, open the issue or pull (from the
439 repository's issue or pull list, `enter`): the same `cost:` line sits under
440 its summary line, with a pull's lead time after it, for anyone who can write
441 the repository.
442
414443 ### Passports
415444
416445 A crew run's environment carries `FORGE_PASSPORT`, a 15-minute credential
scripts/gate.ts +1
@@ -247,6 +247,7 @@ export const GATE: readonly string[] = [
247247 "test/counts.test.ts",
248248 "test/crew-loop.test.ts",
249249 "test/crew-totals.test.ts",
250 "test/ledger-cost.test.ts",
250251 "test/flake.test.ts",
251252 "test/crew-locks.test.ts",
252253 "test/ssh-site.test.ts",
scripts/ledger-verify.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * Walk a forge's cost ledger and say whether every link holds:
3 *
4 * bun scripts/ledger-verify.ts [ledger.git] [--key <base64url public key>]
5 *
6 * The ledger defaults to `$FORGE_DATA/ledger.git` (else `./data/ledger.git`).
7 * Each entry must carry the next seq, name the previous entry's hash, hash
8 * to what it says (SHA-256 of its canonical form, `core/cost_ledger.ts`) and
9 * be signed by the forge's key — the one in the repository's `forge.pub`,
10 * or, to trust nothing the repository says about itself, the one given with
11 * `--key`. Prints the count and the tip, or the first break; exits 1 on a
12 * break.
13 */
14
15 import { existsSync } from "node:fs";
16 import { join } from "node:path";
17 import { verifyChain } from "../src/core/cost_ledger.ts";
18 import { readLedger } from "../src/core/ledger_write.ts";
19
20 const args = process.argv.slice(2);
21 const keyAt = args.indexOf("--key");
22 const given = keyAt >= 0 ? args[keyAt + 1] : undefined;
23 const positional =
24 keyAt < 0 ? args : args.filter((_, i) => i !== keyAt && i !== keyAt + 1);
25 const dir =
26 positional[0] ?? join(process.env["FORGE_DATA"] ?? "./data", "ledger.git");
27
28 if (!existsSync(dir)) {
29 console.error(`no ledger at ${dir}`);
30 process.exit(1);
31 }
32 const { publicKey, lines } = await readLedger(dir);
33 const key = given ?? publicKey;
34 if (key === "") {
35 console.error(`no ledger at ${dir} (no forge.pub and no --key)`);
36 process.exit(1);
37 }
38 const verdict = verifyChain(lines, key);
39 if (verdict.ok) {
40 console.log(`ok: ${verdict.count} entries, tip ${verdict.tip}`);
41 } else {
42 console.log(`broken at entry ${verdict.seq}: ${verdict.reason}`);
43 process.exit(1);
44 }
src/actions/cost.ts added +67
@@ -0,0 +1,67 @@
1 /**
2 * Reading the cost ledger (`core/cost_ledger.ts`) outside the page: one
3 * issue's or pull's roll-up, and the forge's day. The same gates as the
4 * page — an issue's cost is its owner's fact (`canSeeOwnerFacts`, as on the
5 * issue and pull pages), the day is a site admin's (as on the board's forge
6 * line). The API routes and the MCP `cost` tool both answer from here, so
7 * they never disagree with the page.
8 */
9
10 import type { App } from "../app.ts";
11 import {
12 dayCost,
13 issueCost,
14 ledgerLine,
15 type CostRollup,
16 } from "../core/cost_ledger.ts";
17 import { getIssue } from "../core/issues.ts";
18 import { canSeeOwnerFacts, type Repo } from "../core/repos.ts";
19 import { mayView } from "../core/sealed.ts";
20 import type { User } from "../core/users.ts";
21 import { err, ok, type Result } from "../kernel/result.ts";
22
23 export interface IssueCostReport extends CostRollup {
24 readonly number: number;
25 readonly kind: string;
26 /** What the page prints after `cost:` — "" when nothing was entered. */
27 readonly line: string;
28 }
29
30 export interface DayCostReport extends CostRollup {
31 /** The UTC day, `YYYY-MM-DD`, by when the work ended. */
32 readonly day: string;
33 readonly line: string;
34 }
35
36 export function readIssueCost(
37 app: App,
38 user: User | undefined,
39 repo: Repo,
40 number: number,
41 ): Result<IssueCostReport, "forbidden" | "not_found"> {
42 if (!canSeeOwnerFacts(app.db, repo, user)) return err("forbidden");
43 const issue = getIssue(app.db, repo.id, number);
44 // A sealed report is not there for anyone who may not see it (`core/sealed.ts`).
45 if (issue === undefined || !mayView(app.db, repo, issue, user))
46 return err("not_found");
47 const r = issueCost(app.db, issue.id);
48 return ok({ number, kind: issue.kind, ...r, line: ledgerLine(r) });
49 }
50
51 /** A UTC calendar day that exists: "2026-10-15" yes, "2026-02-30" no. */
52 export function costDay(raw: string | null | undefined, now = new Date()): string | undefined {
53 if (raw === null || raw === undefined || raw === "") return now.toISOString().slice(0, 10);
54 if (!/^\d{4}-\d{2}-\d{2}$/.test(raw)) return undefined;
55 const t = Date.parse(`${raw}T00:00:00Z`);
56 return Number.isNaN(t) || new Date(t).toISOString().slice(0, 10) !== raw ? undefined : raw;
57 }
58
59 export function readDayCost(
60 app: App,
61 user: User | undefined,
62 day: string,
63 ): Result<DayCostReport, "forbidden"> {
64 if (user?.isAdmin !== true) return err("forbidden");
65 const r = dayCost(app.db, day);
66 return ok({ day, ...r, line: ledgerLine(r) });
67 }
src/apps/contain.ts +86 −12
@@ -111,8 +111,26 @@ export interface CellSpec {
111111 * environment's (`egressMode`) when the caller has none.
112112 */
113113 readonly egressMode?: "enforce" | "report" | undefined;
114 /** Where the watch adds what this cell's processes used (the cost ledger's compute). */
115 readonly usage?: CellUsage | undefined;
114116 }
115117
118 /**
119 * What a cell's processes used, as the watch saw them once a tick:
120 * `cpuS` is CPU-seconds (user + system, the process's own and its reaped
121 * children's, from `/proc/<pid>/stat` at CLK_TCK=100), counted as each
122 * process's growth since the last tick so an exited process keeps what
123 * it used; `memGbS` is resident memory integrated over time —
124 * Σ (VmRSS GiB × tick seconds). One accumulator may span several cells
125 * (a check's install and its test), so it is only ever added to.
126 */
127 export interface CellUsage {
128 cpuS: number;
129 memGbS: number;
130 }
131
132 export const newUsage = (): CellUsage => ({ cpuS: 0, memGbS: 0 });
133
116134 /**
117135 * Whether undeclared egress is refused (`enforce`, the default) or let
118136 * through and reported (`FORGE_CELLS_EGRESS=report`), for a release that
@@ -360,7 +378,7 @@ export function openCell(
360378 let breach: string | undefined;
361379 let unwatch: (() => void) | undefined;
362380 const watch = (pid: number, stop: (why: string) => void): void => {
363 unwatch = watchTree(pid, spec.limits, writable, (why) => {
381 unwatch = watchTree(pid, spec.limits, writable, spec.usage, (why) => {
364382 if (breach !== undefined) return;
365383 breach = why;
366384 log(`stopped: ${why}`);
@@ -506,6 +524,10 @@ interface Watched {
506524 readonly breach: (why: string) => void;
507525 readonly samples: { at: number; ticks: number }[];
508526 ticks: number;
527 readonly usage: CellUsage | undefined;
528 /** Each process's ticks at the last look, for `usage`'s growth. */
529 readonly seen: Map<number, number>;
530 lastAt: number | undefined;
509531 }
510532
511533 const watched = new Set<Watched>();
@@ -605,6 +627,7 @@ function watchTree(
605627 root: number,
606628 limits: Limits,
607629 writable: readonly string[],
630 usage: CellUsage | undefined,
608631 breach: (why: string) => void,
609632 ): () => void {
610633 const entry: Watched = {
@@ -614,6 +637,9 @@ function watchTree(
614637 breach,
615638 samples: [],
616639 ticks: 0,
640 usage,
641 seen: new Map(),
642 lastAt: undefined,
617643 };
618644 watched.add(entry);
619645 timer ??= setInterval(tick, WATCH.tickMs);
@@ -626,9 +652,31 @@ function watchTree(
626652 };
627653 }
628654
629 interface ProcessRow {
655 export interface ProcessRow {
630656 ppid: number;
657 /** utime + stime: this process's own CPU, what the meter bills. */
631658 ticks: number;
659 /** ticks + cutime + cstime: with its reaped children, what the CPU limit sums. */
660 withReaped: number;
661 }
662
663 /**
664 * One `/proc/<pid>/stat` line's parent and CPU ticks (proc(5): utime, stime,
665 * cutime, cstime are fields 14–17). The meter counts each process's own
666 * growth, so it reads utime + stime only: cutime/cstime would count a reaped
667 * child again in its parent after the meter counted it while it lived. The
668 * limit sums the tree at one instant, where a reaped child's ticks move to
669 * its parent and the sum holds, so it reads all four.
670 */
671 export function statRow(stat: string): ProcessRow {
672 // The command name is in parentheses and may hold spaces; fields after it are fixed.
673 const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
674 const ticks = Number(fields[11]) + Number(fields[12]);
675 return {
676 ppid: Number(fields[1]),
677 ticks,
678 withReaped: ticks + Number(fields[13]) + Number(fields[14]),
679 };
632680 }
633681
634682 function processTable(): {
@@ -651,16 +699,10 @@ function processTable(): {
651699 } catch {
652700 continue;
653701 }
654 // The command name is in parentheses and may hold spaces; fields after it are fixed.
655 const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
656 const ppid = Number(fields[1]);
657 const ticks =
658 Number(fields[11]) +
659 Number(fields[12]) +
660 Number(fields[13]) +
661 Number(fields[14]);
702 const row = statRow(stat);
703 const { ppid } = row;
662704 const pid = Number(name);
663 rows.set(pid, { ppid, ticks });
705 rows.set(pid, row);
664706 const list = children.get(ppid);
665707 if (list) list.push(pid);
666708 else children.set(ppid, [pid]);
@@ -730,8 +772,9 @@ function tick(): void {
730772 let ticks = 0;
731773 for (const pid of tree) {
732774 kib += residentKiB(pid);
733 ticks += rows.get(pid)?.ticks ?? 0;
775 ticks += rows.get(pid)?.withReaped ?? 0;
734776 }
777 meter(entry, tree, rows, kib, now);
735778 if (kib > limits.memoryMiB * 1024) {
736779 entry.breach(
737780 `used ${mib(kib * 1024)} of memory, over its ${limits.memoryMiB} MiB limit`,
@@ -765,3 +808,34 @@ function tick(): void {
765808 }
766809 }
767810 }
811
812 /**
813 * Add one tick's use to the cell's accumulator: each process's CPU ticks
814 * since it was last seen (a new process counts from zero, so what it used
outdated

These ticks include cutime+cstime (see the row parsing above). A child's CPU is counted once while it is alive and again when its parent reaps it, so a check's cpu_s comes out about 2× or more, and the entry is signed and permanent. Meter utime+stime only (stat fields 11 and 12).

815 * before the first look is counted too), and resident memory held for the
816 * time since the last tick.
817 */
818 export function meter(
819 entry: Pick<Watched, "usage" | "seen" | "lastAt">,
820 tree: readonly number[],
821 rows: Map<number, { ticks: number }>,
822 kib: number,
823 now: number,
824 ): void {
825 const usage = entry.usage;
826 if (usage === undefined) return;
827 let grew = 0;
828 const next = new Map<number, number>();
829 for (const pid of tree) {
830 const ticks = rows.get(pid)?.ticks ?? 0;
831 grew += Math.max(0, ticks - (entry.seen.get(pid) ?? 0));
832 next.set(pid, ticks);
833 }
834 entry.seen.clear();
835 for (const [pid, ticks] of next) entry.seen.set(pid, ticks);
836 usage.cpuS += grew / CLK_TCK;
837 const seconds =
838 entry.lastAt === undefined ? WATCH.tickMs / 1000 : (now - entry.lastAt) / 1000;
839 usage.memGbS += (kib / (1024 * 1024)) * seconds;
840 entry.lastAt = now;
841 }
src/checks/service.ts +11 −1
@@ -61,9 +61,11 @@ import {
6161 } from "../core/capacity.ts";
6262 import {
6363 cellsAvailable,
64 newUsage,
6465 resolveLimits,
6566 STEP_HOSTS,
6667 type CellSpec,
68 type CellUsage,
6769 } from "../apps/contain.ts";
6870 import { summariseCheckFailure } from "./summary.ts";
6971 import type { CheckDetail } from "../core/runs.ts";
@@ -371,7 +373,8 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
371373 overran = true;
372374 budget.abort();
373375 }, limit);
374 const outcome = await check(claimed, repo, write, budget.signal).finally(
376 const meter = { usage: newUsage(), measured: false };
377 const outcome = await check(claimed, repo, write, budget.signal, meter).finally(
375378 () => {
376379 clearTimeout(clock);
377380 signal.removeEventListener("abort", forward);
@@ -418,6 +421,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
418421 ...(outcome.ok || outcome.detail === undefined
419422 ? {}
420423 : { checkDetail: outcome.detail }),
424 ...(meter.measured ? { usage: meter.usage } : {}),
421425 });
422426 write(outcome.ok ? `passed in ${seconds}s` : `failed: ${outcome.error}`);
423427 if (done) announceRun(app, done);
@@ -431,6 +435,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
431435 repo: Repo,
432436 write: (line: string) => void,
433437 signal: AbortSignal,
438 meter: { usage: CellUsage; measured: boolean },
434439 ): Promise<
435440 | { ok: true }
436441 | { ok: false; error: string; detail?: CheckDetail | undefined }
@@ -452,6 +457,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
452457 tier: pull === undefined ? "run" : "fast",
453458 write,
454459 signal,
460 meter,
455461 });
456462 return outcome;
457463 }
@@ -468,6 +474,8 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
468474 readonly tier: "run" | "fast" | "full";
469475 readonly write: (line: string) => void;
470476 readonly signal: AbortSignal;
477 /** Where the cell's watch adds what the check used; marked measured once a cell holds it. */
478 readonly meter?: { usage: CellUsage; measured: boolean } | undefined;
471479 }
472480
473481 async function runTier(
@@ -589,8 +597,10 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
589597 onUndeclared: (host, port) =>
590598 noteReached(app.config.dataDir, repo.id, host, port),
591599 egressMode: egressSetting(app.db),
600 usage: x.meter?.usage,
592601 }
593602 : undefined;
603 if (cell !== undefined && x.meter !== undefined) x.meter.measured = true;
594604 try {
595605 const env = childEnv({
596606 // The shard count an admin set (`core/capacity.ts`), never the pod's.
src/core/capacity.ts +32 −2
@@ -21,7 +21,9 @@ export type CapacityKey =
2121 | "checks.shards"
2222 | "children.max"
2323 | "cells.egress"
24 | "guard_new_accounts";
24 | "guard_new_accounts"
25 | "cost.vcpu_hour"
26 | "cost.gb_hour";
2527
2628 interface Definition {
2729 /** What the settings page and the API call it. */
@@ -31,7 +33,8 @@ interface Definition {
3133 /** Whole numbers in a range, or one of a few words. */
3234 readonly kind:
3335 | { readonly type: "count"; readonly min: number; readonly max: number }
34 | { readonly type: "choice"; readonly values: readonly string[] };
36 | { readonly type: "choice"; readonly values: readonly string[] }
37 | { readonly type: "rate"; readonly max: number };
3538 /** What it is when neither the store nor the environment says. */
3639 readonly fallback: string;
3740 readonly help: string;
@@ -80,6 +83,23 @@ export const CAPACITY: Record<CapacityKey, Definition> = {
8083 fallback: "off",
8184 help: "on refuses repository creation and forks for accounts younger than 7 days (agents and admins are exempt); off leaves it to the usual permissions. Takes effect immediately. Replaces the hand-installed database trigger that used to do this with no toggle.",
8285 },
86 // The default rates are AWS Fargate's Linux/x86 list price in us-east-1
87 // (US$0.04048 per vCPU-hour, US$0.004445 per GB-hour) — a stated
88 // assumption until the owner says what this node costs.
89 "cost.vcpu_hour": {
90 label: "Compute: US$ per vCPU-hour",
91 env: "FORGE_COST_VCPU_HOUR",
92 kind: { type: "rate", max: 100 },
93 fallback: "0.04048",
94 help: "What one CPU core for an hour costs on this node. The cost ledger prices each run's CPU-seconds at this rate, and writes the rate into the entry.",
95 },
96 "cost.gb_hour": {
97 label: "Compute: US$ per GB-hour",
98 env: "FORGE_COST_GB_HOUR",
99 kind: { type: "rate", max: 100 },
100 fallback: "0.004445",
101 help: "What one GiB of memory held for an hour costs on this node. The cost ledger prices each run's resident memory over time at this rate.",
102 },
83103 };
84104
85105 export const CAPACITY_KEYS = Object.keys(CAPACITY) as CapacityKey[];
@@ -100,6 +120,8 @@ export function isCapacityKey(key: string): key is CapacityKey {
100120 export function validCapacity(key: CapacityKey, value: string): boolean {
101121 const kind = CAPACITY[key].kind;
102122 if (kind.type === "choice") return kind.values.includes(value);
123 if (kind.type === "rate")
124 return /^\d{1,3}(\.\d{1,6})?$/.test(value) && Number(value) <= kind.max;
103125 if (!/^\d+$/.test(value)) return false;
104126 const n = Number(value);
105127 return n >= kind.min && n <= kind.max;
@@ -201,6 +223,14 @@ export function egressSetting(db: Database): "enforce" | "report" {
201223 return capacityValue(db, "cells.egress") === "report" ? "report" : "enforce";
202224 }
203225
226 /** What compute is priced at now (`core/cost_ledger.ts`), US$ per vCPU-hour and GB-hour. */
227 export function computeRates(db: Database): { vcpuHour: number; gbHour: number } {
228 return {
229 vcpuHour: Number(capacityValue(db, "cost.vcpu_hour")),
230 gbHour: Number(capacityValue(db, "cost.gb_hour")),
231 };
232 }
233
204234 /** What a check's commands and a crew shell are told: the shard count, when one is set. */
205235 export function capacityEnv(db: Database): Record<string, string> {
206236 const shards = capacityValue(db, "checks.shards");
src/core/cost_ledger.ts added +466
@@ -0,0 +1,466 @@
1 /**
2 * The cost ledger (#1386): one entry per finished unit of work — an agent
3 * run, a check, a deploy — saying what it cost in tokens, compute and time,
4 * each entry naming the hash of the one before it and signed by the forge
5 * that wrote it. Append-only and hash-chained, so any reader with the
6 * ledger repository can recompute every link and every signature without
7 * trusting the pages (`scripts/ledger-verify.ts`). Not a token, not
8 * consensus, not a network: a chain of receipts.
9 *
10 * Units, stated once:
11 * - `wall_s` seconds from claim (`started_at`) to end (`finished_at`).
12 * - `lane_wait_s` seconds from queued (`created_at`) to claim: the time the
13 * work waited for a lane.
14 * - `cpu_s` CPU-seconds its cell used (user + system), `mem_gb_s`
15 * resident GiB × seconds — both from the cell's watch
16 * (`apps/contain.ts`); null when no cell measured it.
17 * - `usd_tokens` the provider's reported cost of the run's tokens, US$.
18 * - `usd_compute` cpu_s/3600 × `rate_vcpu_h` + mem_gb_s/3600 × `rate_gb_h`,
19 * US$, with the forge's rates written into the entry so the
20 * arithmetic can be redone; null when compute was not
21 * measured.
22 *
23 * Canonical form: the fields in `FIELDS` order, `JSON.stringify`d, numbers
24 * rounded as `entryFor` rounds them. `hash` = SHA-256(canonical) in hex;
25 * `sig` = Ed25519 over the hash's hex text (`kernel/ledger_key.ts`). The
26 * first entry's `prev` is 64 zeros.
27 *
28 * The chain's truth is the ledger repository in git (`core/ledger_write.ts`);
29 * the `cost_entry` table is its index. This module is pure data: no git,
30 * no authz, no events.
31 */
32
33 import type { Database } from "bun:sqlite";
34 import { sha256 } from "../kernel/hash.ts";
35 import { verifySignature } from "../kernel/ledger_key.ts";
36 import type { RunKind } from "./runs.ts";
37
38 export const GENESIS = "0".repeat(64);
39
40 export interface CostEntry {
41 readonly v: 1;
42 readonly seq: number;
43 readonly prev: string;
44 readonly run: string;
45 readonly kind: RunKind;
46 /** `owner/name` when the entry was written; `repo_id` survives a rename. */
47 readonly repo: string;
48 readonly repo_id: string;
49 readonly issue: number | null;
50 readonly pull: number | null;
51 readonly state: string;
52 readonly started_at: string;
53 readonly ended_at: string;
54 readonly wall_s: number;
55 readonly lane_wait_s: number;
56 readonly cpu_s: number | null;
57 readonly mem_gb_s: number | null;
58 readonly tokens_in: number;
59 readonly tokens_out: number;
60 readonly usd_tokens: number;
61 readonly rate_vcpu_h: number;
62 readonly rate_gb_h: number;
63 readonly usd_compute: number | null;
64 }
65
66 /** An entry as the ledger stores it: the entry, its hash, its signature. */
67 export interface SignedEntry extends CostEntry {
68 readonly hash: string;
69 readonly sig: string;
70 }
71
72 export const FIELDS: readonly (keyof CostEntry)[] = [
73 "v",
74 "seq",
75 "prev",
76 "run",
77 "kind",
78 "repo",
79 "repo_id",
80 "issue",
81 "pull",
82 "state",
83 "started_at",
84 "ended_at",
85 "wall_s",
86 "lane_wait_s",
87 "cpu_s",
88 "mem_gb_s",
89 "tokens_in",
90 "tokens_out",
91 "usd_tokens",
92 "rate_vcpu_h",
93 "rate_gb_h",
94 "usd_compute",
95 ];
96
97 export function canonical(entry: CostEntry): string {
98 const out: Record<string, unknown> = {};
99 for (const f of FIELDS) out[f] = entry[f];
100 return JSON.stringify(out);
101 }
102
103 export const entryHash = (entry: CostEntry): string => sha256(canonical(entry));
104
105 /** The line a batch file holds for one entry. */
106 export function entryLine(entry: SignedEntry): string {
107 const out: Record<string, unknown> = {};
108 for (const f of FIELDS) out[f] = entry[f];
109 out["hash"] = entry.hash;
110 out["sig"] = entry.sig;
111 return JSON.stringify(out);
112 }
113
114 // ---- building an entry from a run ----
115
116 /** What the compute is priced at, US$ per vCPU-hour and per GiB-hour. */
117 export interface Rates {
118 readonly vcpuHour: number;
119 readonly gbHour: number;
120 }
121
122 /** A finished run with what the ledger needs beside it, read in one query. */
123 export interface FinishedRun {
124 readonly id: string;
125 readonly kind: RunKind;
126 readonly repoId: string;
127 readonly repo: string;
128 readonly issueId: string | null;
129 readonly issueNumber: number | null;
130 readonly issueKind: "issue" | "pull" | null;
131 readonly state: string;
132 readonly createdAt: string;
133 readonly startedAt: string;
134 readonly finishedAt: string;
135 readonly cpuS: number | null;
136 readonly memGbS: number | null;
137 readonly tokensIn: number;
138 readonly tokensOut: number;
139 readonly costUsd: number;
140 }
141
142 const round = (n: number, places: number): number => {
143 if (!Number.isFinite(n) || n <= 0) return 0;
144 const f = 10 ** places;
145 return Math.round(n * f) / f;
146 };
147
148 const seconds = (from: string, to: string): number =>
149 (Date.parse(to) - Date.parse(from)) / 1000;
150
151 /** The unsigned entry for a finished run at `seq`, after `prev`. */
152 export function entryFor(
153 run: FinishedRun,
154 rates: Rates,
155 seq: number,
156 prev: string,
157 ): CostEntry {
158 const cpu = run.cpuS === null ? null : round(run.cpuS, 3);
159 const mem = run.memGbS === null ? null : round(run.memGbS, 3);
160 return {
161 v: 1,
162 seq,
163 prev,
164 run: run.id,
165 kind: run.kind,
166 repo: run.repo,
167 repo_id: run.repoId,
168 issue: run.issueKind === "issue" ? run.issueNumber : null,
169 pull: run.issueKind === "pull" ? run.issueNumber : null,
170 state: run.state,
171 started_at: run.startedAt,
172 ended_at: run.finishedAt,
173 wall_s: round(seconds(run.startedAt, run.finishedAt), 3),
174 lane_wait_s: round(seconds(run.createdAt, run.startedAt), 3),
175 cpu_s: cpu,
176 mem_gb_s: mem,
177 tokens_in: Math.round(Math.max(0, run.tokensIn)),
178 tokens_out: Math.round(Math.max(0, run.tokensOut)),
179 usd_tokens: round(run.costUsd, 6),
180 rate_vcpu_h: rates.vcpuHour,
181 rate_gb_h: rates.gbHour,
182 usd_compute:
183 cpu === null || mem === null
184 ? null
185 : round((cpu / 3600) * rates.vcpuHour + (mem / 3600) * rates.gbHour, 6),
186 };
187 }
188
189 export function sealEntry(
190 entry: CostEntry,
191 sign: (message: string) => string,
192 ): SignedEntry {
193 const hash = entryHash(entry);
194 return { ...entry, hash, sig: sign(hash) };
195 }
196
197 // ---- verification ----
198
199 export type ChainVerdict =
200 | { readonly ok: true; readonly count: number; readonly tip: string }
201 | {
202 readonly ok: false;
203 /** The first link that does not hold: its seq, or its line number when unreadable. */
204 readonly seq: number;
205 readonly reason: string;
206 };
207
208 /**
209 * Walk the chain from the first line: each must parse, carry the next seq,
210 * name the previous hash, hash to what it says, and be signed by
211 * `publicKey`. The first break is the verdict.
212 */
213 export function verifyChain(
214 lines: readonly string[],
215 publicKey: string,
216 ): ChainVerdict {
217 let prev = GENESIS;
218 let seq = 0;
219 for (const line of lines) {
220 const expected = seq + 1;
221 let parsed: Record<string, unknown>;
222 try {
223 const value: unknown = JSON.parse(line);
224 if (typeof value !== "object" || value === null || Array.isArray(value))
225 return { ok: false, seq: expected, reason: "not an entry" };
226 parsed = value as Record<string, unknown>;
227 } catch {
228 return { ok: false, seq: expected, reason: "not JSON" };
229 }
230 if (parsed["seq"] !== expected)
231 return {
232 ok: false,
233 seq: expected,
234 reason: `seq is ${String(parsed["seq"])}, expected ${expected}`,
235 };
236 if (parsed["prev"] !== prev)
237 return { ok: false, seq: expected, reason: "prev does not name the entry before" };
238 const hash = sha256(canonical(parsed as unknown as CostEntry));
239 if (parsed["hash"] !== hash)
240 return { ok: false, seq: expected, reason: "hash does not match the entry" };
241 if (
242 typeof parsed["sig"] !== "string" ||
243 !verifySignature(publicKey, hash, parsed["sig"])
244 )
245 return { ok: false, seq: expected, reason: "signature does not verify" };
246 prev = hash;
247 seq = expected;
248 }
249 return { ok: true, count: seq, tip: prev };
250 }
251
252 // ---- the index ----
253
254 /** The chain's head in the index: the last seq and hash, or the genesis. */
255 export function chainHead(db: Database): { seq: number; hash: string } {
256 const row = db
257 .query<{ seq: number; hash: string }, []>(
258 "SELECT seq, hash FROM cost_entry ORDER BY seq DESC LIMIT 1",
259 )
260 .get();
261 return row ?? { seq: 0, hash: GENESIS };
262 }
263
264 export function indexEntries(
265 db: Database,
266 entries: readonly SignedEntry[],
267 issueIds: ReadonlyMap<string, string | null>,
268 ): void {
269 const insert = db.query(
270 `INSERT OR IGNORE INTO cost_entry
271 (seq, run_id, repo_id, issue_id, kind, started_at, ended_at, wall_s, cpu_s,
272 mem_gb_s, lane_wait_s, tokens_in, tokens_out, usd_tokens, usd_compute,
273 prev, hash, line)
274 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)`,
275 );
276 db.transaction(() => {
277 for (const e of entries)
278 insert.run(
279 e.seq,
280 e.run,
281 e.repo_id,
282 issueIds.get(e.run) ?? null,
283 e.kind,
284 e.started_at,
285 e.ended_at,
286 e.wall_s,
287 e.cpu_s,
288 e.mem_gb_s,
289 e.lane_wait_s,
290 e.tokens_in,
291 e.tokens_out,
292 e.usd_tokens,
293 e.usd_compute,
294 e.prev,
295 e.hash,
296 entryLine(e),
297 );
298 })();
299 }
300
301 /**
302 * Finished runs the ledger has not entered yet, oldest end first. A run
303 * that never started did no work and is never entered; a run is settled
304 * once it finished before `settledBefore`, so the spend its runner writes
305 * just after finishing (`core/usage.ts`) is in its entry.
306 */
307 export function pendingRuns(
308 db: Database,
309 settledBefore: string,
310 limit: number,
311 ): FinishedRun[] {
312 return db
313 .query<
314 {
315 id: string;
316 kind: RunKind;
317 repo_id: string;
318 repo: string | null;
319 issue_id: string | null;
320 number: number | null;
321 issue_kind: "issue" | "pull" | null;
322 state: string;
323 created_at: string;
324 started_at: string;
325 finished_at: string;
326 cpu_s: number | null;
327 mem_gb_s: number | null;
328 tokens_in: number | null;
329 tokens_out: number | null;
330 usage_cost: number | null;
331 cost_usd: number;
332 },
333 [string, number]
334 >(
335 `SELECT r.id, r.kind, r.repo_id, u.username || '/' || p.name AS repo,
336 r.issue_id, i.number, i.kind AS issue_kind, r.state,
337 r.created_at, r.started_at, r.finished_at, r.cpu_s, r.mem_gb_s,
338 g.tokens_in, g.tokens_out, g.cost_usd AS usage_cost, r.cost_usd
339 FROM run r
340 LEFT JOIN cost_entry c ON c.run_id = r.id
341 LEFT JOIN repo p ON p.id = r.repo_id
342 LEFT JOIN user u ON u.id = p.owner_id
343 LEFT JOIN issue i ON i.id = r.issue_id
344 LEFT JOIN usage g ON g.run_id = r.id
345 WHERE c.run_id IS NULL
346 AND r.started_at IS NOT NULL AND r.finished_at IS NOT NULL
347 AND r.finished_at < ?1
348 ORDER BY r.finished_at, r.id
349 LIMIT ?2`,
350 )
351 .all(settledBefore, limit)
352 .map((r) => ({
353 id: r.id,
354 kind: r.kind,
355 repoId: r.repo_id,
356 repo: r.repo ?? "",
357 issueId: r.issue_id,
358 issueNumber: r.number,
359 issueKind: r.issue_kind,
360 state: r.state,
361 createdAt: r.created_at,
362 startedAt: r.started_at,
363 finishedAt: r.finished_at,
364 cpuS: r.cpu_s,
365 memGbS: r.mem_gb_s,
366 tokensIn: r.tokens_in ?? 0,
367 tokensOut: r.tokens_out ?? 0,
368 costUsd: r.usage_cost ?? r.cost_usd,
369 }));
370 }
371
372 // ---- roll-ups ----
373
374 export interface CostRollup {
375 readonly runs: number;
376 readonly usdTokens: number;
377 /** Over the runs whose compute was measured; `measured` says how many. */
378 readonly usdCompute: number;
379 readonly measured: number;
380 /** Seconds a check or deploy held a lane (their `wall_s`, summed). */
381 readonly laneS: number;
382 /** Seconds the work waited for a lane (`lane_wait_s`, summed). */
383 readonly waitS: number;
384 /** Seconds agents worked (`wall_s` of agent runs, summed). */
385 readonly agentS: number;
386 }
387
388 interface RollupRow {
389 runs: number;
390 usd_tokens: number | null;
391 usd_compute: number | null;
392 measured: number;
393 lane_s: number | null;
394 wait_s: number | null;
395 agent_s: number | null;
396 }
397
398 const ROLLUP = `SELECT COUNT(*) AS runs, SUM(usd_tokens) AS usd_tokens,
399 SUM(usd_compute) AS usd_compute, COUNT(usd_compute) AS measured,
400 SUM(CASE WHEN kind IN ('check','deploy') THEN wall_s END) AS lane_s,
401 SUM(lane_wait_s) AS wait_s,
402 SUM(CASE WHEN kind = 'agent' THEN wall_s END) AS agent_s
403 FROM cost_entry`;
404
405 const toRollup = (r: RollupRow | null): CostRollup => ({
406 runs: r?.runs ?? 0,
407 usdTokens: r?.usd_tokens ?? 0,
408 usdCompute: r?.usd_compute ?? 0,
409 measured: r?.measured ?? 0,
410 laneS: r?.lane_s ?? 0,
411 waitS: r?.wait_s ?? 0,
412 agentS: r?.agent_s ?? 0,
413 });
414
415 /** What the work on one issue or pull cost, summed over its entries. */
416 export function issueCost(db: Database, issueId: string): CostRollup {

Nothing outside the web pages reads this roll-up. Expose it (and dayCost for admins) through MCP / the JSON API with the same canSeeOwnerFacts gate, so the ledger can be reached through MCP as well as the page, as the direction requires.

417 return toRollup(
418 db
419 .query<RollupRow, [string]>(`${ROLLUP} WHERE issue_id = ?1`)
420 .get(issueId),
421 );
422 }
423
424 /** What the forge's work cost on one UTC day (`YYYY-MM-DD`), by when it ended. */
425 export function dayCost(db: Database, day: string): CostRollup {
426 return toRollup(
427 db
428 .query<RollupRow, [string, string]>(
429 `${ROLLUP} WHERE ended_at >= ?1 AND ended_at < ?2`,
430 )
431 .get(`${day}T00:00:00`, nextDay(day)),
432 );
433 }
434
435 const nextDay = (day: string): string =>
436 new Date(Date.parse(`${day}T00:00:00Z`) + 86_400_000).toISOString().slice(0, 10);
437
438 /** "$0.42 tokens · $0.01 compute · 31 lane-min · 2.1 h waiting" — empty when nothing was entered. */
439 export function ledgerLine(r: CostRollup): string {
outdated

Nit: web/studio/cost_line.ts already exports a costLine that means something else. Give this one a distinct name (e.g. ledgerLine) so imports can't mix them up.

440 if (r.runs === 0) return "";
441 const parts = [`$${r.usdTokens.toFixed(2)} tokens`];
442 if (r.measured > 0) parts.push(`$${r.usdCompute.toFixed(2)} compute`);
443 parts.push(`${Math.round(r.laneS / 60)} lane-min`);
444 parts.push(`${duration(r.waitS)} waiting`);
445 if (r.agentS > 0) parts.push(`${duration(r.agentS)} agent`);
446 return parts.join(" · ");
447 }
448
449 /**
450 * A change's lead time after its cost: " · open 3.0 h" while it is open,
451 * " · open→merged 90 min" once merged — empty for an issue (no `open`).
452 */
453 export function leadText(
454 open: { from: string; to: string | null } | undefined,
455 now: number = Date.now(),
456 ): string {
457 if (open === undefined) return "";
458 const to = open.to === null ? now : Date.parse(open.to);
459 return ` · ${open.to === null ? "open" : "open→merged"} ${duration((to - Date.parse(open.from)) / 1000)}`;
460 }
461
462 /** Seconds in the unit a person reads: minutes under two hours, hours after. */
463 export function duration(s: number): string {
464 if (s < 120 * 60) return `${Math.round(s / 60)} min`;
465 return `${(s / 3600).toFixed(1)} h`;
466 }
src/core/ledger_write.ts added +198
@@ -0,0 +1,198 @@
1 /**
2 * Where the cost ledger is kept: a bare repository the forge owns,
3 * `<data>/ledger.git`, branch `main`. Each sweep enters every settled,
4 * finished run not yet entered, as one batch file (`entries/<first seq>.jsonl`,
5 * one signed entry a line) in one commit, beside `forge.pub` — the public
6 * key every entry's signature verifies against. Git is truth: the
7 * `cost_entry` index is filled from the commit after it lands, and rebuilt
8 * from the repository whenever its tip is not the one this process last
9 * indexed (a crash between the two, another process's sweep).
10 *
11 * A sweep with nothing to enter writes nothing. Two processes sweeping at
12 * once (a release's overlap) cannot fork the chain: the commit lands only
13 * if the branch is still where the sweep read the chain's head from.
14 */
15
16 import { existsSync } from "node:fs";
17 import { join } from "node:path";
18 import type { App } from "../app.ts";
19 import { ledgerKey } from "../kernel/ledger_key.ts";
20 import { err, ok } from "../kernel/result.ts";
21 import { runGit, runGitRaw } from "../git/env.ts";
22 import { resolveOid } from "../git/merge.ts";
23 import { initBareRepo } from "../git/repos.ts";
24 import { commitFiles } from "../git/write.ts";
25 import { computeRates } from "./capacity.ts";
26 import {
27 chainHead,
28 entryFor,
29 entryLine,
30 indexEntries,
31 pendingRuns,
32 sealEntry,
33 type SignedEntry,
34 } from "./cost_ledger.ts";
35
36 export const LEDGER_BRANCH = "main";
37 /** A run finished this recently may still have its spend on the way. */
38 export const SETTLE_MS = 30_000;
39 const BATCH_MAX = 500;
40
41 export const ledgerDir = (dataDir: string): string => join(dataDir, "ledger.git");
42
43 /** The commit each ledger's index was last filled from, by directory. */
44 const indexedTip = new Map<string, string | undefined>();
45 /** One sweep at a time per ledger, in this process. */
46 const sweeping = new Set<string>();
47
48 /** Every entry line in the ledger at `commit`, in chain order, and its public key. */
49 export async function readLedger(
50 dir: string,
51 commit = `refs/heads/${LEDGER_BRANCH}`,
52 ): Promise<{ publicKey: string; lines: string[] }> {
53 const listed = await runGit(["ls-tree", "-r", "-z", commit, "--", "entries/", "forge.pub"], {
54 cwd: dir,
55 });
56 if (!listed.ok) return { publicKey: "", lines: [] };
57 const files = listed.value
58 .split("\0")
59 .filter((l) => l !== "")
60 .map((l) => {
61 const [meta = "", path = ""] = l.split("\t");
62 return { oid: meta.split(" ")[2] ?? "", path };
63 })
64 .filter((f) => /^[0-9a-f]{40,64}$/.test(f.oid))
65 .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
66 if (files.length === 0) return { publicKey: "", lines: [] };
67 const raw = await runGitRaw(["cat-file", "--batch"], {
68 cwd: dir,
69 stdin: files.map((f) => f.oid).join("\n") + "\n",
70 timeoutMs: 120_000,
71 });
72 if (!raw.ok) return { publicKey: "", lines: [] };
73 const bytes = raw.value;
74 const decoder = new TextDecoder();
75 const blobs: string[] = [];
76 let at = 0;
77 while (at < bytes.length) {
78 const nl = bytes.indexOf(10, at);
79 if (nl < 0) break;
80 const size = Number(decoder.decode(bytes.subarray(at, nl)).split(" ")[2]);
81 if (!Number.isInteger(size)) break;
82 blobs.push(decoder.decode(bytes.subarray(nl + 1, nl + 1 + size)));
83 at = nl + 1 + size + 1;
84 }
85 let publicKey = "";
86 const lines: string[] = [];
87 files.forEach((f, i) => {
88 const text = blobs[i] ?? "";
89 if (f.path === "forge.pub") publicKey = text.trim();
90 else for (const line of text.split("\n")) if (line !== "") lines.push(line);
91 });
92 return { publicKey, lines };
93 }
94
95 /**
96 * The ledger's entries numbered past `seq`. As `verifyChain` does, the chain
97 * is read up to its first line that does not parse: the entries before it
98 * are indexed, and the line is logged rather than thrown on every sweep.
99 */
100 export function entriesPast(lines: readonly string[], seq: number): SignedEntry[] {
101 const entries: SignedEntry[] = [];
outdated

This isn't guarded. One line that doesn't parse throws on every sweep from then on, so the ledger never advances again. Skip the line and log it, or stop at it the way verifyChain does.

102 for (const [i, line] of lines.entries()) {
103 let entry: SignedEntry;
104 try {
105 entry = JSON.parse(line) as SignedEntry;
106 } catch {
107 console.error(`cost ledger: line ${i + 1} does not parse; the index stops before it`);
108 break;
109 }
110 if (entry.seq > seq) entries.push(entry);
111 }
112 return entries;
113 }
114
115 /** Fill the index with what the ledger holds past the index's head. */
116 async function reindex(app: App, dir: string, tip: string): Promise<void> {
117 const head = chainHead(app.db);
118 const { lines } = await readLedger(dir, tip);
119 const entries = entriesPast(lines, head.seq);
120 if (entries.length === 0) return;
121 const issues = new Map<string, string | null>();
122 const lookup = app.db.query<{ issue_id: string | null }, [string]>(
123 "SELECT issue_id FROM run WHERE id = ?1",
124 );
125 for (const e of entries) issues.set(e.run, lookup.get(e.run)?.issue_id ?? null);
126 indexEntries(app.db, entries, issues);
127 }
128
129 /**
130 * Enter every settled, finished run not yet entered. Returns how many
131 * entries were written: zero when there was nothing to enter, or when
132 * another writer moved the ledger first (the next sweep catches up).
133 */
134 export async function sweepLedger(
135 app: App,
136 now: number = Date.now(),
137 ): Promise<number> {
138 const dir = ledgerDir(app.config.dataDir);
139 if (sweeping.has(dir)) return 0;
140 sweeping.add(dir);
141 try {
142 if (!existsSync(dir)) {
143 const made = await initBareRepo(dir, { defaultBranch: LEDGER_BRANCH });
144 if (!made.ok) return 0;
145 }
146 const tip = await resolveOid(dir, `refs/heads/${LEDGER_BRANCH}`);
147 // Behind git: another writer's batch, a crash between commit and
148 // index, or an index rebuilt from nothing.
149 if (
150 tip !== undefined &&
151 (indexedTip.get(dir) !== tip || chainHead(app.db).seq === 0)
152 ) {
153 await reindex(app, dir, tip);
154 indexedTip.set(dir, tip);
155 }
156 const pending = pendingRuns(
157 app.db,
158 new Date(now - SETTLE_MS).toISOString(),
159 BATCH_MAX,
160 );
161 if (pending.length === 0) return 0;
162 const key = ledgerKey(app.config.dataDir);
163 const rates = computeRates(app.db);
164 let head = chainHead(app.db);
165 const entries: SignedEntry[] = [];
166 const issues = new Map<string, string | null>();
167 for (const run of pending) {
168 const entry = sealEntry(entryFor(run, rates, head.seq + 1, head.hash), key.sign);
169 entries.push(entry);
170 issues.set(run.id, run.issueId);
171 head = { seq: entry.seq, hash: entry.hash };
172 }
173 const first = entries[0]!.seq;
174 const committed = await commitFiles(dir, {
175 branch: LEDGER_BRANCH,
176 message: `ledger: entries ${first}–${head.seq}\n\ntip ${head.hash}\n`,
177 files: [
178 { path: "forge.pub", content: `${key.publicKey}\n` },
179 {
180 path: `entries/${String(first).padStart(12, "0")}.jsonl`,
181 content: entries.map(entryLine).join("\n") + "\n",
182 },
183 ],
184 author: { name: "forge ledger", email: "[email protected]" },
185 land: async (_commit, current) =>
186 current === tip ? ok() : err("the ledger moved under this sweep"),
187 });
188 if (!committed.ok) {
189 indexedTip.delete(dir);
190 return 0;
191 }
192 indexEntries(app.db, entries, issues);
193 indexedTip.set(dir, committed.value.commitOid);
194 return entries.length;
195 } finally {
196 sweeping.delete(dir);
197 }
198 }
src/core/runs.ts +12
@@ -78,6 +78,9 @@ export interface Run {
7878 readonly sandboxNote: string;
7979 /** A failed check's own detail, when its output was recognised; null otherwise. */
8080 readonly checkDetail: CheckDetail | null;
81 /** CPU-seconds and GiB-seconds its cell's watch measured; null when not measured. */
82 readonly cpuS: number | null;
83 readonly memGbS: number | null;
8184 readonly createdAt: string;
8285 readonly startedAt: string | null;
8386 /** When this deploy's environment started serving — set once, at the swap-in. */
@@ -106,6 +109,8 @@ interface RunRow {
106109 sandbox_enforced: number | null;
107110 sandbox_note: string;
108111 check_detail: string;
112 cpu_s: number | null;
113 mem_gb_s: number | null;
109114 created_at: string;
110115 started_at: string | null;
111116 serving_at: string | null;
@@ -134,6 +139,8 @@ const toRun = (r: RunRow): Run => ({
134139 r.sandbox_enforced === null ? null : r.sandbox_enforced !== 0,
135140 sandboxNote: r.sandbox_note,
136141 checkDetail: r.check_detail ? (JSON.parse(r.check_detail) as CheckDetail) : null,
142 cpuS: r.cpu_s,
143 memGbS: r.mem_gb_s,
137144 createdAt: r.created_at,
138145 startedAt: r.started_at,
139146 servingAt: r.serving_at,
@@ -257,6 +264,8 @@ export function finishRun(
257264 turns?: number | undefined;
258265 /** A failed check's own detail, when its output was recognised. */
259266 checkDetail?: CheckDetail | undefined;
267 /** What its cell used (`apps/contain.ts` `CellUsage`), when one was measured. */
268 usage?: { cpuS: number; memGbS: number } | undefined;
260269 },
261270 ): Run | undefined {
262271 const changes = db
@@ -264,6 +273,7 @@ export function finishRun(
264273 `UPDATE run SET state = ?2, summary = ?3,
265274 session_id = COALESCE(?4, session_id), cost_usd = COALESCE(?5, cost_usd),
266275 turns = COALESCE(?6, turns), check_detail = ?7,
276 cpu_s = COALESCE(?8, cpu_s), mem_gb_s = COALESCE(?9, mem_gb_s),
267277 finished_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
268278 WHERE id = ?1 AND state = 'running'`,
269279 )
@@ -275,6 +285,8 @@ export function finishRun(
275285 outcome.costUsd ?? null,
276286 outcome.turns ?? null,
277287 outcome.checkDetail ? JSON.stringify(outcome.checkDetail) : "",
288 outcome.usage?.cpuS ?? null,
289 outcome.usage?.memGbS ?? null,
278290 ).changes;
279291 return changes > 0 ? getRun(db, runId) : undefined;
280292 }
src/core/schema.ts +31
@@ -1595,6 +1595,37 @@ export const migrations: readonly string[] = [
15951595 PRIMARY KEY (repo_id, parent_id, issue_id)
15961596 );
15971597 `,
1598 // 76 — the cost ledger (#1386, `core/cost_ledger.ts`). A run's compute as
1599 // its cell's watch measured it (NULL: not measured — no cell, or a kind
1600 // that runs outside one), and the chain of cost entries, one per finished
1601 // run. The chain's truth is the ledger repository in git; this table is
1602 // its index, rebuilt from git when it is behind.
1603 `
1604 ALTER TABLE run ADD COLUMN cpu_s REAL;
1605 ALTER TABLE run ADD COLUMN mem_gb_s REAL;
1606 CREATE TABLE IF NOT EXISTS cost_entry (
1607 seq INTEGER PRIMARY KEY,
1608 run_id TEXT NOT NULL UNIQUE,
1609 repo_id TEXT NOT NULL,
1610 issue_id TEXT,
1611 kind TEXT NOT NULL,
1612 started_at TEXT NOT NULL,
1613 ended_at TEXT NOT NULL,
1614 wall_s REAL NOT NULL,
1615 cpu_s REAL,
1616 mem_gb_s REAL,
1617 lane_wait_s REAL NOT NULL,
1618 tokens_in INTEGER NOT NULL,
1619 tokens_out INTEGER NOT NULL,
1620 usd_tokens REAL NOT NULL,
1621 usd_compute REAL,
1622 prev TEXT NOT NULL,
1623 hash TEXT NOT NULL UNIQUE,
1624 line TEXT NOT NULL
1625 );
1626 CREATE INDEX IF NOT EXISTS cost_entry_issue ON cost_entry(issue_id);
1627 CREATE INDEX IF NOT EXISTS cost_entry_ended ON cost_entry(ended_at);
1628 `,
15981629 ];
15991630
16001631 /**
src/http/api.ts +25
@@ -289,6 +289,7 @@ import {
289289 } from "../core/runs.ts";
290290 import { resolveOid } from "../git/merge.ts";
291291 import { readUsage, usageDays, USAGE_DAYS_MAX } from "../actions/usage.ts";
292 import { costDay, readDayCost, readIssueCost } from "../actions/cost.ts";
292293 import { readReturns, reportSpend, RETURNS_DAYS } from "../actions/returns.ts";
293294 import { fleetSelection, readFleetGraph } from "../actions/fleet-graph.ts";
294295 import { readRunLog, subscribeRunLog } from "../runs/log.ts";
@@ -1269,6 +1270,18 @@ export function apiRoutes(router: Router<Handler>): void {
12691270 );
12701271 });
12711272
1273 // The forge's day by the cost ledger (`actions/cost.ts`), `?day=YYYY-MM-DD`
1274 // (UTC, today when absent): the board's forge line, for an admin.
1275 router.add("GET", "/api/v1/admin/cost", (ctx) => {
1276 const denied = accountAdmin(ctx, "ro");
1277 if (denied) return denied;
1278 const day = costDay(ctx.url.searchParams.get("day"));
1279 if (day === undefined)
1280 return apiError("invalid_day", 422, "day is a UTC date, YYYY-MM-DD");
1281 const report = readDayCost(ctx.app, ctx.auth.user, day);
1282 return report.ok ? json(report.value) : notFound();
1283 });
1284
12721285 router.add("GET", "/api/v1/admin/accounts", (ctx) => {
12731286 const denied = accountAdmin(ctx, "ro");
12741287 if (denied) return denied;
@@ -4499,6 +4512,18 @@ export function apiRoutes(router: Router<Handler>): void {
44994512 return json(report.value);
45004513 });
45014514
4515 // What one issue or pull cost by the cost ledger (`actions/cost.ts`):
4516 // the owner's fact, like the line on its page.
4517 router.add("GET", "/api/v1/repos/:owner/:name/issues/:number/cost", (ctx) => {
4518 const repo = loadRepo(ctx);
4519 if (!repo) return notFound();
4520 const number = positiveInt(ctx.params.number);
4521 if (number === undefined) return notFound();
4522 const report = readIssueCost(ctx.app, ctx.auth.user, repo, number);
4523 if (report.ok) return json(report.value);
4524 return report.error === "forbidden" ? forbidden() : notFound();
4525 });
4526
45024527 // The fleet graph's numbers (`actions/fleet-graph.ts`): spend and runs
45034528 // per repository by UTC hour (24 h) and day (14 d), for `?repo=owner/name`
45044529 // repeated, or every repository the caller may write that spent lately.
src/http/mcp.ts +39 −2
@@ -54,6 +54,7 @@ import {
5454 USAGE_DAYS_DEFAULT,
5555 USAGE_DAYS_MAX,
5656 } from "../actions/usage.ts";
57 import { costDay, readDayCost, readIssueCost } from "../actions/cost.ts";
5758 import { ITEM_ID } from "../core/interactions.ts";
5859 import {
5960 FEED_LIMIT_DEFAULT,
@@ -1489,6 +1490,42 @@ const TOOLS: readonly Tool[] = [
14891490 : bad("forbidden", "spend is for those who can write this app");
14901491 },
14911492 },
1493 {
1494 name: "cost",
1495 description:
1496 "What work cost by the forge's cost ledger, as the pages show it. With `repo` and `issue` (an issue or pull number): its entries summed — usdTokens, usdCompute (priced CPU and memory; `measured` says how many runs had a cell to measure), laneS (seconds its checks and deploys held a lane), waitS (seconds it waited for one), agentS, runs — and `line`, the page's `cost:` text. Refused unless you can write the app. Without them: the forge's totals for `day` (UTC, YYYY-MM-DD, default today), for a forge admin only. The same as /api/v1/repos/:owner/:name/issues/:number/cost and /api/v1/admin/cost.",
1497 inputSchema: {
1498 type: "object",
1499 properties: {
1500 repo: REPO_ARG,
1501 issue: { type: "integer", minimum: 1 },
1502 day: { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$" },
1503 },
1504 },
1505 writes: false,
1506 run(ctx, user, args) {
1507 if (args["repo"] === undefined && args["issue"] === undefined) {
1508 const raw = args["day"];
1509 const day =
1510 raw === undefined || typeof raw === "string" ? costDay(raw) : undefined;
1511 if (day === undefined) return bad("invalid_day", "day is a UTC date, YYYY-MM-DD");
1512 const report = readDayCost(ctx.app, user, day);
1513 return report.ok
1514 ? good(report.value)
1515 : bad("forbidden", "only an admin of this forge sees the day's cost");
1516 }
1517 const repo = repoArg(ctx, user, args);
1518 if (isAnswer(repo)) return repo;
1519 const number = args["issue"];
1520 if (typeof number !== "number" || !Number.isInteger(number) || number < 1)
1521 return bad("invalid", "issue is the number of an issue or pull in the app");
1522 const report = readIssueCost(ctx.app, user, repo, number);
1523 if (report.ok) return good(report.value);
1524 return report.error === "forbidden"
1525 ? bad("forbidden", "cost is for those who can write this app")
1526 : bad("not_found", `no issue or pull #${number} here`);
1527 },
1528 },
14921529 {
14931530 name: "link",
14941531 description:
@@ -1754,13 +1791,13 @@ const TOOLS: readonly Tool[] = [
17541791 {
17551792 name: "capacity",
17561793 description:
1757 "The forge's capacity and guards, live: crew runs at once (crew.concurrency), checks at once (checks.concurrency), test shards per check (checks.shards), whether a cell's undeclared egress is refused or reported (cells.egress), and whether new accounts may create repositories and forks (guard_new_accounts: on refuses accounts younger than 7 days, off is the default). Without `key`, each setting, its value and where it comes from, and the recent changes. With `key` and `value` (\"\" goes back to the boot default), the change it would make; with dryRun false, made, by a forge admin with an admin-scope token, never an agent. A change is honoured by the next run, check or cell, never by a restart. The same as Settings → Capacity and /api/v1/admin/capacity.",
1794 "The forge's capacity and guards, live: crew runs at once (crew.concurrency), checks at once (checks.concurrency), test shards per check (checks.shards), whether a cell's undeclared egress is refused or reported (cells.egress), whether new accounts may create repositories and forks (guard_new_accounts: on refuses accounts younger than 7 days, off is the default), and what compute costs on this node for the cost ledger (cost.vcpu_hour, cost.gb_hour: US$ per vCPU-hour and per GB-hour, up to six decimals). Without `key`, each setting, its value and where it comes from, and the recent changes. With `key` and `value` (\"\" goes back to the boot default), the change it would make; with dryRun false, made, by a forge admin with an admin-scope token, never an agent. A change is honoured by the next run, check or cell, never by a restart. The same as Settings → Capacity and /api/v1/admin/capacity.",
17581795 inputSchema: {
17591796 type: "object",
17601797 properties: {
17611798 key: {
17621799 type: "string",
1763 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts"],
1800 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts", "cost.vcpu_hour", "cost.gb_hour"],
17641801 },
17651802 value: { type: "string", maxLength: 16 },
17661803 dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." },
src/kernel/ledger_key.ts added +85
@@ -0,0 +1,85 @@
1 /**
2 * The key a forge signs its cost ledger with: Ed25519, derived from the
3 * data directory's `secret.key` (HKDF-SHA256, info `forge cost ledger v1`)
4 * so it needs no file of its own, survives a snapshot and restore with the
5 * key it came from, and never appears anywhere but in this process. The
6 * public half is published in the ledger repository (`forge.pub`), so a
7 * reader holding only the repository checks every signature without
8 * trusting the pages that show the numbers.
9 *
10 * Signatures and public keys are base64url, raw (32-byte key, 64-byte sig).
11 */
12
13 import {
14 createPrivateKey,
15 createPublicKey,
16 hkdfSync,
17 sign,
18 verify,
19 type KeyObject,
20 } from "node:crypto";
21 import { loadKey } from "./secret.ts";
22
23 /** RFC 8410 PKCS#8 header for a raw 32-byte Ed25519 seed. */
24 const PKCS8_ED25519 = Buffer.from("302e020100300506032b657004220420", "hex");
25 /** RFC 8410 SPKI header for a raw 32-byte Ed25519 public key. */
26 const SPKI_ED25519 = Buffer.from("302a300506032b6570032100", "hex");
27
28 export interface LedgerKey {
29 /** The public key, raw, base64url — what `forge.pub` holds. */
30 readonly publicKey: string;
31 readonly sign: (message: string) => string;
32 }
33
34 const cache = new Map<string, LedgerKey>();
35
36 /** The ledger key for a 32-byte seed — the data directory's or a test's. */
37 export function ledgerKeyFromSecret(secret: Uint8Array): LedgerKey {
38 const seed = Buffer.from(
39 hkdfSync("sha256", secret, Buffer.alloc(0), "forge cost ledger v1", 32),
40 );
41 const key: KeyObject = createPrivateKey({
42 key: Buffer.concat([PKCS8_ED25519, seed]),
43 format: "der",
44 type: "pkcs8",
45 });
46 const jwk = createPublicKey(key).export({ format: "jwk" });
47 return {
48 publicKey: String(jwk.x),
49 sign: (message) =>
50 sign(null, Buffer.from(message, "utf8"), key).toString("base64url"),
51 };
52 }
53
54 export function ledgerKey(dataDir: string): LedgerKey {
55 const known = cache.get(dataDir);
56 if (known) return known;
57 const made = ledgerKeyFromSecret(loadKey(dataDir));
58 cache.set(dataDir, made);
59 return made;
60 }
61
62 /** Whether `signature` is `publicKey`'s over `message`. Never throws. */
63 export function verifySignature(
64 publicKey: string,
65 message: string,
66 signature: string,
67 ): boolean {
68 try {
69 const raw = Buffer.from(publicKey, "base64url");
70 if (raw.length !== 32) return false;
71 const key = createPublicKey({
72 key: Buffer.concat([SPKI_ED25519, raw]),
73 format: "der",
74 type: "spki",
75 });
76 return verify(
77 null,
78 Buffer.from(message, "utf8"),
79 key,
80 Buffer.from(signature, "base64url"),
81 );
82 } catch {
83 return false;
84 }
85 }
src/main.ts +13
@@ -4,6 +4,7 @@
44 * environment-only — a handful of variables, all with sane defaults.
55 */
66
7 import { sweepLedger } from "./core/ledger_write.ts";
78 import { parseCidrs } from "./kernel/cidr.ts";
89 import { createApp } from "./app.ts";
910 import { reconcile } from "./core/reconcile.ts";
@@ -333,6 +334,17 @@ const tickAsks = async (): Promise<void> => {
333334 const staleTimer = setInterval(() => void tickAsks(), 120_000);
334335 void tickAsks();
335336
337 // The cost ledger (`core/ledger_write.ts`): every finished run, entered
338 // once, chained and signed, committed to `<data>/ledger.git`. A minute's
339 // tick with nothing finished writes nothing.
340 const sweepCosts = (): void => {
341 sweepLedger(app).catch((error) =>
342 app.log.error("cost ledger sweep failed", { error: String(error) }),
343 );
344 };
345 const ledgerTimer = setInterval(sweepCosts, 60_000);
346 sweepCosts();
347
336348 app.log.info("forge is up", { url: servers.url, data: app.config.dataDir });
337349 // Only an agent is on a crew (the `repo_crew_agents_only` trigger refuses anyone else). A person
338350 // put on one before that is reported here for the owner to take off — the
@@ -403,6 +415,7 @@ function shutdown(signal: NodeJS.Signals): void {
403415 clearInterval(syncTimer);
404416 clearInterval(staleTimer);
405417 clearInterval(leaseTimer);
418 clearInterval(ledgerTimer);
406419 Promise.all([
407420 prompts.stop(),
408421 notifier.stop(),
src/tui/screens/issue.ts +31 −2
@@ -19,6 +19,7 @@ import {
1919 setIssueLabelsThrough,
2020 setIssueStateThrough,
2121 } from "../../actions/issues.ts";
22 import { readIssueCost } from "../../actions/cost.ts";
2223 import { listRepoRuns } from "../../actions/runs.ts";
2324 import { alreadyDone } from "../../core/done_on_main.ts";
2425 import { getIssue, type Issue, type Label } from "../../core/issues.ts";
@@ -53,6 +54,22 @@ import { local, localRepo, whereRows, whereStrip } from "./where.ts";
5354 /** The crew card shows this many runs before it scrolls. */
5455 const CREW_ROWS = 4;
5556
57 /**
58 * The cost ledger's line for one issue or pull, as the page prints it after
59 * `cost:` — through `readIssueCost`, so the terminal is gated as the page,
60 * the API and MCP are. "" on a live browse, to a stranger, or before any
61 * entry.
62 */
63 export function costLine(
64 f: Session,
65 repo: Repo | undefined,
66 number: number,
67 ): string {
68 if (repo === undefined) return "";
69 const read = readIssueCost(f.app, f.user, repo, number);
70 return read.ok ? read.value.line : "";
71 }
72
5673 /** The status-line tail for an issue the crew found done on main. */
5774 export function doneText(commits: readonly string[], canClose: boolean): string {
5875 if (commits.length === 0) return "";
@@ -82,6 +99,8 @@ export function issueScreen(
8299 const crew = new RunList(f);
83100 /** Which pane `j`/`k`/`enter` belong to; `tab` moves between them. */
84101 let focus: "thread" | "crew" = "thread";
102 /** The cost ledger's line, behind the page's gate — "" when not shown. */
103 let cost = "";
85104 const mayWrite = (): boolean => src.capabilities.write && repo !== undefined;
86105 scroll.top = keep.top ?? 0;
87106
@@ -108,6 +127,7 @@ export function issueScreen(
108127 : [];
109128 crew.set(runs !== undefined && runs.ok ? runs.value : []);
110129 if (crew.runs.length === 0) focus = "thread";
130 cost = costLine(f, repo, number);
111131 width = 0;
112132 ctx.invalidate();
113133 const listed = await src.labels();
@@ -238,13 +258,14 @@ export function issueScreen(
238258 const issue = detail.issue;
239259 const foot = composer.height();
240260 // The where-strip, then three rows of head: the title, the summary
241 // line, and one blank so the first entry is not glued to the metadata.
261 // line (and the cost line, when the ledger has one for this reader),
262 // and one blank so the first entry is not glued to the metadata.
242263 // Then the crew card, only when an agent has worked here.
243264 const crewH =
244265 crew.runs.length === 0 ? 0 : Math.min(crew.runs.length, CREW_ROWS) + 2;
245266 const [strip, head, crewRow, body, box] = split(area, "v", [
246267 len(whereRows(src)),
247 len(3),
268 len(cost === "" ? 3 : 4),
248269 len(crewH),
249270 fill(1),
250271 len(Math.min(foot, Math.max(0, area.h - 7 - crewH - whereRows(src)))),
@@ -288,6 +309,14 @@ export function issueScreen(
288309 { text: label.name, color: label.color },
289310 right,
290311 );
312 if (cost !== "")
313 s.text(
314 head!.x,
315 head!.y + 2,
316 truncate(`cost: ${cost}`, head!.w),
317 style(c.mutedFg, c.bg),
318 right,
319 );
291320 if (crewH > 0) {
292321 const inner = card(s, crewRow!, c, {
293322 title: `Crew · ${plural(crew.runs.length, "run")}`,
src/tui/screens/pull.ts +18 −1
@@ -45,6 +45,7 @@ import {
4545 type EnvState,
4646 type EnvStatus, envsFor } from "../../apps/runtime.ts";
4747 import { getAppByRepo } from "../../core/apps.ts";
48 import { leadText } from "../../core/cost_ledger.ts";
4849 import { getIssue, type Issue } from "../../core/issues.ts";
4950 import { getPull, type Pull } from "../../core/pulls.ts";
5051 import { getRepoById, type Repo } from "../../core/repos.ts";
@@ -96,6 +97,7 @@ import {
9697 runAsync,
9798 } from "./common.ts";
9899 import { assignPicker, assignedText } from "./assign.ts";
100 import { costLine } from "./issue.ts";
99101 import { DiffView, type DiffAnchor, type DiffNote } from "./commits.ts";
100102 import { liveBindings, liveKey } from "./mirror.ts";
101103 import { reviewScreen } from "./review.ts";
@@ -218,6 +220,8 @@ export function pullScreen(
218220 let check: CheckSummary = NO_CHECK;
219221 /** Agent runs about this pull, newest first. */
220222 const crew = new RunList(f);
223 /** The cost ledger's line, behind the page's gate — "" when not shown. */
224 let cost = "";
221225 const mayWrite = (): boolean => src.capabilities.write && repo !== undefined;
222226 scroll.top = keep.top ?? 0;
223227
@@ -244,6 +248,7 @@ export function pullScreen(
244248 : withOutdated(listReviewComments(f.db, row.id), diff);
245249 threads = row === undefined ? [] : readThreads(row);
246250 issueRow = repo === undefined ? undefined : getIssue(f.db, repo.id, number);
251 cost = costLine(f, repo, number);
247252 // The app half: the preview environment (in memory, from the runtime),
248253 // the checks at the live head (a row), and what the crew has done here.
249254 const record = repo === undefined ? undefined : getAppByRepo(f.db, repo.id);
@@ -653,7 +658,7 @@ export function pullScreen(
653658 "v",
654659 [
655660 len(whereRows(src)),
656 len(2),
661 len(cost === "" ? 2 : 3),
657662 len(isApp ? 1 : 0),
658663 len(boxH),
659664 len(2),
@@ -694,6 +699,18 @@ export function pullScreen(
694699 style(c.mutedFg, c.bg),
695700 edge,
696701 );
702 // The cost, and how long the change has been open (or took), as the page.
703 if (cost !== "")
704 s.text(
705 head!.x,
706 head!.y + 2,
707 truncate(
708 `cost: ${cost}${leadText({ from: issue.createdAt, to: facts?.mergedAt ?? null })}`,
709 head!.w,
710 ),
711 style(c.mutedFg, c.bg),
712 edge,
713 );
697714 if (isApp && previewRow!.h > 0)
698715 drawPreviewLine(s, previewRow!, c, preview);
699716 drawMergeBox(s, boxRow!, c, issue, facts, view.summary(), mirrored(), {
src/web/pages/board.ts +5
@@ -14,6 +14,7 @@
1414 * pointer. The old big view (`/big`, every address it had) lands here.
1515 */
1616
17 import { ledgerLine, dayCost } from "../../core/cost_ledger.ts";
1718 import { appsForRepos, type AppRecord } from "../../core/apps.ts";
1819 import { askMeasure } from "../../core/ask_ledger.ts";
1920 import { reviewersOf, waitsForPerson } from "../../crew/review.ts";
@@ -334,6 +335,9 @@ function forgeStrip(ctx: Ctx): Html | null {
334335 (i) => i.key !== "stuck" && i.key !== "held",
335336 );
336337 const ok = v.ok && fh.ok;
338 // The day's work as the cost ledger has it (`core/cost_ledger.ts`): what
339 // ended today, UTC — nothing until something did.
340 const today = ledgerLine(dayCost(app.db, new Date().toISOString().slice(0, 10)));
337341 return html`<div
338342 class="board-forge"
339343 id="forge"
@@ -354,6 +358,7 @@ function forgeStrip(ctx: Ctx): Html | null {
354358 : html`<a class="board-forge-need" href="${href}">${need}</a>`;
355359 })
outdated

No test covers this line. Add one: an admin's board shows #day-cost after a sweep, a non-admin's doesn't, and it isn't there before anything was entered.

356360 }
361 ${today === "" ? "" : html`<span class="board-forge-cost" id="day-cost">today: ${today}</span>`}
357362 </div>`;
358363 }
359364
src/web/pages/capacity.ts +11
@@ -37,6 +37,17 @@ function input(key: CapacityKey, value: string) {
3737 </option>`,
3838 )}
3939 </select>`;
40 if (kind.type === "rate")
41 return html`<input
42 class="input mono"
43 type="number"
44 name="value"
45 min="0"
46 max="${String(kind.max)}"
47 step="0.000001"
48 value="${value}"
49 aria-label="${CAPACITY[key].label}"
50 />`;
4051 return html`<input
4152 class="input mono"
4253 type="number"
src/web/pages/runs.ts +22
@@ -18,6 +18,7 @@ import {
1818 runLog,
1919 steerRepoRun,
2020 } from "../../actions/runs.ts";
21 import { ledgerLine, issueCost, leadText } from "../../core/cost_ledger.ts";
2122 import { getIssuesByIds, type Issue } from "../../core/issues.ts";
2223 import {
2324 canRead,
@@ -113,6 +114,27 @@ export function workSpent(ctx: Ctx, repo: Repo, issueId: string): Html {
113114 >`;
114115 }
115116
117 /**
118 * What the work on one issue or pull cost by the cost ledger
119 * (`core/cost_ledger.ts`): tokens and compute in dollars, the minutes its
120 * checks and deploys held a lane, the time it waited for one — and, for a
121 * change, how long it has been open (or took, open to merged): lead time
122 * is a cost beside the dollars. Owner's facts, like `workSpent`; nothing
123 * before the ledger has an entry for it.
124 */
125 export function ledgerCost(
126 ctx: Ctx,
127 repo: Repo,
128 issueId: string,
129 open?: { from: string; to: string | null } | undefined,
130 ): Html {
131 if (!canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user)) return html``;
132 const line = ledgerLine(issueCost(ctx.app.db, issueId));
133 if (line === "") return html``;
134 const lead = leadText(open);
135 return html`<span class="num" id="ledger-cost">cost: ${line}${lead}</span>`;
136 }
137
outdated

The open / open→merged lead time is new behaviour with no test. Render a pull's change page (open, then merged) and assert the text. The issue-page test doesn't reach this branch.

116138 /**
117139 * What a finished agent run read and wrote, in tokens, from the usage ledger
118140 * (`core/usage.ts`) — counted by the provider, so no tilde. Placed beside the
src/web/studio/change.ts +5 −1
@@ -59,7 +59,7 @@ import {
5959 import { previewCard } from "../pages/apps.ts";
6060 import { lookCard } from "../pages/looks.ts";
6161 import { pullState } from "../pages/pulls.ts";
62 import { workSpent } from "../pages/runs.ts";
62 import { ledgerCost, workSpent } from "../pages/runs.ts";
6363 import {
6464 composer,
6565 conversation,
@@ -204,6 +204,10 @@ export function changeHead(ctx: Ctx, repo: Repo, pull: Pull): Html {
204204 >`,
205205 )}
206206 ${workSpent(ctx, repo, pull.id)}
207 ${ledgerCost(ctx, repo, pull.id, {
208 from: pull.createdAt,
209 to: pull.mergedAt,
210 })}
207211 </div>
208212 </div>`;
209213 }
src/web/studio/tell.ts +2 −1
@@ -48,6 +48,7 @@ import {
4848 costText,
4949 durationText,
5050 reasonWords,
51 ledgerCost,
5152 workSpent,
5253 } from "../pages/runs.ts";
5354 import {
@@ -349,7 +350,7 @@ async function studioTell(
349350 () =>
350351 badge("Sealed security report", { tone: "danger", icon: "lock" }),
351352 )}
352 ${workSpent(ctx, repo, issue.id)}
353 ${workSpent(ctx, repo, issue.id)} ${ledgerCost(ctx, repo, issue.id)}
353354 ${issue.assigneeName !== null
354355 ? html`<span
355356 >${when(issue.assigneeIsAgent, () => icon("bot"))}
test/ledger-cost.test.ts added +561
@@ -0,0 +1,561 @@
1 /**
2 * The cost ledger (#1386): one entry per finished run with its cell's
3 * compute, hash-chained and signed, committed to `<data>/ledger.git`;
4 * verification names the first broken link; roll-ups are the sum of the
5 * entries; a sweep with nothing finished writes nothing.
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 { createApp, type App } from "../src/app.ts";
12 import { meter, newUsage, statRow } from "../src/apps/contain.ts";
13 import { setCapacity, validCapacity } from "../src/core/capacity.ts";
14 import { costDay } from "../src/actions/cost.ts";
15 import { createIssue } from "../src/core/issues.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import {
18 ledgerLine,
19 dayCost,
20 entryFor,
21 GENESIS,
22 issueCost,
23 sealEntry,
24 verifyChain,
25 type FinishedRun,
26 } from "../src/core/cost_ledger.ts";
27 import { entriesPast, ledgerDir, readLedger, sweepLedger } from "../src/core/ledger_write.ts";
28 import { recordUsage } from "../src/core/usage.ts";
29 import { claimRun, createRun, finishRun, getRun } from "../src/core/runs.ts";
30 import { getUserByName, type User } from "../src/core/users.ts";
31 import { resolveOid } from "../src/git/merge.ts";
32 import { getRepoById } from "../src/core/repos.ts";
33 import { createForgeApp } from "../src/tui/forge.ts";
34 import { issueScreen } from "../src/tui/screens/issue.ts";
35 import { pullScreen } from "../src/tui/screens/pull.ts";
36 import { local } from "../src/tui/screens/where.ts";
37 import { headlessTerminal } from "../src/tui/term/terminal.ts";
38 import { settleApp } from "./helpers/tui.ts";
39 import { forgeHttp } from "../src/http/server.ts";
40 import {
41 ledgerKey,
42 ledgerKeyFromSecret,
43 verifySignature,
44 } from "../src/kernel/ledger_key.ts";
45
46 describe("the cell's meter", () => {
47 test("counts each process's CPU growth and integrates resident memory", () => {
48 const usage = newUsage();
49 const entry = { usage, seen: new Map<number, number>(), lastAt: undefined };
50 // First look: pid 10 has used 150 ticks (1.5 s at CLK_TCK 100), 1 GiB resident.
51 meter(entry, [10], new Map([[10, { ticks: 150 }]]), 1024 * 1024, 1_000);
52 // Two seconds on: pid 10 grew 50 ticks, pid 11 appeared with 30; 2 GiB.
53 meter(
54 entry,
55 [10, 11],
56 new Map([
57 [10, { ticks: 200 }],
58 [11, { ticks: 30 }],
59 ]),
60 2 * 1024 * 1024,
61 3_000,
62 );
63 // pid 10 exited: what it used stays counted; pid 11 grew 20.
64 meter(entry, [11], new Map([[11, { ticks: 50 }]]), 0, 4_000);
65 // CPU: (150 + 50 + 30 + 20) / 100 = 2.5 s.
66 expect(usage.cpuS).toBeCloseTo(2.5, 9);
67 // Memory: 1 GiB × 1 s (first tick) + 2 GiB × 2 s + 0 = 5 GiB·s.
68 expect(usage.memGbS).toBeCloseTo(5, 9);
69 });
70
71 test("a reaped child's CPU, moved into its parent's cumulative fields, is not counted twice", () => {
72 // A /proc/<pid>/stat line: pid (comm) state ppid … utime stime cutime cstime …
73 const stat = (pid: number, ppid: number, u: number, s: number, cu: number, cs: number): string =>
74 `${pid} (bun test) S ${ppid} 1 1 0 -1 4194304 0 0 0 0 ${u} ${s} ${cu} ${cs} 20 0 1 0 100 0 0`;
75 expect(statRow(stat(20, 1, 7, 3, 500, 500))).toEqual({ ppid: 1, ticks: 10, withReaped: 1010 });
76 const entry = { usage: newUsage(), seen: new Map<number, number>(), lastAt: undefined };
77 const look = (...lines: string[]): void => {
78 const rows = new Map(lines.map((l) => [Number(l.split(" ")[0]), statRow(l)] as const));
79 meter(entry, [...rows.keys()], rows, 0, 0);
80 };
81 // The parent has used 10 ticks; its child 40.
82 look(stat(20, 1, 7, 3, 0, 0), stat(21, 20, 30, 10, 0, 0));
83 expect(entry.usage.cpuS).toBeCloseTo(0.5, 9);
84 // The child is reaped: its 40 ticks land in the parent's cutime/cstime.
85 look(stat(20, 1, 7, 3, 30, 10));
86 expect(entry.usage.cpuS).toBeCloseTo(0.5, 9);
87 });
88
89 test("a meterless cell counts nothing", () => {
90 const entry = { usage: undefined, seen: new Map<number, number>(), lastAt: undefined };
91 meter(entry, [1], new Map([[1, { ticks: 100 }]]), 1024, 0);
92 expect(entry.seen.size).toBe(0);
93 });
94 });
95
96 const run = (over: Partial<FinishedRun> = {}): FinishedRun => ({
97 id: "r1",
98 kind: "check",
99 repoId: "p1",
100 repo: "ada/hello",
101 issueId: "i1",
102 issueNumber: 7,
103 issueKind: "pull",
104 state: "ok",
105 createdAt: "2026-10-14T10:00:00.000Z",
106 startedAt: "2026-10-14T10:05:00.000Z",
107 finishedAt: "2026-10-14T10:30:00.000Z",
108 cpuS: 3600,
109 memGbS: 7200,
110 tokensIn: 0,
111 tokensOut: 0,
112 costUsd: 0,
113 ...over,
114 });
115
116 describe("an entry, by hand", () => {
117 test("times and the compute price match the arithmetic", () => {
118 const e = entryFor(run(), { vcpuHour: 0.04048, gbHour: 0.004445 }, 1, GENESIS);
119 expect(e.wall_s).toBe(1500); // 10:05 → 10:30
120 expect(e.lane_wait_s).toBe(300); // 10:00 → 10:05
121 expect(e.pull).toBe(7);
122 expect(e.issue).toBeNull();
123 // 3600 CPU-s = 1 vCPU-h × 0.04048 + 7200 GiB-s = 2 GiB-h × 0.004445 = 0.04937.
124 expect(e.usd_compute).toBe(0.04937);
125 });
126
127 test("unmeasured compute is null, not zero", () => {
128 const e = entryFor(run({ cpuS: null, memGbS: null }), { vcpuHour: 1, gbHour: 1 }, 1, GENESIS);
129 expect(e.cpu_s).toBeNull();
130 expect(e.usd_compute).toBeNull();
131 });
132
133 test("the forge's key signs, and only it verifies", () => {
134 const key = ledgerKeyFromSecret(new Uint8Array(32).fill(1));
135 const other = ledgerKeyFromSecret(new Uint8Array(32).fill(2));
136 const sig = key.sign("abc");
137 expect(verifySignature(key.publicKey, "abc", sig)).toBe(true);
138 expect(verifySignature(key.publicKey, "abd", sig)).toBe(false);
139 expect(verifySignature(other.publicKey, "abc", sig)).toBe(false);
140 expect(verifySignature("short", "abc", sig)).toBe(false);
141 });
142 });
143
144 describe("the ledger", () => {
145 let dataDir: string;
146 let app: App;
147 let fetch: (path: string, init?: RequestInit) => Promise<Response>;
148 let cookie = "";
149 let bobCookie = "";
150 let adaToken = "";
151 let bobToken = "";
152 let repoId = "";
153 let issueId = "";
154 const later = (): number => Date.now() + 120_000;
155
156 const finished = (
157 kind: "agent" | "check" | "deploy",
158 usage?: { cpuS: number; memGbS: number },
159 on: string = issueId,
160 ): string => {
161 const made = createRun(app.db, { repoId, kind, issueId: on });
162 claimRun(app.db, made.id);
163 finishRun(app.db, made.id, {
164 state: "ok",
165 summary: "done",
166 ...(usage === undefined ? {} : { usage }),
167 });
168 return made.id;
169 };
170
171 beforeAll(async () => {
172 dataDir = await mkdtemp(join(tmpdir(), "forge-ledger-"));
173 app = createApp({ dataDir, port: 0 });
174 // In-process, no listener: the same routes a served forge answers with.
175 const http = forgeHttp(app);
176 fetch = (path, init) =>
177 http.handle(new Request(`http://localhost${path}`, init));
178 const signed = await fetch(`/signup`, {
179 method: "POST",
180 body: new URLSearchParams({
181 username: "ada",
182 email: "[email protected]",
183 password: "analytical-engine",
184 }),
185 redirect: "manual",
186 });
187 cookie = (signed.headers.get("set-cookie") ?? "").split(";")[0]!;
188 // A second person: no admin, and no writer of ada's repository.
189 const bob = await fetch(`/signup`, {
190 method: "POST",
191 body: new URLSearchParams({
192 username: "bob",
193 email: "[email protected]",
194 password: "difference-engine",
195 }),
196 redirect: "manual",
197 });
198 bobCookie = (bob.headers.get("set-cookie") ?? "").split(";")[0]!;
199 adaToken = createToken(app.db, getUserByName(app.db, "ada")!.id, "ro", "ro").token;
200 bobToken = createToken(app.db, getUserByName(app.db, "bob")!.id, "ro", "ro").token;
201 const headers = { cookie, "content-type": "application/json" };
202 const repo = (await fetch(`/api/v1/repos`, {
203 method: "POST",
204 headers,
205 body: JSON.stringify({ name: "hello", visibility: "public" }),
206 }).then((r) => r.json())) as { id: string };
207 repoId = repo.id;
208 const issue = (await fetch(`/api/v1/repos/ada/hello/issues`, {
209 method: "POST",
210 headers,
211 body: JSON.stringify({ title: "make it cheaper" }),
212 }).then((r) => r.json())) as { id: string; number: number };
213 issueId = app.db
214 .query<{ id: string }, [string, number]>(
215 "SELECT id FROM issue WHERE repo_id = ?1 AND number = ?2",
216 )
217 .get(repoId, issue.number)!.id;
218 });
219
220 afterAll(async () => {
221 app.close();
222 await rm(dataDir, { recursive: true, force: true });
223 });
224
225 const board = (who: string): Promise<string> =>
226 fetch(`/board`, { headers: { cookie: who } }).then((r) => r.text());
227 /** An MCP tool's answer: its JSON value, or its error text. */
228 const tool = async (token: string, name: string, args: unknown) => {
229 const res = await fetch(`/mcp`, {
230 method: "POST",
231 headers: {
232 "content-type": "application/json",
233 accept: "application/json, text/event-stream",
234 authorization: `Bearer ${token}`,
235 },
236 body: JSON.stringify({
237 jsonrpc: "2.0",
238 id: 1,
239 method: "tools/call",
240 params: { name, arguments: args },
241 }),
242 });
243 const body = (await res.json()) as any;
244 const text: string = body.result.content[0].text;
245 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
246 };
247
248 test("the board has no day line before anything was entered", async () => {
249 const page = await board(cookie);
250 expect(page).toContain(`id="forge"`); // the admin's forge line is there
251 expect(page).not.toContain(`id="day-cost"`);
252 });
253
254 test("a sweep with no finished runs writes nothing", async () => {
255 expect(await sweepLedger(app, later())).toBe(0);
256 const dir = ledgerDir(dataDir);
257 expect(await resolveOid(dir, "refs/heads/main")).toBeUndefined();
258 expect(dayCost(app.db, new Date().toISOString().slice(0, 10)).runs).toBe(0);
259 });
260
261 test("a run that never started is never entered", async () => {
262 createRun(app.db, { repoId, kind: "check", issueId });
263 expect(await sweepLedger(app, later())).toBe(0);
264 });
265
266 test("a run that just finished waits to settle", async () => {
267 finished("deploy");
268 expect(await sweepLedger(app, Date.now())).toBe(0);
269 });
270
271 test("every finished run gets one entry, with its cell's numbers", async () => {
272 const check = finished("check", { cpuS: 90, memGbS: 45 });
273 expect(getRun(app.db, check)!.cpuS).toBe(90);
274 const agent = finished("agent");
275 const smith = getUserByName(app.db, "ada")!.id;
276 recordUsage(app.db, {
277 runId: agent,
278 repoId,
279 issueId,
280 agentId: smith,
281 subscriptionId: null,
282 tokensIn: 1200,
283 tokensOut: 300,
284 costUsd: 0.42,
285 wallMs: 1000,
286 outcome: "ok",
287 at: new Date().toISOString(),
288 });
289 expect(await sweepLedger(app, later())).toBe(3); // the deploy, the check, the agent
290 expect(await sweepLedger(app, later())).toBe(0); // entered once
291
292 const { publicKey, lines } = await readLedger(ledgerDir(dataDir));
293 expect(publicKey).toBe(ledgerKey(dataDir).publicKey);
294 expect(lines).toHaveLength(3);
295 const entries = lines.map((l) => JSON.parse(l) as Record<string, unknown>);
296 const byRun = new Map(entries.map((e) => [e["run"], e]));
297 expect(byRun.get(check)!["cpu_s"]).toBe(90);
298 expect(byRun.get(check)!["mem_gb_s"]).toBe(45);
299 // 90/3600 × 0.04048 + 45/3600 × 0.004445 = 0.001012 + 0.0000555625 → 0.001068 (6 places)
300 expect(byRun.get(check)!["usd_compute"]).toBe(0.001068);
301 expect(byRun.get(agent)!["tokens_in"]).toBe(1200);
302 expect(byRun.get(agent)!["usd_tokens"]).toBe(0.42);
303 expect(byRun.get(agent)!["cpu_s"]).toBeNull();
304 expect(verifyChain(lines, publicKey)).toEqual({
305 ok: true,
306 count: 3,
307 tip: entries[2]!["hash"] as string,
308 });
309 });
310
311 test("the forge's rate is the setting, and written into the entry", async () => {
312 setCapacity(app.db, "cost.vcpu_hour", "1", getUserByName(app.db, "ada")!.id);
313 const id = finished("check", { cpuS: 1800, memGbS: 0 });
314 expect(await sweepLedger(app, later())).toBe(1);
315 const { lines } = await readLedger(ledgerDir(dataDir));
316 const last = JSON.parse(lines.at(-1)!) as Record<string, unknown>;
317 expect(last["run"]).toBe(id);
318 expect(last["rate_vcpu_h"]).toBe(1);
319 expect(last["usd_compute"]).toBe(0.5); // half a vCPU-hour at US$1
320 setCapacity(app.db, "cost.vcpu_hour", null, getUserByName(app.db, "ada")!.id);
321 });
322
323 test("roll-ups are the sums of the entries", async () => {
324 const { lines } = await readLedger(ledgerDir(dataDir));
325 const entries = lines.map((l) => JSON.parse(l) as Record<string, number | string | null>);
326 const sum = (f: string, keep = (_: Record<string, unknown>) => true): number =>
327 entries.filter(keep).reduce((s, e) => s + Number(e[f] ?? 0), 0);
328 const r = issueCost(app.db, issueId);
329 expect(r.runs).toBe(entries.length);
330 expect(r.usdTokens).toBeCloseTo(sum("usd_tokens"), 9);
331 expect(r.usdCompute).toBeCloseTo(sum("usd_compute"), 9);
332 expect(r.measured).toBe(entries.filter((e) => e["usd_compute"] !== null).length);
333 expect(r.waitS).toBeCloseTo(sum("lane_wait_s"), 9);
334 expect(r.laneS).toBeCloseTo(
335 sum("wall_s", (e) => e["kind"] === "check" || e["kind"] === "deploy"),
336 9,
337 );
338 const day = dayCost(app.db, new Date().toISOString().slice(0, 10));
339 expect(day.runs).toBe(entries.length);
340 expect(ledgerLine(r)).toStartWith("$0.42 tokens · $0.50 compute");
341 });
342
343 test("the issue's page shows the cost to its owner, and not to a stranger", async () => {
344 const page = await fetch(`/ada/hello/issues/1`, {
345 headers: { cookie },
346 }).then((r) => r.text());
347 expect(page).toContain(`id="ledger-cost"`);
348 expect(page).toContain("cost: $0.42 tokens");
349 const anon = await fetch(`/ada/hello/issues/1`).then((r) => r.text());
350 expect(anon).not.toContain(`id="ledger-cost"`);
351 });
352
353 test("an index lost is rebuilt from git, not re-entered", async () => {
354 const before = (await readLedger(ledgerDir(dataDir))).lines.length;
355 app.db.exec("DELETE FROM cost_entry");
356 expect(await sweepLedger(app, later())).toBe(0);
357 expect(issueCost(app.db, issueId).runs).toBe(before);
358 expect((await readLedger(ledgerDir(dataDir))).lines.length).toBe(before);
359 });
360
361 test("a line that does not parse stops the index before it, and does not throw", async () => {
362 const { lines } = await readLedger(ledgerDir(dataDir));
363 const said = console.error;
364 console.error = () => {};
365 try {
366 const got = entriesPast([lines[0]!, lines[1]!, "{not json", lines[2]!], 1);
367 expect(got.map((e) => e.seq)).toEqual([2]);
368 } finally {
369 console.error = said;
370 }
371 });
372
373 test("a tampered entry breaks verification at its own link", async () => {
374 const { publicKey, lines } = await readLedger(ledgerDir(dataDir));
375 const forged = [...lines];
376 const second = JSON.parse(forged[1]!) as Record<string, unknown>;
377 second["wall_s"] = Number(second["wall_s"]) - 60; // a lane-minute taken off the bill
378 forged[1] = JSON.stringify(second);
379 expect(verifyChain(forged, publicKey)).toMatchObject({
380 ok: false,
381 seq: 2,
382 reason: "hash does not match the entry",
383 });
384 // Re-hashing the forgery does not help: the next link names the old hash,
385 // and the forger has no key to re-sign with.
386 const key = ledgerKeyFromSecret(new Uint8Array(32).fill(9));
387 const resealed = sealEntry(second as never, key.sign);
388 forged[1] = JSON.stringify(resealed);
389 expect(verifyChain(forged, publicKey)).toMatchObject({
390 ok: false,
391 seq: 2,
392 reason: "signature does not verify",
393 });
394 // Dropping an entry breaks the link after the gap.
395 expect(verifyChain([lines[0]!, lines[2]!], publicKey)).toMatchObject({
396 ok: false,
397 seq: 2,
398 });
399 });
400
401 test("the verify script walks the repository and says ok", async () => {
402 const proc = Bun.spawn(
403 ["bun", "scripts/ledger-verify.ts", ledgerDir(dataDir)],
404 { stdout: "pipe", stderr: "pipe", env: { PATH: process.env["PATH"] ?? "" } },
405 );
406 const out = await new Response(proc.stdout).text();
407 const said = await new Response(proc.stderr).text();
408 expect({ code: await proc.exited, said }).toEqual({ code: 0, said: "" });
409 expect(out).toStartWith("ok: 4 entries");
410 });
411
412 test("the board's forge line shows the day to an admin, and not to anyone else", async () => {
413 const day = ledgerLine(dayCost(app.db, new Date().toISOString().slice(0, 10)));
414 expect(day).toStartWith("$0.42 tokens");
415 const page = await board(cookie);
416 expect(page).toContain(`<span class="board-forge-cost" id="day-cost">today: ${day}</span>`);
417 const bobs = await board(bobCookie);
418 expect(bobs).not.toContain(`id="day-cost"`);
419 expect(bobs).not.toContain("today: $");
420 });
421
422 test("a pull's page shows its cost and how long it has been open, then took", async () => {
423 const ada = getUserByName(app.db, "ada")!.id;
424 const made = createIssue(app.db, { repoId, authorId: ada, title: "cheaper cells", kind: "pull" });
425 if (!made.ok) throw new Error(made.error);
426 const pull = made.value;
427 // Opened three hours ago, by the clock the lead time reads.
428 const opened = new Date(Date.now() - 3 * 3_600_000).toISOString();
429 app.db.query("UPDATE issue SET created_at = ?1 WHERE id = ?2").run(opened, pull.id);
430 app.db
431 .query(
432 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at)
433 VALUES (?1, 'main', 'cheaper', '', '', NULL)`,
434 )
435 .run(pull.id);
436 finished("check", { cpuS: 3600, memGbS: 0 }, pull.id);
437 expect(await sweepLedger(app, later())).toBe(1);
438 const path = `/ada/hello/pulls/${pull.number}`;
439
440 const open = await fetch(path, { headers: { cookie } }).then((r) => r.text());
441 // One vCPU-hour at the default US$0.04048 → $0.04; no tokens; 3 h open.
442 expect(open).toMatch(
443 /id="ledger-cost">cost: \$0\.00 tokens · \$0\.04 compute · \d+ lane-min · 0 min waiting · open 3\.0 h<\/span>/,
444 );
445
446 // Merged ninety minutes after it was opened: the lead time is fixed.
447 const merged = new Date(Date.parse(opened) + 90 * 60_000).toISOString();
448 app.db.query("UPDATE pull SET merged_at = ?1 WHERE issue_id = ?2").run(merged, pull.id);
449 app.db.query("UPDATE issue SET state = 'closed', closed_at = ?2 WHERE id = ?1").run(pull.id, merged);
450 const done = await fetch(path, { headers: { cookie } }).then((r) => r.text());
451 expect(done).toContain("· open→merged 90 min</span>");
452 expect(done).not.toContain("· open 3.0 h");
453
454 const stranger = await fetch(path, { headers: { cookie: bobCookie } }).then((r) => r.text());
455 expect(stranger).not.toContain(`id="ledger-cost"`);
456 });
457
458 test("the terminal's issue and pull screens show the page's cost line to a writer, and not to a stranger", async () => {
459 const repo = getRepoById(app.db, repoId)!;
460 const pull = app.db
461 .query<{ number: number }, [string]>(
462 "SELECT number FROM issue WHERE repo_id = ?1 AND kind = 'pull' ORDER BY number DESC",
463 )
464 .get(repoId)!.number;
465 const screenText = async (
466 user: User | undefined,
467 open: typeof issueScreen | typeof pullScreen,
468 number: number,
469 ): Promise<string> => {
470 const { app: tui, session } = createForgeApp(
471 app,
472 { sshUsername: user?.username ?? "guest", remoteAddress: "127.0.0.1", user },
473 { terminal: headlessTerminal(200, 44), exitHooks: false },
474 );
475 tui.start();
476 try {
477 tui.ctx.push(open(session, tui.ctx, local(session, repo), number));
478 await settleApp(tui);
479 return tui.screen.toText();
480 } finally {
481 tui.stop();
482 }
483 };
484 const ada = getUserByName(app.db, "ada")!;
485 const bob = getUserByName(app.db, "bob")!;
486 const issueLine = `cost: ${ledgerLine(issueCost(app.db, issueId))}`;
487 expect(await screenText(ada, issueScreen, 1)).toContain(issueLine);
488 // The pull's line carries its lead time after the cost, as the page does.
489 expect(await screenText(ada, pullScreen, pull)).toMatch(
490 /cost: \$0\.00 tokens · \$0\.04 compute · \d+ lane-min · 0 min waiting · open→merged 90 min/,
491 );
492 for (const who of [bob, undefined]) {
493 // The screens are there (the repository is public); only the line is not.
494 const issueSeen = await screenText(who, issueScreen, 1);
495 expect(issueSeen).toContain("make it cheaper");
496 expect(issueSeen).not.toContain("cost:");
497 const pullSeen = await screenText(who, pullScreen, pull);
498 expect(pullSeen).toContain("cheaper cells");
499 expect(pullSeen).not.toContain("cost:");
500 }
501 });
502
503 test("the JSON API and MCP read the same roll-up as the page, behind the same gates", async () => {
504 const want = issueCost(app.db, issueId);
505 const api = await fetch(`/api/v1/repos/ada/hello/issues/1/cost`, { headers: { cookie } });
506 expect(api.status).toBe(200);
507 const body = (await api.json()) as Record<string, unknown>;
508 expect(body).toMatchObject({ number: 1, kind: "issue", runs: want.runs, line: ledgerLine(want) });
509 expect(body["usdTokens"]).toBeCloseTo(want.usdTokens, 9);
510 // A reader who cannot write the repository is refused, as on the page.
511 expect((await fetch(`/api/v1/repos/ada/hello/issues/1/cost`, { headers: { cookie: bobCookie } })).status).toBe(403);
512 expect((await fetch(`/api/v1/repos/ada/hello/issues/999/cost`, { headers: { cookie } })).status).toBe(404);
513
514 const viaMcp = await tool(adaToken, "cost", { repo: "ada/hello", issue: 1 });
515 expect(viaMcp.value).toEqual(body);
516 expect((await tool(bobToken, "cost", { repo: "ada/hello", issue: 1 })).error).toContain("write this app");
517
518 // The day: an admin's, and nobody else's.
519 const today = new Date().toISOString().slice(0, 10);
520 const dayWant = dayCost(app.db, today);
521 const dayApi = await fetch(`/api/v1/admin/cost`, { headers: { cookie } });
522 expect(dayApi.status).toBe(200);
523 const dayBody = (await dayApi.json()) as Record<string, unknown>;
524 expect(dayBody).toMatchObject({ day: today, runs: dayWant.runs, line: ledgerLine(dayWant) });
525 expect((await fetch(`/api/v1/admin/cost`, { headers: { cookie: bobCookie } })).status).toBe(404);
526 expect((await fetch(`/api/v1/admin/cost?day=2026-02-30`, { headers: { cookie } })).status).toBe(422);
527 expect((await fetch(`/api/v1/admin/cost?day=1999-01-01`, { headers: { cookie } })).json()).resolves.toMatchObject({ runs: 0, line: "" });
528 expect((await tool(adaToken, "cost", {})).value).toEqual(dayBody);
529 expect((await tool(bobToken, "cost", {})).error).toContain("only an admin");
530 });
531
532 test("a rate is set through the capacity API in the forms it takes, and refused in others", async () => {
533 const put = (value: string) =>
534 fetch(`/api/v1/admin/capacity/cost.vcpu_hour`, {
535 method: "PUT",
536 headers: { cookie, "content-type": "application/json", origin: "http://localhost" },
537 body: JSON.stringify({ value }),
538 });
539 expect((await put("0.04048")).status).toBe(200);
540 for (const bad of ["101", "1e3", "-1", ".5", "1.1234567"])
541 expect({ bad, status: (await put(bad)).status }).toEqual({ bad, status: 422 });
542 setCapacity(app.db, "cost.vcpu_hour", null, getUserByName(app.db, "ada")!.id);
543 });
544 });
545
546 describe("a compute rate, at the boundary", () => {
547 test("dollars with up to six decimals, from 0 to 100", () => {
548 for (const good of ["0", "0.04048", "0.004445", "100", "99.999999", "1.123456"])
549 expect({ good, ok: validCapacity("cost.vcpu_hour", good) }).toEqual({ good, ok: true });
550 for (const bad of ["101", "100.000001", "1e3", "-1", ".5", "1.", "1.1234567", "", " 1", "0x10", "Infinity", "NaN"])
551 expect({ bad, ok: validCapacity("cost.gb_hour", bad) }).toEqual({ bad, ok: false });
552 });
553
554 test("a day is a calendar date that exists, today when absent", () => {
555 const now = new Date("2026-10-15T23:59:59Z");
556 expect(costDay(null, now)).toBe("2026-10-15");
557 expect(costDay("2024-02-29")).toBe("2024-02-29");
558 for (const bad of ["2026-02-30", "2026-13-01", "26-10-15", "2026-10-15T00:00", "today"])
559 expect(costDay(bad)).toBeUndefined();
560 });
561 });
test/mcp.test.ts +1
@@ -191,6 +191,7 @@ describe("the forge over MCP", () => {
191191 "returns",
192192 "spend",
193193 "usage",
194 "cost",
194195 "link",
195196 "unlink",
196197 "attach_look",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs