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

Cost ledger: an issue sums its pulls, and the board shows the median ask→live #1392

Closed opened this
Closed without merging

torque/forge:torque/1389-cost-ledger-an-issue-sums-its-pulls-and → main 7 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
30 files changed +2344 −15
README.md +34
@@ -400,6 +400,40 @@ The terminal has no backups view, so it has no readout.
400400 grew up in switched off: what a host owes it, the moves in order, and what is
401401 given up.
402402
403 ### The cost ledger
404
405 Every run that did work (agent, check, deploy) gets one entry when it ends:
406 tokens and their dollars, the CPU-seconds and GiB-seconds its cell's watch
407 measured (`null` where no cell held it), the seconds it waited for a lane
408 and the seconds it ran, and the compute priced at the forge's rates
409 (`/settings/capacity`: US$ per vCPU-hour and per GB-hour, defaulting to
410 Fargate's list price, written into each entry). Entries are hash-chained
411 (`prev`, `hash` = SHA-256 of the canonical entry) and signed with an
412 Ed25519 key derived from the data directory's `secret.key`, committed a
413 batch at a time to `<data>/ledger.git` beside `forge.pub`. The database is
414 its index. Anyone holding the repository can check it:
415
416 ```sh
417 bun scripts/ledger-verify.ts data/ledger.git # ok: N entries, tip …
418 bun scripts/ledger-verify.ts ledger.git --key <pub> # trust a key you were given, not forge.pub
419 ```
420
421 A pull and an issue show `cost: $… tokens · $… compute · N lane-min · … waiting`
422 to their owner; the board's forge line shows the day's totals to an admin.
423 An issue's line adds the entries of every pull whose description closes it
424 (`Closes #N`, merged or not: an abandoned try still cost), and, once one of
425 them serves, `ask→live`: from the issue opening to the first production
426 deploy queued after that pull merged starting to serve. The board puts the
427 day's median ask→live beside the dollars, over the issues that went live
428 that UTC day (`src/core/lead_time.ts` states what counts).
429
430 The same line reaches every door, from `src/actions/work_cost.ts`: the
431 issue and pull JSON carry it as `cost` (`rollup`, `pulls`, `askLiveS`,
432 `openS`, `line`), the MCP `cost` tool takes `{ repo, issue }`, the
433 terminal's issue and pull screens print it under the title, and its
434 dashboard prints the day's line for an admin. A reader who cannot write the
435 repository gets no `cost` key, a refusal from the tool and nothing on screen.
436
403437 ## Cloud accounts
404438
405439 **Settings → Cloud accounts** (admins) holds provider keys — Cloudflare,
docs/MCP.md +1
@@ -54,6 +54,7 @@ for a tunnel and a forge that sleeps.
5454 | `limb` | `{ app, issue, action, reason?, pillar?, operation?, dryRun? }`: defer, resume or close a whole limb as not doing, or undo an operation; plans unless `dryRun` is false, and applying takes an admin token | yes |
5555 | `watch` | `{ app, issue, watch? }`: watch a milestone, or stop with `watch: false`: one item in your feed that follows it, and one push to your phone when it lands | yes |
5656 | `usage` | `{ repo, days? }`: what the crew's runs spent — tokens, cost, wall time — by subscription, agent, issue, and each account's 5-hour and weekly standing; a writer's | |
57 | `cost` | `{ repo, issue }`: what the work on one issue or pull cost by the cost ledger — tokens and compute in dollars, lane and waiting seconds; an issue with every pull that closes it and its ask→live, a pull with how long it was open; `line` is the words the page shows; a writer's | |
5758 | `link` | `{ app, issue, blockedBy }`: the issue waits for another; loops and cross-repository are refused | yes |
5859 | `unlink` | `{ app, issue, blockedBy }`: the issue stops waiting for it | yes |
5960 | `hold` | `{ app, pull, why?, release?, dryRun? }`: hold a pull so no rule reviews or lands it, or let it go; a person who can write, never an agent; plans unless `dryRun: false` | yes |
scripts/gate.ts +2
@@ -239,6 +239,8 @@ export const GATE: readonly string[] = [
239239 "test/counts.test.ts",
240240 "test/crew-loop.test.ts",
241241 "test/crew-totals.test.ts",
242 "test/ledger-cost.test.ts",
243 "test/ledger-rollup.test.ts",
242244 "test/ssh-site.test.ts",
243245 "test/web-code.test.ts",
244246 "test/web-origins.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/work_cost.ts added +110
@@ -0,0 +1,110 @@
1 /**
2 * What the work on one issue or pull cost by the cost ledger
3 * (`core/cost_ledger.ts`), as every door shows it: the web issue and change
4 * pages, the issue and pull JSON, the MCP `cost` tool and the terminal's
5 * issue and pull screens all read it here, so they never disagree.
6 *
7 * An issue sums its own entries and those of every pull that closes it
8 * (`pullsClosing`), and once one of them serves in production, how long it
9 * took from the ask to live (`core/lead_time.ts`). A pull sums its own, and
10 * how long it has been open (or took, open to merged): lead time is a cost
11 * beside the dollars.
12 *
13 * Cost is the owner's own fact (`canSeeOwnerFacts`, the predicate the run
14 * pages use), so a reader who cannot write the repository is refused, and
15 * the forge's day line is the admin's.
16 */
17
18 import type { Database } from "bun:sqlite";
19 import {
20 costLine,
21 costOf,
22 dayCost,
23 duration,
24 type CostRollup,
25 } from "../core/cost_ledger.ts";
26 import type { Issue } from "../core/issues.ts";
27 import { dayAskLive, issueAskLive } from "../core/lead_time.ts";
28 import { getPull, pullsClosing } from "../core/pulls.ts";
29 import { canSeeOwnerFacts, type Repo } from "../core/repos.ts";
30 import type { User } from "../core/users.ts";
31 import { err, ok, type Result } from "../kernel/result.ts";
32
33 export interface WorkCost {
34 readonly rollup: CostRollup;
35 /** An issue: the pulls that close it. Null for a pull. */
36 readonly pulls: number | null;
37 /** An issue: seconds from the ask to its first change serving; null until one does. */
38 readonly askLiveS: number | null;
39 /** A pull: seconds open so far, or open to merged; null for an issue. */
40 readonly openS: number | null;
41 readonly merged: boolean;
42 /** The line every surface prints after "cost: " — empty when there is nothing to say. */
43 readonly line: string;
44 }
45
46 /** The cost of the work on `issue` (an issue or a pull), for `user`. */
47 export function readWorkCost(
48 db: Database,
49 user: User | undefined,
50 repo: Repo,
51 issue: Issue,
52 now: number = Date.now(),
53 ): Result<WorkCost, "forbidden"> {
54 if (!canSeeOwnerFacts(db, repo, user)) return err("forbidden");
55 return ok(
56 issue.kind === "pull" ? pullCost(db, repo, issue, now) : issueCost(db, repo, issue),
57 );
58 }
59
60 function issueCost(db: Database, repo: Repo, issue: Issue): WorkCost {
61 const pulls = pullsClosing(db, repo.id, issue.number);
62 const rollup = costOf(db, [issue.id, ...pulls.map((p) => p.id)]);
63 const merges = pulls.flatMap((p) => (p.mergedAt === null ? [] : [p.mergedAt]));
64 const live = issueAskLive(db, issue, merges, repo.id);
65 const askLiveS = live === null ? null : Math.max(0, live);
66 const spent = costLine(rollup);
67 const line =
68 spent === "" && askLiveS === null
69 ? ""
70 : [
71 ...(spent === "" ? [] : [spent]),
72 ...(pulls.length === 0
73 ? []
74 : [`with ${pulls.length} ${pulls.length === 1 ? "pull" : "pulls"}`]),
75 ...(askLiveS === null ? [] : [`ask→live ${duration(askLiveS)}`]),
76 ].join(" · ");
77 return { rollup, pulls: pulls.length, askLiveS, openS: null, merged: false, line };
78 }
79
80 function pullCost(db: Database, repo: Repo, issue: Issue, now: number): WorkCost {
81 const rollup = costOf(db, [issue.id]);
82 const mergedAt = getPull(db, repo.id, issue.number)?.mergedAt ?? null;
83 const openS = Math.max(
84 0,
85 ((mergedAt === null ? now : Date.parse(mergedAt)) - Date.parse(issue.createdAt)) / 1000,
86 );
87 const spent = costLine(rollup);
88 const line =
89 spent === ""
90 ? ""
91 : `${spent} · ${mergedAt === null ? "open" : "open→merged"} ${duration(openS)}`;
92 return { rollup, pulls: null, askLiveS: null, openS, merged: mergedAt !== null, line };
93 }
94
95 /**
96 * The forge's day (`YYYY-MM-DD`, UTC) by the ledger: what ended that day,
97 * and the median ask→live over the issues that went live in it. Empty when
98 * neither has anything to say.
99 */
100 export function dayWorkLine(db: Database, day: string): string {
101 const lead = dayAskLive(db, day);
102 return [
103 costLine(dayCost(db, day)),
104 lead.medianS === null
105 ? ""
106 : `median ask→live ${duration(Math.max(0, lead.medianS))} (${lead.n} live)`,
107 ]
108 .filter((s) => s !== "")
109 .join(" · ");
110 }
src/apps/contain.ts +59 −1
@@ -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);
@@ -732,6 +758,7 @@ function tick(): void {
732758 kib += residentKiB(pid);
733759 ticks += rows.get(pid)?.ticks ?? 0;
734760 }
761 meter(entry, tree, rows, kib, now);
735762 if (kib > limits.memoryMiB * 1024) {
736763 entry.breach(
737764 `used ${mib(kib * 1024)} of memory, over its ${limits.memoryMiB} MiB limit`,
@@ -765,3 +792,34 @@ function tick(): void {
765792 }
766793 }
767794 }
795
796 /**
797 * Add one tick's use to the cell's accumulator: each process's CPU ticks
798 * since it was last seen (a new process counts from zero, so what it used
799 * before the first look is counted too), and resident memory held for the
800 * time since the last tick.
801 */
802 export function meter(
803 entry: Pick<Watched, "usage" | "seen" | "lastAt">,
804 tree: readonly number[],
805 rows: Map<number, { ticks: number }>,
806 kib: number,
807 now: number,
808 ): void {
809 const usage = entry.usage;
810 if (usage === undefined) return;
811 let grew = 0;
812 const next = new Map<number, number>();
813 for (const pid of tree) {
814 const ticks = rows.get(pid)?.ticks ?? 0;
815 grew += Math.max(0, ticks - (entry.seen.get(pid) ?? 0));
816 next.set(pid, ticks);
817 }
818 entry.seen.clear();
819 for (const [pid, ticks] of next) entry.seen.set(pid, ticks);
820 usage.cpuS += grew / CLK_TCK;
821 const seconds =
822 entry.lastAt === undefined ? WATCH.tickMs / 1000 : (now - entry.lastAt) / 1000;
823 usage.memGbS += (kib / (1024 * 1024)) * seconds;
824 entry.lastAt = now;
825 }
src/checks/service.ts +17 −1
@@ -60,9 +60,11 @@ import {
6060 } from "../core/capacity.ts";
6161 import {
6262 cellsAvailable,
63 newUsage,
6364 resolveLimits,
6465 STEP_HOSTS,
6566 type CellSpec,
67 type CellUsage,
6668 } from "../apps/contain.ts";
6769 import { summariseCheckFailure } from "./summary.ts";
6870 import type { CheckDetail } from "../core/runs.ts";
@@ -370,7 +372,14 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
370372 overran = true;
371373 budget.abort();
372374 }, limit);
373 const outcome = await check(claimed, repo, write, budget.signal).finally(
375 const meter = { usage: newUsage(), measured: false };
376 const outcome = await check(
377 claimed,
378 repo,
379 write,
380 budget.signal,
381 meter,
382 ).finally(
374383 () => {
375384 clearTimeout(clock);
376385 signal.removeEventListener("abort", forward);
@@ -417,6 +426,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
417426 ...(outcome.ok || outcome.detail === undefined
418427 ? {}
419428 : { checkDetail: outcome.detail }),
429 ...(meter.measured ? { usage: meter.usage } : {}),
420430 });
421431 write(outcome.ok ? `passed in ${seconds}s` : `failed: ${outcome.error}`);
422432 if (done) announceRun(app, done);
@@ -430,6 +440,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
430440 repo: Repo,
431441 write: (line: string) => void,
432442 signal: AbortSignal,
443 meter: { usage: CellUsage; measured: boolean },
433444 ): Promise<
434445 | { ok: true }
435446 | { ok: false; error: string; detail?: CheckDetail | undefined }
@@ -451,6 +462,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
451462 tier: pull === undefined ? "run" : "fast",
452463 write,
453464 signal,
465 meter,
454466 });
455467 return outcome;
456468 }
@@ -467,6 +479,8 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
467479 readonly tier: "run" | "fast" | "full";
468480 readonly write: (line: string) => void;
469481 readonly signal: AbortSignal;
482 /** Where the cell's watch adds what the check used; marked measured once a cell holds it. */
483 readonly meter?: { usage: CellUsage; measured: boolean } | undefined;
470484 }
471485
472486 async function runTier(
@@ -588,8 +602,10 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
588602 onUndeclared: (host, port) =>
589603 noteReached(app.config.dataDir, repo.id, host, port),
590604 egressMode: egressSetting(app.db),
605 usage: x.meter?.usage,
591606 }
592607 : undefined;
608 if (cell !== undefined && x.meter !== undefined) x.meter.measured = true;
593609 try {
594610 const env = childEnv({
595611 // 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 +467
@@ -0,0 +1,467 @@
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 {
417 return costOf(db, [issueId]);
418 }
419
420 /**
421 * What the work on several issues and pulls cost together, summed over the
422 * entries of each — an issue's roll-up is its own id and its pulls' ids
423 * (`pullsClosing`). An entry names one issue or pull, so none is counted
424 * twice; a repeated id is read once.
425 */
426 export function costOf(db: Database, issueIds: readonly string[]): CostRollup {
427 const ids = [...new Set(issueIds)].slice(0, 500);
428 if (ids.length === 0) return toRollup(null);
429 return toRollup(
430 db
431 .query<RollupRow, string[]>(
432 `${ROLLUP} WHERE issue_id IN (${ids.map((_, n) => `?${n + 1}`).join(",")})`,
433 )
434 .get(...ids),
435 );
436 }
437
438 /** What the forge's work cost on one UTC day (`YYYY-MM-DD`), by when it ended. */
439 export function dayCost(db: Database, day: string): CostRollup {
440 return toRollup(
441 db
442 .query<RollupRow, [string, string]>(
443 `${ROLLUP} WHERE ended_at >= ?1 AND ended_at < ?2`,
444 )
445 .get(`${day}T00:00:00`, nextDay(day)),
446 );
447 }
448
449 const nextDay = (day: string): string =>
450 new Date(Date.parse(`${day}T00:00:00Z`) + 86_400_000).toISOString().slice(0, 10);
451
452 /** "$0.42 tokens · $0.01 compute · 31 lane-min · 2.1 h waiting" — empty when nothing was entered. */
453 export function costLine(r: CostRollup): string {
454 if (r.runs === 0) return "";
455 const parts = [`$${r.usdTokens.toFixed(2)} tokens`];
456 if (r.measured > 0) parts.push(`$${r.usdCompute.toFixed(2)} compute`);
457 parts.push(`${Math.round(r.laneS / 60)} lane-min`);
458 parts.push(`${duration(r.waitS)} waiting`);
459 if (r.agentS > 0) parts.push(`${duration(r.agentS)} agent`);
460 return parts.join(" · ");
461 }
462
463 /** Seconds in the unit a person reads: minutes under two hours, hours after. */
464 export function duration(s: number): string {
465 if (s < 120 * 60) return `${Math.round(s / 60)} min`;
466 return `${(s / 3600).toFixed(1)} h`;
467 }
src/core/lead_time.ts added +180
@@ -0,0 +1,180 @@
1 /**
2 * Ask→live (#1389): how long from an issue opening to its change serving in
3 * production — lead time, a cost beside the dollars of the cost ledger
4 * (`core/cost_ledger.ts`).
5 *
6 * What counts, stated once:
7 * - The ask is the issue's `created_at`.
8 * - A pull answers an issue when its description closes it
9 * (`closesFromBody`: `Closes #12`, `Fixes #3`), the forge's one reading.
10 * - A merged pull is live at the `serving_at` of the first production
11 * deploy of its repository *queued at or after* its merge — the push
12 * that merge made, or a later one, carries it. Rollbacks are not
13 * followed: a deploy queued after the merge is taken to contain it.
14 * - An issue is live when the first of its pulls is. An issue whose
15 * repository never deploys to production never goes live, and is not
16 * in any median.
17 * - An issue opened after its change was already live (filed to record
18 * work done) waited for nothing, and is left out of the day's median.
19 * - The day's median is over the issues that went live that UTC day, a
20 * pull counted only when it merged within `WINDOW_DAYS` before the day
21 * ends (so the read stays bounded).
22 *
23 * Pure data: no authz, no events. Seconds throughout.
24 */
25
26 import type { Database } from "bun:sqlite";
27 import { closesFromBody } from "./pulls.ts";
28
29 /** How far back a merge is looked for when a day's live changes are counted. */
30 export const WINDOW_DAYS = 30;
31
32 /**
33 * The median of a set: the middle value, or the mean of the two middle
34 * values of an even set; null for the empty set.
35 */
36 export function median(xs: readonly number[]): number | null {
37 if (xs.length === 0) return null;
38 const sorted = [...xs].sort((a, b) => a - b);
39 const mid = Math.floor(sorted.length / 2);
40 return sorted.length % 2 === 0
41 ? (sorted[mid - 1]! + sorted[mid]!) / 2
42 : sorted[mid]!;
43 }
44
45 /** A production deploy that served: when it was queued, when it served. */
46 export interface Served {
47 readonly createdAt: string;
48 readonly servingAt: string;
49 }
50
51 /**
52 * When a change merged at `mergedAt` went live: the earliest `servingAt`
53 * of the deploys queued at or after the merge; null when none has served.
54 */
55 export function liveAt(
56 mergedAt: string,
57 deploys: readonly Served[],
58 ): string | null {
59 const merged = Date.parse(mergedAt);
60 let best: number | null = null;
61 for (const d of deploys) {
62 if (Date.parse(d.createdAt) < merged) continue;
63 const at = Date.parse(d.servingAt);
64 if (best === null || at < best) best = at;
65 }
66 return best === null ? null : new Date(best).toISOString();
67 }
68
69 const servedSince = (
70 db: Database,
71 repoId: string,
72 since: string,
73 ): Served[] =>
74 db
75 .query<{ created_at: string; serving_at: string }, [string, string]>(
76 `SELECT created_at, serving_at FROM run
77 WHERE repo_id = ?1 AND kind = 'deploy' AND env = 'production'
78 AND serving_at IS NOT NULL AND created_at >= ?2`,
79 )
80 .all(repoId, since)
81 .map((r) => ({ createdAt: r.created_at, servingAt: r.serving_at }));
82
83 /**
84 * One issue's ask→live in seconds: from its opening to the first of its
85 * merged pulls serving. Null while nothing that closes it is live.
86 */
87 export function issueAskLive(
88 db: Database,
89 issue: { readonly createdAt: string },
90 merges: readonly string[],
91 repoId: string,
92 ): number | null {
93 if (merges.length === 0) return null;
94 const first = merges.reduce((a, b) => (a < b ? a : b));
95 const deploys = servedSince(db, repoId, first);
96 let best: number | null = null;
97 for (const m of merges) {
98 const at = liveAt(m, deploys);
99 if (at !== null && (best === null || Date.parse(at) < best))
100 best = Date.parse(at);
101 }
102 return best === null ? null : (best - Date.parse(issue.createdAt)) / 1000;
103 }
104
105 /** The day's ask→live: the median seconds, and how many issues it is over. */
106 export interface DayAskLive {
107 readonly medianS: number | null;
108 readonly n: number;
109 }
110
111 const dayStart = (day: string): number => Date.parse(`${day}T00:00:00Z`);
112
113 /**
114 * The median ask→live over the issues, forge-wide, whose change went live
115 * on one UTC day (`YYYY-MM-DD`). Three reads, whatever merged: the pulls
116 * merged in the window, the production deploys that served in it, and the
117 * issues those pulls close.
118 */
119 export function dayAskLive(db: Database, day: string): DayAskLive {
120 const from = dayStart(day);
121 const to = from + 86_400_000;
122 const since = new Date(from - WINDOW_DAYS * 86_400_000).toISOString();
123 const until = new Date(to).toISOString();
124 const pulls = db
125 .query<
126 { repo_id: string; body: string; merged_at: string },
127 [string, string]
128 >(
129 `SELECT i.repo_id, i.body, p.merged_at
130 FROM pull p JOIN issue i ON i.id = p.issue_id
131 WHERE p.merged_at IS NOT NULL AND p.merged_at >= ?1 AND p.merged_at < ?2`,
132 )
133 .all(since, until);
134 if (pulls.length === 0) return { medianS: null, n: 0 };
135 const deploys = new Map<string, Served[]>();
136 for (const r of db
137 .query<
138 { repo_id: string; created_at: string; serving_at: string },
139 [string, string]
140 >(
141 `SELECT repo_id, created_at, serving_at FROM run
142 WHERE kind = 'deploy' AND env = 'production'
143 AND serving_at IS NOT NULL AND serving_at >= ?1 AND serving_at < ?2
144 AND created_at >= ?1`,
145 )
146 .all(since, until)) {
147 const list = deploys.get(r.repo_id) ?? [];
148 list.push({ createdAt: r.created_at, servingAt: r.serving_at });
149 deploys.set(r.repo_id, list);
150 }
151 // Each closed issue, by `repo#number`, at the first instant one of its
152 // pulls went live.
153 const live = new Map<string, { repoId: string; number: number; at: number }>();
154 for (const p of pulls) {
155 const at = liveAt(p.merged_at, deploys.get(p.repo_id) ?? []);
156 if (at === null) continue;
157 const t = Date.parse(at);
158 for (const number of closesFromBody(p.body)) {
159 const key = `${p.repo_id}#${number}`;
160 const seen = live.get(key);
161 if (seen === undefined || t < seen.at)
162 live.set(key, { repoId: p.repo_id, number, at: t });
163 }
164 }
165 const today = [...live.values()].filter((l) => l.at >= from && l.at < to);
166 if (today.length === 0) return { medianS: null, n: 0 };
167 const opened = new Map<string, number>();
168 const find = db.query<{ created_at: string }, [string, number]>(
169 "SELECT created_at FROM issue WHERE repo_id = ?1 AND number = ?2 AND kind = 'issue'",
170 );
171 for (const l of today) {
172 const row = find.get(l.repoId, l.number);
173 if (row !== null) opened.set(`${l.repoId}#${l.number}`, Date.parse(row.created_at));
174 }
175 const seconds = today.flatMap((l) => {
176 const o = opened.get(`${l.repoId}#${l.number}`);
177 return o === undefined || o > l.at ? [] : [(l.at - o) / 1000];
178 });
179 return { medianS: median(seconds), n: seconds.length };
180 }
src/core/ledger_write.ts added +182
@@ -0,0 +1,182 @@
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 /** Fill the index with what the ledger holds past the index's head. */
96 async function reindex(app: App, dir: string, tip: string): Promise<void> {
97 const head = chainHead(app.db);
98 const { lines } = await readLedger(dir, tip);
99 const entries: SignedEntry[] = [];
100 for (const line of lines) {
101 const entry = JSON.parse(line) as SignedEntry;
102 if (entry.seq > head.seq) entries.push(entry);
103 }
104 if (entries.length === 0) return;
105 const issues = new Map<string, string | null>();
106 const lookup = app.db.query<{ issue_id: string | null }, [string]>(
107 "SELECT issue_id FROM run WHERE id = ?1",
108 );
109 for (const e of entries) issues.set(e.run, lookup.get(e.run)?.issue_id ?? null);
110 indexEntries(app.db, entries, issues);
111 }
112
113 /**
114 * Enter every settled, finished run not yet entered. Returns how many
115 * entries were written: zero when there was nothing to enter, or when
116 * another writer moved the ledger first (the next sweep catches up).
117 */
118 export async function sweepLedger(
119 app: App,
120 now: number = Date.now(),
121 ): Promise<number> {
122 const dir = ledgerDir(app.config.dataDir);
123 if (sweeping.has(dir)) return 0;
124 sweeping.add(dir);
125 try {
126 if (!existsSync(dir)) {
127 const made = await initBareRepo(dir, { defaultBranch: LEDGER_BRANCH });
128 if (!made.ok) return 0;
129 }
130 const tip = await resolveOid(dir, `refs/heads/${LEDGER_BRANCH}`);
131 // Behind git: another writer's batch, a crash between commit and
132 // index, or an index rebuilt from nothing.
133 if (
134 tip !== undefined &&
135 (indexedTip.get(dir) !== tip || chainHead(app.db).seq === 0)
136 ) {
137 await reindex(app, dir, tip);
138 indexedTip.set(dir, tip);
139 }
140 const pending = pendingRuns(
141 app.db,
142 new Date(now - SETTLE_MS).toISOString(),
143 BATCH_MAX,
144 );
145 if (pending.length === 0) return 0;
146 const key = ledgerKey(app.config.dataDir);
147 const rates = computeRates(app.db);
148 let head = chainHead(app.db);
149 const entries: SignedEntry[] = [];
150 const issues = new Map<string, string | null>();
151 for (const run of pending) {
152 const entry = sealEntry(entryFor(run, rates, head.seq + 1, head.hash), key.sign);
153 entries.push(entry);
154 issues.set(run.id, run.issueId);
155 head = { seq: entry.seq, hash: entry.hash };
156 }
157 const first = entries[0]!.seq;
158 const committed = await commitFiles(dir, {
159 branch: LEDGER_BRANCH,
160 message: `ledger: entries ${first}–${head.seq}\n\ntip ${head.hash}\n`,
161 files: [
162 { path: "forge.pub", content: `${key.publicKey}\n` },
163 {
164 path: `entries/${String(first).padStart(12, "0")}.jsonl`,
165 content: entries.map(entryLine).join("\n") + "\n",
166 },
167 ],
168 author: { name: "forge ledger", email: "[email protected]" },
169 land: async (_commit, current) =>
170 current === tip ? ok() : err("the ledger moved under this sweep"),
171 });
172 if (!committed.ok) {
173 indexedTip.delete(dir);
174 return 0;
175 }
176 indexEntries(app.db, entries, issues);
177 indexedTip.set(dir, committed.value.commitOid);
178 return entries.length;
179 } finally {
180 sweeping.delete(dir);
181 }
182 }
src/core/pulls.ts +24
@@ -792,6 +792,30 @@ export function openPullsClosing(
792792 return out;
793793 }
794794
795 /**
796 * Every pull of a repository whose description closes issue `number` —
797 * open, merged or closed unmerged — by its issue row id, with when it
798 * merged. One read: the `LIKE` narrows to bodies naming `#number`, and
799 * `closesFromBody` keeps only those that close it (`#12` is not `#123`).
800 */
801 export function pullsClosing(
802 db: Database,
803 repoId: string,
804 number: number,
805 ): { id: string; mergedAt: string | null }[] {
806 return db
807 .query<
808 { id: string; body: string; merged_at: string | null },
809 [string, string]
810 >(
811 `SELECT i.id, i.body, p.merged_at FROM issue i JOIN pull p ON p.issue_id = i.id
812 WHERE i.repo_id = ?1 AND i.kind = 'pull' AND i.body LIKE ?2`,
813 )
814 .all(repoId, `%#${number}%`)
815 .filter((r) => closesFromBody(r.body).includes(number))
816 .map((r) => ({ id: r.id, mergedAt: r.merged_at }));
817 }
818
795819 /**
796820 * The person whose words a pull answers: the author of the issue it closes
outdated

Stray edit: answers:the should be answers: the.

797821 * (or continues), when that is a person. Derived from the body and the issue
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 +40
@@ -1595,6 +1595,46 @@ 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 `,
1629 // 77 — ask→live (#1389, `core/lead_time.ts`): the board reads the day's
1630 // merged pulls and the production deploys that served, forge-wide, on
1631 // every render; these keep both reads off a table scan.
1632 `
1633 CREATE INDEX IF NOT EXISTS run_deploy_served ON run(serving_at)
1634 WHERE kind = 'deploy' AND serving_at IS NOT NULL;
1635 CREATE INDEX IF NOT EXISTS pull_merged ON pull(merged_at)
1636 WHERE merged_at IS NOT NULL;
1637 `,
15981638 ];
15991639
16001640 /**
src/http/api.ts +7
@@ -286,6 +286,7 @@ import {
286286 } from "../core/runs.ts";
287287 import { resolveOid } from "../git/merge.ts";
288288 import { readUsage, usageDays, USAGE_DAYS_MAX } from "../actions/usage.ts";
289 import { readWorkCost } from "../actions/work_cost.ts";
289290 import { readReturns, reportSpend, RETURNS_DAYS } from "../actions/returns.ts";
290291 import { fleetSelection, readFleetGraph } from "../actions/fleet-graph.ts";
291292 import { readRunLog, subscribeRunLog } from "../runs/log.ts";
@@ -2304,8 +2305,12 @@ export function apiRoutes(router: Router<Handler>): void {
23042305 router.add("GET", "/api/v1/repos/:owner/:name/issues/:number", (ctx) => {
23052306 const found = loadIssue(ctx);
23062307 if ("error" in found) return found.error;
2308 // What the work cost (`actions/work_cost.ts`): the owner's fact, so a
2309 // reader who cannot write here gets no `cost` key at all.
2310 const cost = readWorkCost(ctx.app.db, ctx.auth.user, found.repo, found.issue);
23072311 return json({
23082312 ...withLabels(ctx, found.issue),
2313 ...(cost.ok ? { cost: cost.value } : {}),
23092314 comments: readerMarked(
23102315 ctx,
23112316 found.repo.id,
@@ -2783,8 +2788,10 @@ export function apiRoutes(router: Router<Handler>): void {
27832788 { db: ctx.app.db, requireReview: found.repo.requireReview },
27842789 );
27852790 const hold = getHold(ctx.app.db, found.pull.id);
2791 const cost = readWorkCost(ctx.app.db, ctx.auth.user, found.repo, found.pull);
27862792 return json({
27872793 ...withLabels(ctx, found.pull),
2794 ...(cost.ok ? { cost: cost.value } : {}),
27882795 status,
27892796 diff,
27902797 hold: hold === undefined ? null : holdJson(hold),
src/http/mcp.ts +27 −2
@@ -45,6 +45,7 @@ import {
4545 USAGE_DAYS_DEFAULT,
4646 USAGE_DAYS_MAX,
4747 } from "../actions/usage.ts";
48 import { readWorkCost } from "../actions/work_cost.ts";
4849 import { ITEM_ID } from "../core/interactions.ts";
4950 import {
5051 FEED_LIMIT_DEFAULT,
@@ -1415,6 +1416,30 @@ const TOOLS: readonly Tool[] = [
14151416 : bad("forbidden", "spend is for those who can write this app");
14161417 },
14171418 },
1419 {
1420 name: "cost",
1421 description:
1422 "What the work on one issue or pull cost by the cost ledger: tokens and compute in US dollars, lane-seconds, seconds waiting for a lane and agent seconds; for an issue, summed with every pull that closes it, and seconds from the ask to live once one serves in production; for a pull, seconds open (or open to merged). `line` is the same words the issue page and the terminal show. The same data as `cost` in /api/v1/repos/:owner/:name/issues/:number; refused unless you can write the app.",
1423 inputSchema: {
1424 type: "object",
1425 properties: {
1426 repo: REPO_ARG,
1427 issue: { type: "integer", minimum: 1, description: "An issue or pull number." },
1428 },
1429 required: ["repo", "issue"],
1430 },
1431 writes: false,
1432 run(ctx, user, args) {
1433 const repo = repoArg(ctx, user, args);
1434 if (isAnswer(repo)) return repo;
1435 const issue = issueArg(ctx, repo, args, "issue");
1436 if ("ok" in issue) return issue;
1437 const cost = readWorkCost(ctx.app.db, user, repo, issue);
1438 return cost.ok
1439 ? good({ issue: issue.number, kind: issue.kind, ...cost.value })
1440 : bad("forbidden", "cost is for those who can write this app");
1441 },
1442 },
14181443 {
14191444 name: "link",
14201445 description:
@@ -1680,13 +1705,13 @@ const TOOLS: readonly Tool[] = [
16801705 {
16811706 name: "capacity",
16821707 description:
1683 "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.",
1708 "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.",
16841709 inputSchema: {
16851710 type: "object",
16861711 properties: {
16871712 key: {
16881713 type: "string",
1689 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts"],
1714 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts", "cost.vcpu_hour", "cost.gb_hour"],
16901715 },
16911716 value: { type: "string", maxLength: 16 },
16921717 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/dashboard.ts +25 −4
@@ -18,6 +18,7 @@ import { holdWords, plannerHold } from "../../crew/autonomy.ts";
1818 import { forgeNeeds } from "../../actions/health.ts";
1919 import { mayView } from "../../core/sealed.ts";
2020 import { pinRepo, unpinRepo } from "../../actions/origins.ts";
21 import { dayWorkLine } from "../../actions/work_cost.ts";
2122 import { listAssignedTo, type Issue } from "../../core/issues.ts";
2223 import { listPins, pinnedRepoIds, type Pin } from "../../core/pins.ts";
2324 import { listOrgsForUser } from "../../core/orgs.ts";
@@ -102,6 +103,9 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
102103 };
103104 let focus: PaneId = "repos";
104105
106 /** "today: …" across the top, for a site admin, when the ledger has the day. */
107 let today = "";
108
105109 const reload = (): void => {
106110 // The server remembers the *choice* and nothing about the laptop, so
107111 // this is a list of decisions — never a status that would be stale.
@@ -109,6 +113,11 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
109113 pinned = f.user ? pinnedRepoIds(f.db, f.user.id) : new Set<string>();
110114 all = listReposVisibleTo(f.db, f.user, { limit: 200 });
111115 onYou = assignedToMe();
116 // The forge's day by the cost ledger, as the board's strip has it — a
117 // site admin's, like the strip; nobody else pays for the reads.
118 today = f.user?.isAdmin === true
119 ? dayWorkLine(f.db, new Date().toISOString().slice(0, 10))
120 : "";
112121 const now = new Date();
113122 holds = new Map(
114123 all.flatMap((repo) => {
@@ -273,15 +282,15 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
273282 reload();
274283 return Promise.resolve();
275284 },
276 render(area, s) {
285 render(whole, s) {
277286 const c = ctx.theme.c;
278287 const set = ctx.icons;
279288 // A site admin's forge strip, as the board's: "All fine" or a line
280289 // per cause. Anyone else gets no rows and no reads.
281 let body = area;
290 let body = whole;
282291 if (forge !== undefined) {
283292 const lines = forge.length === 0 ? ["All fine"] : forge.slice(0, 3);
284 const [strip, rest] = split(area, "v", [len(lines.length), fill(1)]);
293 const [strip, rest] = split(whole, "v", [len(lines.length), fill(1)]);
285294 lines.forEach((line, i) =>
286295 s.text(
287296 strip!.x,
@@ -293,7 +302,19 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
293302 );
294303 body = rest!;
295304 }
296 const { main, aside, stacked } = beside(body, ctx.twoPane, {
305 const [dayRow, area] = split(body, "v", [
306 len(today === "" ? 0 : 1),
307 fill(1),
308 ]);
309 if (today !== "")
310 s.text(
311 dayRow!.x,
312 dayRow!.y,
313 truncate(`today: ${today}`, dayRow!.w),
314 style(c.mutedFg, c.bg),
315 dayRow!.x + dayRow!.w,
316 );
317 const { main, aside, stacked } = beside(area!, ctx.twoPane, {
297318 main: fill(3),
298319 aside: fill(2),
299320 });
src/tui/screens/issue.ts +21 −1
@@ -20,6 +20,7 @@ import {
2020 setIssueStateThrough,
2121 } from "../../actions/issues.ts";
2222 import { listRepoRuns } from "../../actions/runs.ts";
23 import { readWorkCost } from "../../actions/work_cost.ts";
2324 import { getIssue, type Issue, type Label } from "../../core/issues.ts";
2425 import type { Repo } from "../../core/repos.ts";
2526 import type { IssueDetail, RepoSource } from "../../view/source.ts";
@@ -68,6 +69,8 @@ export function issueScreen(
6869 const repo = localRepo(src);
6970 /** The local row — who it is assigned to. Undefined on a live browse. */
7071 let issueRow: Issue | undefined;
72 /** "cost: …" under the head, when the ledger has something and it is ours to see. */
73 let cost = "";
7174 /** What the crew has done here, newest first; a card when there is any. */
7275 const crew = new RunList(f);
7376 /** Which pane `j`/`k`/`enter` belong to; `tab` moves between them. */
@@ -84,6 +87,13 @@ export function issueScreen(
8487 }
8588 detail = read.value;
8689 issueRow = repo === undefined ? undefined : getIssue(f.db, repo.id, number);
90 // What the work cost by the ledger, in the web page's words
91 // (`actions/work_cost.ts`); the owner's fact, so empty for anyone else.
92 const priced =
93 repo === undefined || issueRow === undefined
94 ? undefined
95 : readWorkCost(f.db, f.user, repo, issueRow);
96 cost = priced?.ok === true ? priced.value.line : "";
8797 const runs =
8898 repo === undefined || issueRow === undefined
8999 ? undefined
@@ -224,7 +234,8 @@ export function issueScreen(
224234 const issue = detail.issue;
225235 const foot = composer.height();
226236 // The where-strip, then three rows of head: the title, the summary
227 // line, and one blank so the first entry is not glued to the metadata.
237 // line, and the cost line or one blank so the first entry is not glued
238 // to the metadata.
228239 // Then the crew card, only when an agent has worked here.
229240 const crewH =
230241 crew.runs.length === 0 ? 0 : Math.min(crew.runs.length, CREW_ROWS) + 2;
@@ -274,6 +285,15 @@ export function issueScreen(
274285 { text: label.name, color: label.color },
275286 right,
276287 );
288 // The head's third row: blank, or what the work cost.
289 if (cost !== "")
290 s.text(
291 head!.x,
292 head!.y + 2,
293 truncate(`cost: ${cost}`, head!.w),
294 style(c.mutedFg, c.bg),
295 right,
296 );
277297 if (crewH > 0) {
278298 const inner = card(s, crewRow!, c, {
279299 title: `Crew · ${plural(crew.runs.length, "run")}`,
src/tui/screens/pull.ts +26 −2
@@ -30,6 +30,7 @@ import {
3030 addCommentThrough,
3131 setIssueStateThrough,
3232 } from "../../actions/issues.ts";
33 import { readWorkCost } from "../../actions/work_cost.ts";
3334 import {
3435 addReview,
3536 mergePull,
@@ -211,6 +212,8 @@ export function pullScreen(
211212 let requireChecks = repo?.requireChecks === true;
212213 /** The local issue row — who it is assigned to. Undefined on a live browse. */
213214 let issueRow: Issue | undefined;
215 /** "cost: …" under the head, when the ledger has something and it is ours to see. */
216 let cost = "";
214217 /** Whether the repository is an app, and its preview of this pull if so. */
215218 let isApp = false;
216219 let preview: EnvStatus | undefined;
@@ -244,6 +247,13 @@ export function pullScreen(
244247 : withOutdated(listReviewComments(f.db, row.id), diff);
245248 threads = row === undefined ? [] : readThreads(row);
246249 issueRow = repo === undefined ? undefined : getIssue(f.db, repo.id, number);
250 // What the work cost by the ledger, in the web page's words
251 // (`actions/work_cost.ts`); the owner's fact, so empty for anyone else.
252 const priced =
253 repo === undefined || issueRow === undefined
254 ? undefined
255 : readWorkCost(f.db, f.user, repo, issueRow);
256 cost = priced?.ok === true ? priced.value.line : "";
247257 // The app half: the preview environment (in memory, from the runtime),
248258 // the checks at the live head (a row), and what the crew has done here.
249259 const record = repo === undefined ? undefined : getAppByRepo(f.db, repo.id);
@@ -653,12 +663,17 @@ export function pullScreen(
653663 "v",
654664 [
655665 len(whereRows(src)),
656 len(2),
666 len(cost === "" ? 2 : 3),
657667 len(isApp ? 1 : 0),
658668 len(boxH),
659669 len(2),
660670 fill(1),
661 len(Math.min(foot, Math.max(0, area.h - 13 - whereRows(src)))),
671 len(
672 Math.min(
673 foot,
674 Math.max(0, area.h - 13 - (cost === "" ? 0 : 1) - whereRows(src)),
675 ),
676 ),
662677 ],
663678 );
664679 whereStrip(s, strip!, c, f, src);
@@ -694,6 +709,15 @@ export function pullScreen(
694709 style(c.mutedFg, c.bg),
695710 edge,
696711 );
712 // A third row when the ledger has something to say and it is ours.
713 if (cost !== "")
714 s.text(
715 head!.x,
716 head!.y + 2,
717 truncate(`cost: ${cost}`, head!.w),
718 style(c.mutedFg, c.bg),
719 edge,
720 );
697721 if (isApp && previewRow!.h > 0)
698722 drawPreviewLine(s, previewRow!, c, preview);
699723 drawMergeBox(s, boxRow!, c, issue, facts, view.summary(), mirrored(), {
src/web/pages/board.ts +8
@@ -14,6 +14,7 @@
1414 * pointer. The old big view (`/big`, every address it had) lands here.
1515 */
1616
17 import { dayWorkLine } from "../../actions/work_cost.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,12 @@ 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 // Beside the dollars, the day's lead time (`core/lead_time.ts`): the
341 // median from an issue opening to its change serving in production, over
342 // the issues that went live today.
343 const today = dayWorkLine(app.db, new Date().toISOString().slice(0, 10));
337344 return html`<div
338345 class="board-forge"
339346 id="forge"
@@ -354,6 +361,7 @@ function forgeStrip(ctx: Ctx): Html | null {
354361 : html`<a class="board-forge-need" href="${href}">${need}</a>`;
355362 })
356363 }
364 ${today === "" ? "" : html`<span class="board-forge-cost" id="day-cost">today: ${today}</span>`}
357365 </div>`;
358366 }
359367
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 +13
@@ -12,6 +12,7 @@
1212 */
1313
1414 import type { Database } from "bun:sqlite";
15 import { readWorkCost } from "../../actions/work_cost.ts";
1516 import {
1617 cancelRepoRun,
1718 listRepoRuns,
@@ -113,6 +114,18 @@ 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, in the words
119 * every door shares (`actions/work_cost.ts`): an issue with its pulls and
120 * ask→live, a change with how long it has been open. Owner's facts, like
121 * `workSpent`; nothing before the ledger has an entry for it.
122 */
123 export function ledgerCost(ctx: Ctx, repo: Repo, issue: Issue): Html {
124 const cost = readWorkCost(ctx.app.db, ctx.auth.user, repo, issue);
125 if (!cost.ok || cost.value.line === "") return html``;
126 return html`<span class="num" id="ledger-cost">cost: ${cost.value.line}</span>`;
127 }
128
116129 /**
117130 * What a finished agent run read and wrote, in tokens, from the usage ledger
118131 * (`core/usage.ts`) — counted by the provider, so no tilde. Placed beside the
src/web/studio/change.ts +2 −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,7 @@ export function changeHead(ctx: Ctx, repo: Repo, pull: Pull): Html {
204204 >`,
205205 )}
206206 ${workSpent(ctx, repo, pull.id)}
207 ${ledgerCost(ctx, repo, pull)}
207208 </div>
208209 </div>`;
209210 }
src/web/studio/tell.ts +2 −1
@@ -47,6 +47,7 @@ import {
4747 costText,
4848 durationText,
4949 reasonWords,
50 ledgerCost,
5051 workSpent,
5152 } from "../pages/runs.ts";
5253 import {
@@ -322,7 +323,7 @@ async function studioTell(
322323 () =>
323324 badge("Sealed security report", { tone: "danger", icon: "lock" }),
324325 )}
325 ${workSpent(ctx, repo, issue.id)}
326 ${workSpent(ctx, repo, issue.id)} ${ledgerCost(ctx, repo, issue)}
outdated

This line is the only place an issue's cost or ask→live can be seen. The TUI issue screen and the MCP and JSON issue reads need the same roll-up, behind the same canSeeOwnerFacts gate.

326327 ${issue.assigneeName !== null
327328 ? html`<span
328329 >${when(issue.assigneeIsAgent, () => icon("bot"))}
test/ledger-cost.test.ts added +325
@@ -0,0 +1,325 @@
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 } from "../src/apps/contain.ts";
13 import { setCapacity } from "../src/core/capacity.ts";
14 import {
15 costLine,
16 dayCost,
17 entryFor,
18 GENESIS,
19 issueCost,
20 sealEntry,
21 verifyChain,
22 type FinishedRun,
23 } from "../src/core/cost_ledger.ts";
24 import { ledgerDir, readLedger, sweepLedger } from "../src/core/ledger_write.ts";
25 import { recordUsage } from "../src/core/usage.ts";
26 import { claimRun, createRun, finishRun, getRun } from "../src/core/runs.ts";
27 import { getUserByName } from "../src/core/users.ts";
28 import { resolveOid } from "../src/git/merge.ts";
29 import { forgeHttp } from "../src/http/server.ts";
30 import {
31 ledgerKey,
32 ledgerKeyFromSecret,
33 verifySignature,
34 } from "../src/kernel/ledger_key.ts";
35
36 describe("the cell's meter", () => {
37 test("counts each process's CPU growth and integrates resident memory", () => {
38 const usage = newUsage();
39 const entry = { usage, seen: new Map<number, number>(), lastAt: undefined };
40 // First look: pid 10 has used 150 ticks (1.5 s at CLK_TCK 100), 1 GiB resident.
41 meter(entry, [10], new Map([[10, { ticks: 150 }]]), 1024 * 1024, 1_000);
42 // Two seconds on: pid 10 grew 50 ticks, pid 11 appeared with 30; 2 GiB.
43 meter(
44 entry,
45 [10, 11],
46 new Map([
47 [10, { ticks: 200 }],
48 [11, { ticks: 30 }],
49 ]),
50 2 * 1024 * 1024,
51 3_000,
52 );
53 // pid 10 exited: what it used stays counted; pid 11 grew 20.
54 meter(entry, [11], new Map([[11, { ticks: 50 }]]), 0, 4_000);
55 // CPU: (150 + 50 + 30 + 20) / 100 = 2.5 s.
56 expect(usage.cpuS).toBeCloseTo(2.5, 9);
57 // Memory: 1 GiB × 1 s (first tick) + 2 GiB × 2 s + 0 = 5 GiB·s.
58 expect(usage.memGbS).toBeCloseTo(5, 9);
59 });
60
61 test("a meterless cell counts nothing", () => {
62 const entry = { usage: undefined, seen: new Map<number, number>(), lastAt: undefined };
63 meter(entry, [1], new Map([[1, { ticks: 100 }]]), 1024, 0);
64 expect(entry.seen.size).toBe(0);
65 });
66 });
67
68 const run = (over: Partial<FinishedRun> = {}): FinishedRun => ({
69 id: "r1",
70 kind: "check",
71 repoId: "p1",
72 repo: "ada/hello",
73 issueId: "i1",
74 issueNumber: 7,
75 issueKind: "pull",
76 state: "ok",
77 createdAt: "2026-10-14T10:00:00.000Z",
78 startedAt: "2026-10-14T10:05:00.000Z",
79 finishedAt: "2026-10-14T10:30:00.000Z",
80 cpuS: 3600,
81 memGbS: 7200,
82 tokensIn: 0,
83 tokensOut: 0,
84 costUsd: 0,
85 ...over,
86 });
87
88 describe("an entry, by hand", () => {
89 test("times and the compute price match the arithmetic", () => {
90 const e = entryFor(run(), { vcpuHour: 0.04048, gbHour: 0.004445 }, 1, GENESIS);
91 expect(e.wall_s).toBe(1500); // 10:05 → 10:30
92 expect(e.lane_wait_s).toBe(300); // 10:00 → 10:05
93 expect(e.pull).toBe(7);
94 expect(e.issue).toBeNull();
95 // 3600 CPU-s = 1 vCPU-h × 0.04048 + 7200 GiB-s = 2 GiB-h × 0.004445 = 0.04937.
96 expect(e.usd_compute).toBe(0.04937);
97 });
98
99 test("unmeasured compute is null, not zero", () => {
100 const e = entryFor(run({ cpuS: null, memGbS: null }), { vcpuHour: 1, gbHour: 1 }, 1, GENESIS);
101 expect(e.cpu_s).toBeNull();
102 expect(e.usd_compute).toBeNull();
103 });
104
105 test("the forge's key signs, and only it verifies", () => {
106 const key = ledgerKeyFromSecret(new Uint8Array(32).fill(1));
107 const other = ledgerKeyFromSecret(new Uint8Array(32).fill(2));
108 const sig = key.sign("abc");
109 expect(verifySignature(key.publicKey, "abc", sig)).toBe(true);
110 expect(verifySignature(key.publicKey, "abd", sig)).toBe(false);
111 expect(verifySignature(other.publicKey, "abc", sig)).toBe(false);
112 expect(verifySignature("short", "abc", sig)).toBe(false);
113 });
114 });
115
116 describe("the ledger", () => {
117 let dataDir: string;
118 let app: App;
119 let fetch: (path: string, init?: RequestInit) => Promise<Response>;
120 let cookie = "";
121 let repoId = "";
122 let issueId = "";
123 const later = (): number => Date.now() + 120_000;
124
125 const finished = (
126 kind: "agent" | "check" | "deploy",
127 usage?: { cpuS: number; memGbS: number },
128 ): string => {
129 const made = createRun(app.db, { repoId, kind, issueId });
130 claimRun(app.db, made.id);
131 finishRun(app.db, made.id, {
132 state: "ok",
133 summary: "done",
134 ...(usage === undefined ? {} : { usage }),
135 });
136 return made.id;
137 };
138
139 beforeAll(async () => {
140 dataDir = await mkdtemp(join(tmpdir(), "forge-ledger-"));
141 app = createApp({ dataDir, port: 0 });
142 // In-process, no listener: the same routes a served forge answers with.
143 const http = forgeHttp(app);
144 fetch = (path, init) =>
145 http.handle(new Request(`http://localhost${path}`, init));
146 const signed = await fetch(`/signup`, {
147 method: "POST",
148 body: new URLSearchParams({
149 username: "ada",
150 email: "[email protected]",
151 password: "analytical-engine",
152 }),
153 redirect: "manual",
154 });
155 cookie = (signed.headers.get("set-cookie") ?? "").split(";")[0]!;
156 const headers = { cookie, "content-type": "application/json" };
157 const repo = (await fetch(`/api/v1/repos`, {
158 method: "POST",
159 headers,
160 body: JSON.stringify({ name: "hello", visibility: "public" }),
161 }).then((r) => r.json())) as { id: string };
162 repoId = repo.id;
163 const issue = (await fetch(`/api/v1/repos/ada/hello/issues`, {
164 method: "POST",
165 headers,
166 body: JSON.stringify({ title: "make it cheaper" }),
167 }).then((r) => r.json())) as { id: string; number: number };
168 issueId = app.db
169 .query<{ id: string }, [string, number]>(
170 "SELECT id FROM issue WHERE repo_id = ?1 AND number = ?2",
171 )
172 .get(repoId, issue.number)!.id;
173 });
174
175 afterAll(async () => {
176 app.close();
177 await rm(dataDir, { recursive: true, force: true });
178 });
179
180 test("a sweep with no finished runs writes nothing", async () => {
181 expect(await sweepLedger(app, later())).toBe(0);
182 const dir = ledgerDir(dataDir);
183 expect(await resolveOid(dir, "refs/heads/main")).toBeUndefined();
184 expect(dayCost(app.db, new Date().toISOString().slice(0, 10)).runs).toBe(0);
185 });
186
187 test("a run that never started is never entered", async () => {
188 createRun(app.db, { repoId, kind: "check", issueId });
189 expect(await sweepLedger(app, later())).toBe(0);
190 });
191
192 test("a run that just finished waits to settle", async () => {
193 finished("deploy");
194 expect(await sweepLedger(app, Date.now())).toBe(0);
195 });
196
197 test("every finished run gets one entry, with its cell's numbers", async () => {
198 const check = finished("check", { cpuS: 90, memGbS: 45 });
199 expect(getRun(app.db, check)!.cpuS).toBe(90);
200 const agent = finished("agent");
201 const smith = getUserByName(app.db, "ada")!.id;
202 recordUsage(app.db, {
203 runId: agent,
204 repoId,
205 issueId,
206 agentId: smith,
207 subscriptionId: null,
208 tokensIn: 1200,
209 tokensOut: 300,
210 costUsd: 0.42,
211 wallMs: 1000,
212 outcome: "ok",
213 at: new Date().toISOString(),
214 });
215 expect(await sweepLedger(app, later())).toBe(3); // the deploy, the check, the agent
216 expect(await sweepLedger(app, later())).toBe(0); // entered once
217
218 const { publicKey, lines } = await readLedger(ledgerDir(dataDir));
219 expect(publicKey).toBe(ledgerKey(dataDir).publicKey);
220 expect(lines).toHaveLength(3);
221 const entries = lines.map((l) => JSON.parse(l) as Record<string, unknown>);
222 const byRun = new Map(entries.map((e) => [e["run"], e]));
223 expect(byRun.get(check)!["cpu_s"]).toBe(90);
224 expect(byRun.get(check)!["mem_gb_s"]).toBe(45);
225 // 90/3600 × 0.04048 + 45/3600 × 0.004445 = 0.001012 + 0.0000555625 → 0.001068 (6 places)
226 expect(byRun.get(check)!["usd_compute"]).toBe(0.001068);
227 expect(byRun.get(agent)!["tokens_in"]).toBe(1200);
228 expect(byRun.get(agent)!["usd_tokens"]).toBe(0.42);
229 expect(byRun.get(agent)!["cpu_s"]).toBeNull();
230 expect(verifyChain(lines, publicKey)).toEqual({
231 ok: true,
232 count: 3,
233 tip: entries[2]!["hash"] as string,
234 });
235 });
236
237 test("the forge's rate is the setting, and written into the entry", async () => {
238 setCapacity(app.db, "cost.vcpu_hour", "1", getUserByName(app.db, "ada")!.id);
239 const id = finished("check", { cpuS: 1800, memGbS: 0 });
240 expect(await sweepLedger(app, later())).toBe(1);
241 const { lines } = await readLedger(ledgerDir(dataDir));
242 const last = JSON.parse(lines.at(-1)!) as Record<string, unknown>;
243 expect(last["run"]).toBe(id);
244 expect(last["rate_vcpu_h"]).toBe(1);
245 expect(last["usd_compute"]).toBe(0.5); // half a vCPU-hour at US$1
246 setCapacity(app.db, "cost.vcpu_hour", null, getUserByName(app.db, "ada")!.id);
247 });
248
249 test("roll-ups are the sums of the entries", async () => {
250 const { lines } = await readLedger(ledgerDir(dataDir));
251 const entries = lines.map((l) => JSON.parse(l) as Record<string, number | string | null>);
252 const sum = (f: string, keep = (_: Record<string, unknown>) => true): number =>
253 entries.filter(keep).reduce((s, e) => s + Number(e[f] ?? 0), 0);
254 const r = issueCost(app.db, issueId);
255 expect(r.runs).toBe(entries.length);
256 expect(r.usdTokens).toBeCloseTo(sum("usd_tokens"), 9);
257 expect(r.usdCompute).toBeCloseTo(sum("usd_compute"), 9);
258 expect(r.measured).toBe(entries.filter((e) => e["usd_compute"] !== null).length);
259 expect(r.waitS).toBeCloseTo(sum("lane_wait_s"), 9);
260 expect(r.laneS).toBeCloseTo(
261 sum("wall_s", (e) => e["kind"] === "check" || e["kind"] === "deploy"),
262 9,
263 );
264 const day = dayCost(app.db, new Date().toISOString().slice(0, 10));
265 expect(day.runs).toBe(entries.length);
266 expect(costLine(r)).toStartWith("$0.42 tokens · $0.50 compute");
267 });
268
269 test("the issue's page shows the cost to its owner, and not to a stranger", async () => {
270 const page = await fetch(`/ada/hello/issues/1`, {
271 headers: { cookie },
272 }).then((r) => r.text());
273 expect(page).toContain(`id="ledger-cost"`);
274 expect(page).toContain("cost: $0.42 tokens");
275 const anon = await fetch(`/ada/hello/issues/1`).then((r) => r.text());
276 expect(anon).not.toContain(`id="ledger-cost"`);
277 });
278
279 test("an index lost is rebuilt from git, not re-entered", async () => {
280 const before = (await readLedger(ledgerDir(dataDir))).lines.length;
281 app.db.exec("DELETE FROM cost_entry");
282 expect(await sweepLedger(app, later())).toBe(0);
283 expect(issueCost(app.db, issueId).runs).toBe(before);
284 expect((await readLedger(ledgerDir(dataDir))).lines.length).toBe(before);
285 });
286
287 test("a tampered entry breaks verification at its own link", async () => {
288 const { publicKey, lines } = await readLedger(ledgerDir(dataDir));
289 const forged = [...lines];
290 const second = JSON.parse(forged[1]!) as Record<string, unknown>;
291 second["wall_s"] = Number(second["wall_s"]) - 60; // a lane-minute taken off the bill
292 forged[1] = JSON.stringify(second);
293 expect(verifyChain(forged, publicKey)).toMatchObject({
294 ok: false,
295 seq: 2,
296 reason: "hash does not match the entry",
297 });
298 // Re-hashing the forgery does not help: the next link names the old hash,
299 // and the forger has no key to re-sign with.
300 const key = ledgerKeyFromSecret(new Uint8Array(32).fill(9));
301 const resealed = sealEntry(second as never, key.sign);
302 forged[1] = JSON.stringify(resealed);
303 expect(verifyChain(forged, publicKey)).toMatchObject({
304 ok: false,
305 seq: 2,
306 reason: "signature does not verify",
307 });
308 // Dropping an entry breaks the link after the gap.
309 expect(verifyChain([lines[0]!, lines[2]!], publicKey)).toMatchObject({
310 ok: false,
311 seq: 2,
312 });
313 });
314
315 test("the verify script walks the repository and says ok", async () => {
316 const proc = Bun.spawn(
317 ["bun", "scripts/ledger-verify.ts", ledgerDir(dataDir)],
318 { stdout: "pipe", stderr: "pipe", env: { PATH: process.env["PATH"] ?? "" } },
319 );
320 const out = await new Response(proc.stdout).text();
321 const said = await new Response(proc.stderr).text();
322 expect({ code: await proc.exited, said }).toEqual({ code: 0, said: "" });
323 expect(out).toStartWith("ok: 4 entries");
324 });
325 });
test/ledger-doors.test.ts added +293
@@ -0,0 +1,293 @@
1 /**
2 * Every door to an issue's cost says the same thing (#1389): the web issue
3 * and change pages, the issue and pull JSON, the MCP `cost` tool and the
4 * terminal's issue, pull and dashboard screens all read
5 * `actions/work_cost.ts` — and a reader who cannot write the repository
6 * gets none of it, on any of them.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import {
14 entryFor,
15 indexEntries,
16 sealEntry,
17 type FinishedRun,
18 } from "../src/core/cost_ledger.ts";
19 import { createIssue } from "../src/core/issues.ts";
20 import { getRepo, type Repo } from "../src/core/repos.ts";
21 import { createRun } from "../src/core/runs.ts";
22 import { createToken } from "../src/core/tokens.ts";
23 import { createUser, type User } from "../src/core/users.ts";
24 import { forgeHttp } from "../src/http/server.ts";
25 import { createForgeApp } from "../src/tui/forge.ts";
26 import { issueScreen } from "../src/tui/screens/issue.ts";
27 import { pullScreen } from "../src/tui/screens/pull.ts";
28 import { local } from "../src/tui/screens/where.ts";
29 import type { Session } from "../src/tui/session.ts";
30 import type { App as Tui, Screen } from "../src/tui/app/app.ts";
31 import { headlessTerminal } from "../src/tui/term/terminal.ts";
32 import { settleApp } from "./helpers/tui.ts";
33 import { quietLogs } from "./helpers/globals.ts";
34
35 quietLogs();
36
37 const H = 3600;
38
39 describe("the cost line, through every door", () => {
40 let dataDir: string;
41 let app: App;
42 let fetch: (path: string, init?: RequestInit) => Promise<Response>;
43 let ada: User;
44 let bob: User;
45 let repo: Repo;
46 let adaToken = "";
47 let bobToken = "";
48 let ask = { id: "", number: 0 };
49 let change = { id: "", number: 0 };
50 let seq = 0;
51
52 const issue = (
53 title: string,
54 body: string,
55 kind: "issue" | "pull",
56 at: string,
57 ): { id: string; number: number } => {
58 const made = createIssue(app.db, {
59 repoId: repo.id,
60 authorId: ada.id,
61 title,
62 body,
63 kind,
64 });
65 if (!made.ok) throw new Error(made.error);
66 app.db
67 .query("UPDATE issue SET created_at = ?2 WHERE id = ?1")
68 .run(made.value.id, at);
69 return { id: made.value.id, number: made.value.number };
70 };
71
72 const entry = (issueId: string, usd: number): void => {
73 const end = Date.now();
74 const run: FinishedRun = {
75 id: `run-${++seq}`,
76 kind: "agent",
77 repoId: repo.id,
78 repo: "ada/hello",
79 issueId,
80 issueNumber: null,
81 issueKind: null,
82 state: "ok",
83 createdAt: new Date(end - 60_000).toISOString(),
84 startedAt: new Date(end - 60_000).toISOString(),
85 finishedAt: new Date(end).toISOString(),
86 cpuS: null,
87 memGbS: null,
88 tokensIn: 0,
89 tokensOut: 0,
90 costUsd: usd,
91 };
92 const sealed = sealEntry(
93 entryFor(run, { vcpuHour: 0, gbHour: 0 }, seq, "0".repeat(64)),
94 () => "",
95 );
96 indexEntries(app.db, [sealed], new Map([[run.id, issueId]]));
97 };
98
99 /** What `user`'s terminal shows once `make` is on top and settled. */
100 const terminal = async (
101 user: User,
102 make: (s: Session, ctx: Tui["ctx"]) => Screen | undefined,
103 ): Promise<string> => {
104 const { app: tui, session } = createForgeApp(
105 app,
106 {
107 sshUsername: user.username,
108 remoteAddress: "127.0.0.1",
109 fingerprint: `SHA256:${user.username}`,
110 user,
111 },
112 { terminal: headlessTerminal(160, 40), exitHooks: false },
113 );
114 tui.start();
115 try {
116 const screen = make(session, tui.ctx);
117 if (screen !== undefined) tui.ctx.push(screen);
118 await settleApp(tui);
119 return tui.screen.toText();
120 } finally {
121 tui.stop();
122 }
123 };
124
125 const mcpCost = async (token: string, number: number) => {
126 const res = await fetch(`/mcp`, {
127 method: "POST",
128 headers: {
129 "content-type": "application/json",
130 accept: "application/json, text/event-stream",
131 authorization: `Bearer ${token}`,
132 },
133 body: JSON.stringify({
134 jsonrpc: "2.0",
135 id: 1,
136 method: "tools/call",
137 params: { name: "cost", arguments: { repo: "ada/hello", issue: number } },
138 }),
139 });
140 const body = (await res.json()) as any;
141 const text: string = body.result.content[0].text;
142 return body.result.isError === true
143 ? { error: text }
144 : { value: JSON.parse(text) };
145 };
146
147 beforeAll(async () => {
148 dataDir = await mkdtemp(join(tmpdir(), "forge-ledger-doors-"));
149 app = createApp({ dataDir, port: 0 });
150 const http = forgeHttp(app);
151 fetch = (path, init) => http.handle(new Request(`http://localhost${path}`, init));
152 const a = await createUser(app.db, {
153 trusted: true,
154 username: "ada",
155 email: "[email protected]",
156 password: "analytical-engine",
157 adminIfFirst: true,
158 });
159 if (!a.ok) throw new Error(a.error);
160 ada = a.value;
161 const b = await createUser(app.db, {
162 trusted: true,
163 username: "bob",
164 email: "[email protected]",
165 password: "difference-engine",
166 });
167 if (!b.ok) throw new Error(b.error);
168 bob = b.value;
169 adaToken = createToken(app.db, ada.id, "rw", "rw").token;
170 bobToken = createToken(app.db, bob.id, "rw", "rw").token;
171 const made = await fetch(`/api/v1/repos`, {
172 method: "POST",
173 headers: { authorization: `Bearer ${adaToken}`, "content-type": "application/json" },
174 body: JSON.stringify({ name: "hello", visibility: "public" }),
175 });
176 expect(made.status).toBe(201);
177 repo = getRepo(app.db, "ada", "hello")!;
178
179 // Opened 3 h ago; its pull opened 2 h ago and merged 10 min ago; a
180 // production deploy queued after the merge served a second ago.
181 const now = Date.now();
182 const ago = (s: number): string => new Date(now - s * 1000).toISOString();
183 ask = issue("ship the thing", "", "issue", ago(3 * H));
184 change = issue("the thing", `Closes #${ask.number}`, "pull", ago(2 * H));
185 app.db
186 .query(
187 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at)
188 VALUES (?1, 'main', 'torque/thing', ?2, ?2, ?3)`,
189 )
190 .run(change.id, "0".repeat(40), ago(600));
191 const deploy = createRun(app.db, { repoId: repo.id, kind: "deploy", env: "production" });
192 app.db
193 .query("UPDATE run SET created_at = ?2, started_at = ?2, serving_at = ?3 WHERE id = ?1")
194 .run(deploy.id, ago(300), ago(1));
195 entry(ask.id, 0.5);
196 entry(change.id, 0.25);
197 });
198
199 afterAll(async () => {
200 app.close();
201 await rm(dataDir, { recursive: true, force: true });
202 });
203
204 // By hand: $0.50 + $0.25 = $0.75 over the issue and its one pull; asked
205 // 3 h before its change served. The pull alone: $0.25, open 2 h less the
206 // 10 min since it merged = 110 min.
207 const ISSUE_LINE = /^\$0\.75 tokens · .* · with 1 pull · ask→live 3\.0 h$/;
208 const PULL_LINE = /^\$0\.25 tokens · .* · open→merged 110 min$/;
209
210 test("the issue and pull JSON carry the roll-up for the owner", async () => {
211 const auth = { authorization: `Bearer ${adaToken}` };
212 const i = (await fetch(`/api/v1/repos/ada/hello/issues/${ask.number}`, {
213 headers: auth,
214 }).then((r) => r.json())) as any;
215 expect(i.cost.line).toMatch(ISSUE_LINE);
216 expect(i.cost.rollup.runs).toBe(2);
217 expect(i.cost.rollup.usdTokens).toBeCloseTo(0.75, 9);
218 expect(i.cost.pulls).toBe(1);
219 expect(i.cost.askLiveS).toBeCloseTo(3 * H - 1, 0);
220
221 const p = (await fetch(`/api/v1/repos/ada/hello/pulls/${change.number}`, {
222 headers: auth,
223 }).then((r) => r.json())) as any;
224 expect(p.cost.line).toMatch(PULL_LINE);
225 expect(p.cost.merged).toBe(true);
226 expect(p.cost.openS).toBeCloseTo(110 * 60, 0);
227
228 // The web page prints the same words.
229 const page = await fetch(`/ada/hello/issues/${ask.number}`, {
230 headers: auth,
231 }).then((r) => r.text());
232 expect(page).toContain(`id="ledger-cost">cost: ${i.cost.line}<`);
233 });
234
235 test("the MCP cost tool answers the same", async () => {
236 const i = await mcpCost(adaToken, ask.number);
237 expect(i.value.kind).toBe("issue");
238 expect(i.value.line).toMatch(ISSUE_LINE);
239 const p = await mcpCost(adaToken, change.number);
240 expect(p.value.kind).toBe("pull");
241 expect(p.value.line).toMatch(PULL_LINE);
242 expect((await mcpCost(adaToken, 999)).error).toContain("no issue #999");
243 });
244
245 test("the terminal's issue and pull screens, and the admin's dashboard", async () => {
246 const onIssue = await terminal(ada, (s, ctx) =>
247 issueScreen(s, ctx, local(s, repo), ask.number),
248 );
249 expect(onIssue).toMatch(/cost: \$0\.75 tokens · .* · with 1 pull · ask→live 3\.0 h/);
250 const onPull = await terminal(ada, (s, ctx) =>
251 pullScreen(s, ctx, local(s, repo), change.number),
252 );
253 expect(onPull).toMatch(/cost: \$0\.25 tokens · .* · open→merged 110 min/);
254 const home = await terminal(ada, () => undefined);
255 expect(home).toContain("today: $0.75 tokens");
256 expect(home).toContain("median ask→live 3.0 h (1 live)");
257 });
258
259 test("a reader who cannot write here gets none of it, on any door", async () => {
260 const auth = { authorization: `Bearer ${bobToken}` };
261 const i = (await fetch(`/api/v1/repos/ada/hello/issues/${ask.number}`, {
262 headers: auth,
263 }).then((r) => r.json())) as any;
264 expect(i.number).toBe(ask.number);
265 expect("cost" in i).toBe(false);
266 const p = (await fetch(`/api/v1/repos/ada/hello/pulls/${change.number}`, {
267 headers: auth,
268 }).then((r) => r.json())) as any;
269 expect(p.number).toBe(change.number);
270 expect("cost" in p).toBe(false);
271 const anon = (await fetch(`/api/v1/repos/ada/hello/issues/${ask.number}`).then(
272 (r) => r.json(),
273 )) as any;
274 expect("cost" in anon).toBe(false);
275
276 expect((await mcpCost(bobToken, ask.number)).error).toContain(
277 "cost is for those who can write this app",
278 );
279
280 const onIssue = await terminal(bob, (s, ctx) =>
281 issueScreen(s, ctx, local(s, repo), ask.number),
282 );
283 expect(onIssue).toContain("ship the thing");
284 expect(onIssue).not.toContain("cost:");
285 const onPull = await terminal(bob, (s, ctx) =>
286 pullScreen(s, ctx, local(s, repo), change.number),
287 );
288 expect(onPull).toContain("the thing");
289 expect(onPull).not.toContain("cost:");
290 const home = await terminal(bob, () => undefined);
291 expect(home).not.toContain("today:");
292 });
293 });
test/ledger-rollup.test.ts added +281
@@ -0,0 +1,281 @@
1 /**
2 * The cost ledger's roll-ups (#1389): an issue's cost is its own entries
3 * plus those of every pull that closes it, and ask→live — issue opened to
4 * its change serving in production — has a day's median that equals the
5 * hand calculation.
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 {
13 costOf,
14 entryFor,
15 indexEntries,
16 issueCost,
17 sealEntry,
18 type FinishedRun,
19 } from "../src/core/cost_ledger.ts";
20 import { createIssue } from "../src/core/issues.ts";
21 import {
22 dayAskLive,
23 issueAskLive,
24 liveAt,
25 median,
26 } from "../src/core/lead_time.ts";
27 import { pullsClosing } from "../src/core/pulls.ts";
28 import { createRun } from "../src/core/runs.ts";
29 import { forgeHttp } from "../src/http/server.ts";
30
31 const H = 3600;
32
33 describe("the median, by hand", () => {
34 test("odd, even, unsorted and empty sets", () => {
35 expect(median([7, 1, 3])).toBe(3);
36 // (2 + 4) / 2
37 expect(median([4, 1, 2, 10])).toBe(3);
38 expect(median([5])).toBe(5);
39 expect(median([])).toBeNull();
40 });
41
42 test("a change is live at the first deploy queued after its merge", () => {
43 const deploys = [
44 // Queued before the merge: cannot carry it, though it served after.
45 { createdAt: "2026-03-10T09:00:00.000Z", servingAt: "2026-03-10T10:30:00.000Z" },
46 { createdAt: "2026-03-10T10:05:00.000Z", servingAt: "2026-03-10T10:20:00.000Z" },
47 { createdAt: "2026-03-10T11:00:00.000Z", servingAt: "2026-03-10T11:10:00.000Z" },
48 ];
49 expect(liveAt("2026-03-10T10:00:00.000Z", deploys)).toBe("2026-03-10T10:20:00.000Z");
50 expect(liveAt("2026-03-10T12:00:00.000Z", deploys)).toBeNull();
51 });
52 });
53
54 describe("roll-ups over a forge", () => {
55 let dataDir: string;
56 let app: App;
57 let fetch: (path: string, init?: RequestInit) => Promise<Response>;
58 let cookie = "";
59 let repoId = "";
60 let quietId = "";
61 let authorId = "";
62 let seq = 0;
63
64 const issue = (
65 repo: string,
66 title: string,
67 opts: { body?: string; kind?: "issue" | "pull"; at?: string } = {},
68 ): { id: string; number: number } => {
69 const made = createIssue(app.db, {
70 repoId: repo,
71 authorId,
72 title,
73 body: opts.body ?? "",
74 kind: opts.kind ?? "issue",
75 });
76 if (!made.ok) throw new Error(made.error);
77 if (opts.at !== undefined)
78 app.db.query("UPDATE issue SET created_at = ?2 WHERE id = ?1").run(made.value.id, opts.at);
79 return { id: made.value.id, number: made.value.number };
80 };
81
82 const pull = (
83 repo: string,
84 closes: string,
85 mergedAt: string | null,
86 ): { id: string; number: number } => {
87 const p = issue(repo, `work on ${closes}`, { body: closes, kind: "pull" });
88 app.db
89 .query(
90 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at)
91 VALUES (?1, 'main', ?2, ?3, ?3, ?4)`,
92 )
93 .run(p.id, `torque/${p.number}`, "0".repeat(40), mergedAt);
94 return p;
95 };
96
97 const deploy = (repo: string, createdAt: string, servingAt: string): void => {
98 const run = createRun(app.db, { repoId: repo, kind: "deploy", env: "production" });
99 app.db
100 .query("UPDATE run SET created_at = ?2, started_at = ?2, serving_at = ?3 WHERE id = ?1")
101 .run(run.id, createdAt, servingAt);
102 };
103
104 /** One ledger entry against an issue or pull, with the numbers given. */
105 const entry = (
106 issueId: string,
107 kind: "agent" | "check",
108 usd: number,
109 wallS: number,
110 waitS: number,
111 ): void => {
112 const end = Date.parse("2026-03-10T12:00:00.000Z");
113 const run: FinishedRun = {
114 id: `run-${++seq}`,
115 kind,
116 repoId,
117 repo: "ada/hello",
118 issueId,
119 issueNumber: null,
120 issueKind: null,
121 state: "ok",
122 createdAt: new Date(end - (wallS + waitS) * 1000).toISOString(),
123 startedAt: new Date(end - wallS * 1000).toISOString(),
124 finishedAt: new Date(end).toISOString(),
125 cpuS: null,
126 memGbS: null,
127 tokensIn: 0,
128 tokensOut: 0,
129 costUsd: usd,
130 };
131 const sealed = sealEntry(entryFor(run, { vcpuHour: 0, gbHour: 0 }, seq, "0".repeat(64)), () => "");
132 indexEntries(app.db, [sealed], new Map([[run.id, issueId]]));
133 };
134
135 beforeAll(async () => {
136 dataDir = await mkdtemp(join(tmpdir(), "forge-rollup-"));
137 app = createApp({ dataDir, port: 0 });
138 const http = forgeHttp(app);
139 fetch = (path, init) => http.handle(new Request(`http://localhost${path}`, init));
140 const signed = await fetch(`/signup`, {
141 method: "POST",
142 body: new URLSearchParams({
143 username: "ada",
144 email: "[email protected]",
145 password: "analytical-engine",
146 }),
147 redirect: "manual",
148 });
149 cookie = (signed.headers.get("set-cookie") ?? "").split(";")[0]!;
150 authorId = app.db
151 .query<{ id: string }, []>("SELECT id FROM user WHERE username = 'ada'")
152 .get()!.id;
153 // The board's forge line is the site admin's.
154 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(authorId);
155 const headers = { cookie, "content-type": "application/json" };
156 const make = async (name: string): Promise<string> =>
157 (
158 (await fetch(`/api/v1/repos`, {
159 method: "POST",
160 headers,
161 body: JSON.stringify({ name, visibility: "public" }),
162 }).then((r) => r.json())) as { id: string }
163 ).id;
164 repoId = await make("hello");
165 quietId = await make("quiet");
166 });
167
168 afterAll(async () => {
169 app.close();
170 await rm(dataDir, { recursive: true, force: true });
171 });
172
173 test("an issue's roll-up is its own entries plus its pulls'", () => {
174 const ask = issue(repoId, "make it cheaper");
175 // Twelve issues so a "#1x" body exists to be mistaken for "#1".
176 for (let i = 0; i < 12; i++) issue(repoId, `filler ${i}`);
177 const merged = pull(repoId, `Closes #${ask.number}`, "2026-03-10T10:00:00.000Z");
178 const dropped = pull(repoId, `Fixes #${ask.number}, a first try`, null);
179 const other = pull(repoId, `Closes #1${ask.number}`, null);
180 expect(pullsClosing(app.db, repoId, ask.number).map((p) => p.id).sort()).toEqual(
181 [merged.id, dropped.id].sort(),
182 );
183
184 entry(ask.id, "agent", 0.1, 600, 0); // own: $0.10, 10 min agent
185 entry(merged.id, "agent", 0.25, 1200, 30); // pull: $0.25, 20 min agent, 30 s wait
186 entry(merged.id, "check", 0, 300, 90); // pull: 5 lane-min, 90 s wait
187 entry(dropped.id, "agent", 0.05, 60, 0); // the abandoned pull still cost
188 entry(other.id, "agent", 9, 60, 0); // not this issue's
189
190 const ids = [ask.id, ...pullsClosing(app.db, repoId, ask.number).map((p) => p.id)];
191 const r = costOf(app.db, ids);
192 const own = issueCost(app.db, ask.id);
193 const pulls = [merged.id, dropped.id].map((id) => issueCost(app.db, id));
194 // By hand: 0.10 + 0.25 + 0 + 0.05 = 0.40; 4 runs; waits 30 + 90 = 120 s;
195 // lane 300 s (the check); agent 600 + 1200 + 60 = 1860 s.
196 expect(r.runs).toBe(4);
197 expect(r.usdTokens).toBeCloseTo(0.4, 9);
198 expect(r.waitS).toBeCloseTo(120, 9);
199 expect(r.laneS).toBeCloseTo(300, 9);
200 expect(r.agentS).toBeCloseTo(1860, 9);
201 expect(r.runs).toBe(own.runs + pulls[0]!.runs + pulls[1]!.runs);
202 expect(r.usdTokens).toBeCloseTo(
203 own.usdTokens + pulls[0]!.usdTokens + pulls[1]!.usdTokens,
204 9,
205 );
206 // An id named twice is read once.
207 expect(costOf(app.db, [ask.id, ask.id]).runs).toBe(1);
208 expect(costOf(app.db, []).runs).toBe(0);
209 });
210
211 test("the day's median ask→live equals the hand calculation", () => {
212 const day = "2026-03-20";
213 const at = (hhmm: string, d = day): string => `${d}T${hhmm}:00.000Z`;
214 // Four issues that go live on the day, at 1 h, 3 h, 5 h and 10 h.
215 const a = issue(repoId, "a", { at: at("08:00") });
216 const b = issue(repoId, "b", { at: at("06:00") });
217 const c = issue(repoId, "c", { at: at("04:00") });
218 const d = issue(repoId, "d", { at: "2026-03-19T23:00:00.000Z" });
219 pull(repoId, `Closes #${a.number}`, at("08:30"));
220 pull(repoId, `Fixes #${b.number} and closes #${c.number}`, at("08:40"));
221 pull(repoId, `Resolves #${d.number}`, at("08:50"));
222 // A deploy queued before any merge, serving late: carries none of them.
223 deploy(repoId, at("08:20"), at("11:00"));
224 deploy(repoId, at("08:45"), at("09:00")); // a, b, c live at 09:00
225 // d: a second pull for it merged first, but its deploy served later.
226 pull(repoId, `Closes #${d.number}`, at("08:55"));
227 deploy(repoId, at("08:55"), at("09:00"));
228 // e went live yesterday: not the day's.
229 const e = issue(repoId, "e", { at: "2026-03-19T01:00:00.000Z" });
230 pull(repoId, `Closes #${e.number}`, "2026-03-19T02:00:00.000Z");
231 deploy(repoId, "2026-03-19T02:00:00.000Z", "2026-03-19T02:10:00.000Z");
232 // f's repository never deploys: never live.
233 const f = issue(quietId, "f", { at: at("01:00") });
234 pull(quietId, `Closes #${f.number}`, at("02:00"));
235 // a deploy to a preview is not production.
236 const g = issue(repoId, "g", { at: at("12:00") });
237 pull(repoId, `Closes #${g.number}`, at("13:00"));
238 const preview = createRun(app.db, { repoId, kind: "deploy", env: "pull-9" });
239 app.db
240 .query("UPDATE run SET created_at = ?2, serving_at = ?3 WHERE id = ?1")
241 .run(preview.id, at("13:05"), at("13:10"));
242
243 // Opened → 09:00: a 1 h, b 3 h, c 5 h, d 10 h (23:00 the day before).
244 // Median of {1, 3, 5, 10} h = (3 + 5) / 2 = 4 h = 14 400 s.
245 expect(dayAskLive(app.db, day)).toEqual({ medianS: 4 * H, n: 4 });
246 // On the 19th, e (1 h 10 min) and the first test's issue, whose March
247 // pull that deploy carried — but it was opened after, so it is left out.
248 expect(dayAskLive(app.db, "2026-03-19")).toEqual({ medianS: 1 * H + 600, n: 1 });
249 expect(dayAskLive(app.db, "2026-03-21")).toEqual({ medianS: null, n: 0 });
250
251 const opened = { createdAt: at("04:00") };
252 expect(issueAskLive(app.db, opened, [at("08:40")], repoId)).toBe(5 * H);
253 expect(issueAskLive(app.db, opened, [], repoId)).toBeNull();
254 });
255
256 test("the issue's page sums its pulls and says its ask→live", async () => {
257 const now = Date.now();
258 const ago = (s: number): string => new Date(now - s * 1000).toISOString();
259 const ask = issue(repoId, "ship the thing", { at: ago(3 * H) });
260 const p = pull(repoId, `Closes #${ask.number}`, ago(600));
261 deploy(repoId, ago(300), ago(1));
262 entry(ask.id, "agent", 0.5, 60, 0);
263 entry(p.id, "agent", 0.25, 60, 0);
264 const page = await fetch(`/ada/hello/issues/${ask.number}`, {
265 headers: { cookie },
266 }).then((r) => r.text());
267 const line = /id="ledger-cost">([^<]*)</.exec(page)?.[1] ?? "";
268 expect(line).toStartWith("cost: $0.75 tokens");
269 expect(line).toContain("with 1 pull");
270 expect(line).toContain("ask→live 3.0 h");
271 const anon = await fetch(`/ada/hello/issues/${ask.number}`).then((r) => r.text());
272 expect(anon).not.toContain(`id="ledger-cost"`);
273 });
274
275 test("the board's forge line shows the day's median ask→live", async () => {
276 const page = await fetch(`/board`, { headers: { cookie } }).then((r) => r.text());
277 const line = /id="day-cost">([^<]*)</.exec(page)?.[1] ?? "";
278 // The one issue live today is the page test's: 3 h.
279 expect(line).toContain("median ask→live 3.0 h (1 live)");
280 });
281 });
test/mcp.test.ts +1
@@ -189,6 +189,7 @@ describe("the forge over MCP", () => {
189189 "returns",
190190 "spend",
191191 "usage",
192 "cost",
192193 "link",
193194 "unlink",
194195 "attach_look",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs