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

An open chapter's page says what it has cost so far and what a chapter of its pace costs #13280

Merged opened this

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

Merged

scout/forge:scout/13261-an-open-chapter-s-page-says-what-it-has → main 3 commits fork 2 threads · 2 unresolved

  • Merged. scout/13261-an-open-chapter-s-page-says-what-it-has was merged into main as 2e0097b.

Review

Sign in to review this change.
6 files changed +167 −22
docs/features/chapters.md +6
@@ -24,3 +24,9 @@ A closed chapter's list is frozen, so `itemsOf` keeps it in process memory (at m
2424 ## The first chapter: v1.0.0
2525
2626 Drafting a chapter named `v1.0.0` records the v1 list's issues in it (the issue of every probe in `scripts/v1-proven.ts`, those that exist in the repository). Closing it (Ship it or Close) runs those read-only probes against the forge's public origin and is refused, naming each probe that does not pass, until every one passes; `unproven` is not a pass. The close tags the default branch's tip and nothing more: a person cuts the release with `scripts/cut-release.ts`.
27
28 ## What it has cost (#13261)
29
30 An open chapter's page says what it has cost so far and what a chapter of its pace costs, in a line under the progress sentence (`costSentence`, `src/core/chapters.ts`). The terminal prints the same sentence after the progress sentence on the chapter's list and on each row of the chapters screen; the MCP `repo` tool's `progress` carries it too. A closed chapter keeps its finished page, which already says its cost.
31
32 Try it: open `/<owner>/<name>/chapters/<open chapter>` and read the line under the progress sentence.
src/core/chapters.ts +26 −4
@@ -183,7 +183,10 @@ export function chapterOfIssue(db: Database, issueId: string): Chapter | undefin
183183 return row === null ? undefined : toChapter(row);
184184 }
185185
186 /** Put an issue in a chapter (moving it from another that is not closed). Closed chapters hold their list. */
186 /**
187 * Put an issue in a chapter (moving it from another that is not closed). Closed chapters hold their
188 * list.
189 */
187190 export function putIssue(db: Database, chapter: Chapter, issueId: string, byId: string | undefined): Result<void, ChapterError> {
188191 if (chapter.state === "closed") return err("closed");
189192 const from = chapterOfIssue(db, issueId);
@@ -346,6 +349,25 @@ export function progressOf(chapter: Chapter, items: readonly Item[], now: Date):
346349 export const progressSentence = (p: Progress): string =>
347350 `${p.done} of ${p.total} done${p.finishesOn === null ? "" : `; at this pace it finishes ${p.finishesOn}`}.`;
348351
352 /**
353 * What the chapter's issues have cost so far (their runs and checks, and their pulls'), in dollars.
354 */
355 export const spentOf = (items: readonly Item[]): number => round4(items.reduce((sum, i) => sum + i.costUsd, 0));
356
357 const dollars = (n: number): string => `$${n.toFixed(2)}`;
358
359 /**
360 * The line under the progress sentence: what the chapter has cost, and once something is done, what
361 * a chapter of this pace costs (spent so far per item done, over the whole list).
362 */
363 export function costSentence(items: readonly Item[]): string {
364 const spent = spentOf(items);
365 const done = items.filter((i) => i.status === "done").length;
366 const base = `${dollars(spent)} spent so far`;
367 if (done === 0 || done >= items.length) return `${base}.`;
368 return `${base}; at this pace the chapter costs about ${dollars((spent / done) * items.length)}.`;
369 }
370
349371 // ---- the crew's gate ----
350372
351373 /** Whether the repository has closed a chapter and opened none since: the crew rests. */
@@ -384,9 +406,9 @@ export function chapterHold(db: Database, repoId: string, issue: Pick<Issue, "id
384406 }
385407
386408 /**
387 * Where an issue the planner opens lands while a chapter is open: a defect of a chapter item joins the
388 * chapter; anything else waits in the next chapter. Undefined when no chapter is open (nothing to do)
389 * or no later chapter is drafted (the caller sends it to Later).
409 * Where an issue the planner opens lands while a chapter is open: a defect of a chapter item joins
410 * the chapter; anything else waits in the next chapter. Undefined when no chapter is open (nothing
411 * to do) or no later chapter is drafted (the caller sends it to Later).
390412 */
391413 export function placeNewIssue(db: Database, repoId: string, issueId: string, body: string): { chapter: Chapter; scope: "defect" | "next" } | "later" | undefined {
392414 const open = openChapterOf(db, repoId);
src/http/mcp/tools/repo.ts +2 −2
@@ -4,7 +4,7 @@ import { audienceFor } from "../../../core/audience.ts";
44 import { upstreamFacts } from "../../../actions/upstream_follow.ts";
55 import { creditFacts } from "../../../actions/credit_facts.ts";
66 import { type ChapterActError, close, fill, open, preview, refusalWords, type Refused } from "../../../actions/chapters.ts";
7 import { getChapter, itemsOf, listChapters, progressOf, progressSentence } from "../../../core/chapters.ts";
7 import { costSentence, getChapter, itemsOf, spentOf, listChapters, progressOf, progressSentence } from "../../../core/chapters.ts";
88 import { err } from "../../../kernel/result.ts";
99 import { good, str, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
1010
@@ -56,7 +56,7 @@ export const tool: Tool = {
5656 const items = itemsOf(ctx.app.db, c);
5757 const p = progressOf(c, items, now);
5858 return good({
59 name: c.name, means: c.means, state: c.state, progress: progressSentence(p), finishesOn: p.finishesOn,
59 name: c.name, means: c.means, state: c.state, progress: progressSentence(p), cost: costSentence(items), spentUsd: spentOf(items), finishesOn: p.finishesOn,

The new cost and spentUsd fields have no test. Add one in the MCP chapter test asserting spentUsd equals the ledger sum.

6060 items: items.map((i) => ({ number: i.number, title: i.title, status: i.status, doneAt: i.doneAt })),
6161 });
6262 }
src/tui/screens/chapters.ts +13 −12
@@ -1,16 +1,16 @@
11 /**
2 * An app's chapters, in the terminal (#11603): the page's list (`web/pages/chapters.ts`) from the same
3 * acts (`actions/chapters.ts`), so the same owner-only gate applies: anyone who can read the repository
4 * sees the chapters, only a person who administers it drafts, opens, fills, ships or patches. `n`
5 * drafts, `c` closes the one under the cursor when nothing is in its way and `u` takes a close back
6 * within a minute (#12288), `o` opens the one under the cursor, `s` ships it, `p` opens a patch chapter for a closed
7 * one, `enter` shows its list, where `a` adds an issue by number and `x` takes the one under the
8 * cursor out. Each act is an event on the bus, so an open web page sees it, and this screen follows
9 * a change made there.
2 * An app's chapters, in the terminal (#11603): the page's list (`web/pages/chapters.ts`) from the
3 * same acts (`actions/chapters.ts`), so the same owner-only gate applies: anyone who can read the
4 * repository sees the chapters, only a person who administers it drafts, opens, fills, ships or
5 * patches. `n` drafts, `c` closes the one under the cursor when nothing is in its way and `u` takes
6 * a close back within a minute (#12288), `o` opens the one under the cursor, `s` ships it, `p`
7 * opens a patch chapter for a closed one, `enter` shows its list, where `a` adds an issue by number
8 * and `x` takes the one under the cursor out. Each act is an event on the bus, so an open web page
9 * sees it, and this screen follows a change made there.
1010 */
1111
1212 import { CHAPTER_WORDS, close, draft, fill, open, patch, reopen, refusalWords, undoableClose } from "../../actions/chapters.ts";
13 import { getChapter, itemsOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
13 import { costSentence, getChapter, itemsOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
1414 import { canAdmin, type Repo } from "../../core/repos.ts";
1515 import type { Ctx, Screen } from "../app/app.ts";
1616 import type { Command } from "../app/palette.ts";
@@ -25,9 +25,10 @@ const isChapterEvent = (kind: string): boolean => kind.startsWith("chapter.") ||
2525
2626 /** The words under a chapter's name: what done means, then how far it is. */
2727 function chapterRow(f: Session, repo: Repo, c: Chapter): ListRow {
28 const p = progressOf(c, itemsOf(f.app.db, c), new Date());
28 const items = itemsOf(f.app.db, c);
29 const p = progressOf(c, items, new Date());
2930 const undo = c.state === "closed" && undoableClose(f.app, repo, c) ? " Closed just now: u undoes it." : "";

New behaviour (cost sentence on the row, and on the chapter screen header) has no test; it would stay green if removed. Add a TUI test asserting the row text includes the cost sentence.

30 const progress = (c.state === "closed" ? "finished" : progressSentence(p)) + undo;
31 const progress = (c.state === "closed" ? "finished" : `${progressSentence(p)} ${costSentence(items)}`) + undo;
3132 return { title: `${c.name} — ${c.state}`, note: c.means === "" ? progress : `${c.means} ${progress}` };
3233 }
3334
@@ -76,7 +77,7 @@ export function chapterScreen(f: Session, ctx: Ctx, repo: Repo, name: string): S
7677 head!.x,
7778 head!.y,
7879 truncate(
79 chapter === undefined ? "No such chapter." : `${chapter.state}: ${progressSentence(p!)}`,
80 chapter === undefined ? "No such chapter." : `${chapter.state}: ${progressSentence(p!)} ${costSentence(all)}`,
8081 head!.w,
8182 ),
8283 style(c.mutedFg, c.bg),
src/web/pages/chapters.ts +5 −4
@@ -1,13 +1,13 @@
11 /**
22 * Chapters (#11603): `/:owner/:name/chapters` lists the open chapter, the drafts after it and the
33 * closed ones; `/:owner/:name/chapters/:chapter` is the list being crossed off — done items struck
4 * through with the day they went live, what is building, what is left, the date at the current pace —
5 * or, once closed, the one page that says it is finished. Server-rendered, no script; every change
6 * is a same-origin POST by a person who administers the repository.
4 * through with the day they went live, what is building, what is left, the date at the current pace
5 * — or, once closed, the one page that says it is finished. Server-rendered, no script; every
6 * change is a same-origin POST by a person who administers the repository.
77 */
88
99 import { CHAPTER_WORDS, close, draft, fill, open, patch, reopen, refusalWords } from "../../actions/chapters.ts";
10 import { getChapter, itemsOf, nextChapterOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
10 import { costSentence, getChapter, itemsOf, nextChapterOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
1111 import { canAdmin, type Repo } from "../../core/repos.ts";
1212 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1313 import type { Ctx } from "../../http/context.ts";
@@ -117,6 +117,7 @@ export function chapterPage(ctx: Ctx): Response {
117117 const done = items.filter((i) => i.status === "done");
118118 main = html`<p>${c.means}</p>
119119 <p data-progress>${progressSentence(p)}</p>
120 <p data-cost>${costSentence(items)}</p>
120121 ${items.length === 0 ? html`<p>No issues in this chapter yet.</p>` : null}
121122 <ul class="list setting-list">${[...done, ...building, ...left].map((i) => itemRow(repo, i, may, c))}</ul>
122123 ${may
test/chapters-cost.test.ts added +115
@@ -0,0 +1,115 @@
1 /** An open chapter says what its issues have cost (#13261): the figure is the run ledger's sum. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { newApp } from "../src/actions/apps.ts";
7 import { createApp, type App } from "../src/app.ts";
8 import { costSentence, draftChapter, getChapter, itemsOf, putIssue, spentOf, startChapter } from "../src/core/chapters.ts";
9 import { createIssue } from "../src/core/issues.ts";
10 import { getRepo, type Repo } from "../src/core/repos.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { chapterScreen, chaptersScreen } from "../src/tui/screens/chapters.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { settleApp } from "./helpers/tui.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 describe("an open chapter's cost", () => {
23 let dataDir = "";
24 let app: App;
25 let servers: Servers;
26 let repo: Repo;
27 let token = "";
28
29 beforeAll(async () => {
30 dataDir = await mkdtemp(join(tmpdir(), "forge-chapters-cost-"));
31 app = createApp({ dataDir, port: 0, host: "forge.test", url: "https://forge.test" });
32 const made = await createUser(app.db, { username: "alice", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, adminIfFirst: true });
33 if (!made.ok) throw new Error(String(made.error));
34 const owner = made.value;
35 const created = await newApp(app, owner, { name: "shop", description: "Words", visibility: "public" });
36 if (!created.ok) throw new Error(String(created.error));
37 repo = getRepo(app.db, "alice", "shop")!;
38 const chapter = draftChapter(app.db, repo.id, { name: "v2", means: "Two" }, owner.id);
39 if (!chapter.ok) throw new Error(chapter.error);
40 const ids: string[] = [];
41 for (const cost of [[0.5, 0.25], [1.1], []]) {
42 const issue = createIssue(app.db, { repoId: repo.id, authorId: owner.id, title: `item ${ids.length}` });
43 if (!issue.ok) throw new Error(issue.error);
44 ids.push(issue.value.id);
45 putIssue(app.db, chapter.value, issue.value.id, owner.id);
46 for (const usd of cost)
47 app.db.query(`INSERT INTO run (id, repo_id, kind, issue_id, cost_usd) VALUES (?1, ?2, 'agent', ?3, ?4)`).run(`r${ids.length}-${usd}`, repo.id, issue.value.id, usd);
48 }
49 // A run on an issue outside the chapter is not its cost.
50 const other = createIssue(app.db, { repoId: repo.id, authorId: owner.id, title: "elsewhere" });
51 if (!other.ok) throw new Error(other.error);
52 app.db.query(`INSERT INTO run (id, repo_id, kind, issue_id, cost_usd) VALUES ('rx', ?1, 'agent', ?2, 9)`).run(repo.id, other.value.id);
53 startChapter(app.db, chapter.value, new Date());
54 token = createToken(app.db, owner.id, "t", "rw").token;
55 servers = await serve(app);
56 }, 30_000);
57
58 afterAll(async () => {
59 servers.stop();
60 app.close();
61 await rm(dataDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
62 });
63
64 test("the figure equals the ledger sum for the chapter's issues, and no more", () => {
65 const chapter = getChapter(app.db, repo.id, "v2")!;
66 const c = { id: chapter.id };
67 const sum = app.db
68 .query<{ s: number }, [string]>(
69 `SELECT SUM(run.cost_usd) AS s FROM run JOIN chapter_item ci ON ci.issue_id = run.issue_id WHERE ci.chapter_id = ?1`,
70 )
71 .get(c.id)!.s;
72 expect(sum).toBe(1.85);
73 const items = itemsOf(app.db, chapter);
74 expect(spentOf(items)).toBe(1.85);
75 expect(costSentence(items)).toBe("$1.85 spent so far.");
76 });
77
78 test("the page shows it under the progress sentence", async () => {
79 const res = await fetch(`${servers.url}/alice/shop/chapters/v2`, { headers: { authorization: `Bearer ${token}` } });
80 const text = await res.text();
81 expect(text).toMatch(/data-progress[^]*data-cost>\$1\.85 spent so far\./);
82 });
83
84 test("a pace is projected once something is done", () => {
85 const item = (status: "done" | "left", costUsd: number) => ({ issueId: "x", number: 1, title: "t", status, doneAt: null, pull: null, builder: null, costUsd });
86 expect(costSentence([item("done", 2), item("left", 0)])).toBe("$2.00 spent so far; at this pace the chapter costs about $4.00.");
87 });
88
89 test("the terminal's chapter list row and chapter screen header carry it", async () => {
90 const guest = { sshUsername: "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test" };
91 const screens = [chaptersScreen, (f: any, c: any, r: Repo) => chapterScreen(f, c, r, "v2")];
92 for (const make of screens) {
93 const terminal = headlessTerminal(220, 20);
94 const { app: tui, session } = createForgeApp(app, guest, { terminal, exitHooks: false });
95 tui.start();
96 tui.ctx.push(make(session, tui.ctx, repo));
97 await settleApp(tui);
98 const text = tui.screen.toText();
99 tui.stop?.();
100 expect(text).toContain("$1.85 spent so far");
101 }
102 });
103
104 test("the repo tool's chapter view returns the sentence and the sum", async () => {
105 const res = await fetch(`${servers.url}/mcp`, {
106 method: "POST",
107 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
108 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "repo", arguments: { repo: "alice/shop", view: "chapters", chapter: "v2" } } }),
109 });
110 const body: any = await res.json();
111 const value = JSON.parse(body.result.content[0].text);
112 expect(value.spentUsd).toBe(1.85);
113 expect(value.cost).toBe("$1.85 spent so far.");
114 });
115 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs