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

A wave page says how long the wave took, from its first issue opened to its last pull landed #14162

Merged opened this

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

Merged

scout/forge:scout/14128-a-wave-page-says-how-long-the-wave-took → main 6 commits fork 2 threads · 2 unresolved

  • Merged. scout/14128-a-wave-page-says-how-long-the-wave-took was merged into main as b488080.

Review

Sign in to review this change.
8 files changed +221 −4
docs/features/README.md +1
@@ -191,6 +191,7 @@ Read with the guide page [Tell the crew](../guide-tell-the-crew.md).
191191 - [How close a wave is to done](wave-landed.md)
192192 - [What a repository with no waves says and offers](wave-empty.md)
193193 - [Reading a wave's pulls, newest landed first, with who merged each](wave-pulls-order.md)
194 - [How long a wave took, or has been open](wave-duration.md)
194195 - [What became of the first ask](ask-status.md)
195196 - [When a setting or a permission stands in the way](blocked-by.md)
196197 - [The map's growth line](map-growth.md)
docs/features/wave-duration.md added +9
@@ -0,0 +1,9 @@
1 # The wave duration
2
3 A wave's page, the terminal's wave screen and the MCP say how long the wave took: `took 3 days` once every change has landed, `open for 3 days` while one has not.
4
5 - **From** the earliest opening of an issue of the wave: its pulls' own, and the issues they close.
6 - **To** the last pull landed. Whole days, rounded down; under one day says `less than a day`.
7 - Only the pulls the reader may see are counted, as in the size words beside it. A wave naming no visible change says nothing.
8
9 All three doors build the words with `waveDuration` in `src/story/wave_duration.ts`. It looks the repository up once per owner and name and reads issue times in two queries per repository, so a large wave stays fast.
src/http/mcp/tools/waves.ts +5 −1
@@ -3,6 +3,7 @@ import { VERSION as WAVE_VERSION } from "../../../story/wave.ts";
33 import { repoDir } from "../../../git/repos.ts";
44 import { movedForViewer, waveProgress } from "../../../story/wave_moved.ts";
55 import { carriedPulls } from "../../../story/wave_pulls.ts";
6 import { waveDuration } from "../../../story/wave_duration.ts";
67 import { landedSentence } from "../../../story/words.ts";
78 import { planNow } from "../../../story/wave_plan.ts";
89 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
@@ -43,14 +44,17 @@ export const tool: Tool = {
4344 const progress = waveProgress(
4445 movedForViewer({ db: ctx.app.db, repo, refs: pullRefs(w), viewer: user, plan: () => planNow(ctx.app.db, repo, new Date()) }),
4546 );
47 const carried = carriedPulls(ctx.app.db, pullRefs(w), user);
48 const took = waveDuration(ctx.app.db, carried, new Date());
4649 return good({
4750 repo: repo.ownerName + "/" + repo.name,
4851 wave: {
4952 version: w.version,
5053 date: w.date,
5154 headline: w.headline,
52 landed: landedSentence(carriedPulls(ctx.app.db, pullRefs(w), user)),
55 landed: landedSentence(carried),
5356 ...(progress === "" ? {} : { progress }),
57 ...(took === "" ? {} : { took }),
5458 highlights: w.highlights,
5559 pulls: w.pulls.flatMap((p) => {
5660 const n = /\/pulls\/(\d+)\/?$/.exec(p.url);
src/story/wave_duration.ts added +79
@@ -0,0 +1,79 @@
1 /**

Both doors: a wave is readable in the terminal (src/tui/screens/waves.ts) but this duration is not. Add it there using waveDuration, gated as the page is (carried pulls are already viewer-filtered), and write docs/features/wave-duration.md. The "No door" line is not a reason to skip it.

2 * How long a wave took, in plain words: from the first issue opened to the last pull landed, or,
3 * while it is still open, how long it has been open. One sentence for the page and the MCP.
4 */
5
6 import type { Database } from "bun:sqlite";
7 import { closesFromBody } from "../core/pulls.ts";
8 import { getRepo } from "../core/repos.ts";
9 import type { CarriedPull } from "./wave_pulls.ts";
10
11 const DAY = 86_400_000;
12
13 /** "less than a day", "1 day", "3 days": whole days, rounded down. */
14 export function daysWords(ms: number): string {
15 const days = Math.floor(Math.max(ms, 0) / DAY);
16 return days < 1 ? "less than a day" : days === 1 ? "1 day" : `${days} days`;
17 }
18
19 /**
20 * "took 3 days" when every change has landed, else "open for 3 days"; empty when there is no start
21 * to count from (a wave naming no change the viewer can see).
22 */
23 export function durationWords(startedAt: string | null, pulls: readonly { mergedAt: string | null }[], now: Date): string {
24 if (startedAt === null || pulls.length === 0) return "";
25 const start = Date.parse(startedAt);
26 if (Number.isNaN(start)) return "";
27 const landed = pulls.flatMap((p) => (p.mergedAt === null ? [] : [Date.parse(p.mergedAt)])).filter((t) => !Number.isNaN(t));
28 if (landed.length < pulls.length) return `open for ${daysWords(now.getTime() - start)}`;
29 return `took ${daysWords(Math.max(...landed) - start)}`;
30 }
31
32 /**
33 * The earliest moment an issue of the wave was opened: its pulls' own, and the issues they close.
34 * One repo lookup per owner and name, two queries per repo however many pulls.
35 */
outdated

waveStart does getRepo plus one or two queries per pull, and one query per closed issue: an N+1 on a page that must answer in under 50 ms. Look the repo up once per owner and name, and fetch the issue timestamps in one query with IN (...). Also at < first compares ISO strings; parse with Date.parse so mixed formats cannot misorder.

36 export function waveStart(db: Database, pulls: readonly CarriedPull[]): string | null {
37 let first: string | null = null;
38 let firstMs = Infinity;
39 const see = (at: string | null | undefined): void => {
40 if (at === null || at === undefined) return;
41 const ms = Date.parse(at);
42 if (!Number.isNaN(ms) && ms < firstMs) {
43 firstMs = ms;
44 first = at;
45 }
46 };
47 const byRepo = new Map<string, { owner: string; name: string; numbers: number[] }>();
48 for (const p of pulls) {
49 const key = `${p.owner}/${p.name}`;
50 const group = byRepo.get(key) ?? { owner: p.owner, name: p.name, numbers: [] };
51 group.numbers.push(p.number);
52 byRepo.set(key, group);
53 }
54 for (const { owner, name, numbers } of byRepo.values()) {
55 const repo = getRepo(db, owner, name);
56 if (repo === undefined) continue;
57 const rows = db
58 .query<{ created_at: string; body: string | null }, (string | number)[]>(
59 `SELECT created_at, body FROM issue WHERE repo_id = ?1 AND number IN (${numbers.map((_, i) => `?${i + 2}`).join(",")})`,
60 )
61 .all(repo.id, ...numbers);
62 const closed = new Set<number>();
63 for (const row of rows) {
64 see(row.created_at);
65 for (const n of closesFromBody(row.body ?? "")) closed.add(n);
66 }
67 const ns = [...closed];
68 if (ns.length === 0) continue;
69 for (const row of db
70 .query<{ created_at: string }, (string | number)[]>(
71 `SELECT created_at FROM issue WHERE repo_id = ?1 AND number IN (${ns.map((_, i) => `?${i + 2}`).join(",")})`,
72 )
73 .all(repo.id, ...ns)) see(row.created_at);
74 }
75 return first;
76 }
77
78 /** The wave's duration sentence, from the pulls the viewer may see. */
79 export const waveDuration = (db: Database, pulls: readonly CarriedPull[], now: Date): string => durationWords(waveStart(db, pulls), pulls, now);
src/tui/screens/waves.ts +7 −2
@@ -10,6 +10,7 @@ import { canRead, getRepo } from "../../core/repos.ts";
1010 import { mayDirectCrew } from "../../crew/direct.ts";
1111 import { nearMilestones, standingLine } from "../../web/pages/milestones_near.ts";
1212 import { VERSION } from "../../story/wave.ts";
13 import { waveDuration } from "../../story/wave_duration.ts";
1314 import { movedWithPulls, shippedOf, shippedWords, waveProgress, type MovedMilestone } from "../../story/wave_moved.ts";
1415 import { milestonePath, planNow } from "../../story/wave_plan.ts";
1516 import { repoBase } from "../../web/chrome.ts";
@@ -66,6 +67,8 @@ export function waveLines(
6667 picked: number | null = null,
6768 /** The standing line, as the page's trail says it; none when empty. */
6869 standing = "",
70 /** How long the wave took, as the page says it; none when empty. */
71 duration = "",
6972 ): string[] {
7073 if (!entry.ok) return [plain(entry.file), "", `Not a wave: ${plain(entry.reason)}`];
7174 const w = entry.wave;
@@ -74,6 +77,7 @@ export function waveLines(
7477 plain(waveSentence(pulls.filter((p) => p.mergedAt !== null).map((p) => p.title))),
7578 // Sized over `pulls`, the ones this viewer may see, as the page's header is.
7679 `${plain(w.version)} ${plain(w.date)} ${sizeWords(waveSize(pulls))} ${landedSentence(pulls)}${standing === "" ? "" : ` ${plain(standing)}`}`,
80 ...(duration === "" ? [] : [plain(duration)]),
7781 ...(moved.length === 0 ? [] : [plain(waveProgress(moved))]),
7882 "",
7983 "Highlights",
@@ -111,11 +115,12 @@ function waveScreen(
111115 moved: MovedLine[],
112116 src: RepoSource,
113117 standing = "",
118 duration = "",
114119 ): Screen {
115120 const scroll = new Scroll();
116121 let picked = 0;
117122 /** Where the wave's pulls start in the text, so the pick is scrolled into view. */
118 const linesFor = (): string[] => waveLines(entry, pulls, moved, pulls.length === 0 ? null : picked, standing);
123 const linesFor = (): string[] => waveLines(entry, pulls, moved, pulls.length === 0 ? null : picked, standing, duration);
119124 const open = (): void => {
120125 const p = pulls[picked];
121126 if (p === undefined) return;
@@ -210,7 +215,7 @@ export function wavesScreen(f: Session, ctx: Ctx, src: RepoSource): Screen {
210215 nearMilestones(f.app, `${repo.ownerName}/${repo.name}`, f.user)?.near ?? [],
211216 )
212217 : "";
213 ctx.push(waveScreen(f, ctx, one, pulls, moved, src, standing));
218 ctx.push(waveScreen(f, ctx, one, pulls, moved, src, standing, one.ok ? waveDuration(f.db, pulls, new Date()) : ""));
214219 });
215220 };
216221
src/web/pages/waves.ts +3 −1
@@ -17,6 +17,7 @@ import { repoDir } from "../../git/repos.ts";
1717 import type { Ctx } from "../../http/context.ts";
1818 import { VERSION, type Wave } from "../../story/wave.ts";
1919 import { movedWithPulls, type MovedMilestone, shippedOf, shippedWords, waveProgress, widestMoved } from "../../story/wave_moved.ts";
20 import { waveDuration } from "../../story/wave_duration.ts";
2021 import { carriedPulls, inLandingOrder, pullPath } from "../../story/wave_pulls.ts";
2122 import { fromWave, pullRefs, readWave, readWaves, sizeWords, waveSize } from "../../story/waves.ts";
2223 import { FIRST_WAVE_BUTTON, FIRST_WAVE_TELL, NO_WAVES, landedSentence, waveSentence } from "../../story/words.ts";
@@ -241,10 +242,11 @@ export async function wavePage(ctx: Ctx): Promise<Response> {
241242 * The bar under the version line, named differently from the sentence beside it; none when empty.
242243 */
243244 const landed = carried.length === 0 ? "" : progress(carried.filter((p) => p.mergedAt !== null).length, carried.length, "Share landed");
245 const duration = entry.ok ? waveDuration(ctx.app.db, carried, new Date()) : "";
244246 const content = entry.ok
245247 ? html`<h1>${entry.wave.headline}</h1>
246248 <p data-wave-sentence>${waveSentence(carried.filter((p) => p.mergedAt !== null).map((p) => p.title))}</p>
247 <p class="muted">${entry.wave.version} · ${entry.wave.date} · <span data-wave-size>${sizeWords(waveSize(carried))}</span> · <span data-wave-landed>${landedSentence(carried)}</span> · <span data-wave-standing>${standing}</span></p>
249 <p class="muted">${entry.wave.version} · ${entry.wave.date} · <span data-wave-size>${sizeWords(waveSize(carried))}</span> · <span data-wave-landed>${landedSentence(carried)}</span>${duration === "" ? "" : html` · <span data-wave-duration>${duration}</span>`} · <span data-wave-standing>${standing}</span></p>
248250 ${landed}
249251 ${waveProgressRow(moved)}
250252 <h2>Highlights</h2>
test/tui-waves.test.ts +6
@@ -392,3 +392,9 @@ describe("a wave's pulls in the terminal", () => {
392392 expect(lines.join("\n")).toContain("merged by ada 2026-01-02");
393393 });
394394 });
395
396 test("the wave screen says how long the wave took, on the line after the trail (#14128)", () => {
397 const entry = { ok: true, file: "v1.md", wave: { version: "v1", date: "2026-01-01", headline: "H", highlights: [] } } as unknown as Parameters<typeof waveLines>[0];
398 expect(waveLines(entry, [], [], null, "", "took 3 days")).toContain("took 3 days");
399 expect(waveLines(entry, [])).not.toContain("took 3 days");
400 });
test/wave-duration.test.ts added +111
@@ -0,0 +1,111 @@
1 /**
2 * A wave says how long it took, or how long it has been open: same words on the page and in the MCP
3 * (#14128).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { createSession } from "../src/core/sessions.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { daysWords, durationWords } from "../src/story/wave_duration.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17 import { mergedPull, waveNaming } from "./helpers/wave-pulls.ts";
18
19 quietLogs();
20
21 test("the words: days rounded down, took when all landed, open for otherwise", () => {
22 const now = new Date("2026-03-10T00:00:00.000Z");
23 expect(daysWords(3.9 * 86_400_000)).toBe("3 days");
24 expect(daysWords(86_400_000)).toBe("1 day");
25 expect(daysWords(3_600_000)).toBe("less than a day");
26 expect(durationWords("2026-03-01T09:00:00.000Z", [{ mergedAt: "2026-03-04T10:00:00.000Z" }], now)).toBe("took 3 days");
27 expect(durationWords("2026-03-01T00:00:00.000Z", [{ mergedAt: "2026-03-02T00:00:00.000Z" }, { mergedAt: null }], now)).toBe("open for 9 days");
28 expect(durationWords("2026-03-01T00:00:00.000Z", [{ mergedAt: null }], now)).toBe("open for 9 days");
29 expect(durationWords(null, [], now)).toBe("");
30 });
31
32 let dataDir = "";
33 let app: App;
34 let servers: Servers;
35 let cookie = "";
36 let token = "";
37
38 const day = (n: number): string => new Date(Date.now() - n * 86_400_000).toISOString();
39
40 beforeAll(async () => {
41 dataDir = await mkdtemp(join(tmpdir(), "forge-wave-duration-"));
42 app = createApp({ dataDir, port: 0 });
43 servers = await serve(app);
44 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
45 if (!u.ok) throw new Error(String(u.error));
46 cookie = `forge_session=${createSession(app.db, u.value.id).token}; forge_mode=dev`;
47 token = createToken(app.db, u.value.id, "ro", "ro").token;
48 const made = await createRepo(app, u.value, { name: "plan", visibility: "public" });
49 if (!made.ok) throw new Error(String(made.error));
50 const repo = made.value;
51 const init = await commitToBranch(app, u.value, repo, { message: "init", files: [{ path: "README.md", content: "hi\n" }] });
52 if (!init.ok) throw new Error(JSON.stringify(init.error));
53 const opened = (n: number, at: string) => app.db.query("UPDATE issue SET created_at = ? WHERE repo_id = ? AND number = ?").run(at, repo.id, n);
54 const merged = async (title: string, openedAt: string, mergedAt: string | null) => {
55 const n = await mergedPull(app, u.value, repo, title);
56 opened(n, openedAt);
57 app.db.query("UPDATE pull SET merged_at = ? WHERE issue_id = (SELECT id FROM issue WHERE repo_id = ? AND number = ?)").run(mergedAt, repo.id, n);
58 return n;
59 };
60 const closed = await merged("Closed work", "2026-03-01T09:00:00.000Z", "2026-03-04T10:00:00.000Z");
61 const half = await merged("Half work", day(5), day(4));
62 const waiting = await merged("Waiting work", day(5), null);
63 const never = await merged("Never work", day(2), null);
64 const ref = (number: number) => ({ owner: "alice", name: "plan", number });
65 const c = await commitToBranch(app, u.value, repo, {
66 message: "waves",
67 files: [
68 { path: "waves/0.1.0.md", content: waveNaming("0.1.0", [ref(closed)]) },
69 { path: "waves/0.2.0.md", content: waveNaming("0.2.0", [ref(half), ref(waiting)]) },
70 { path: "waves/0.3.0.md", content: waveNaming("0.3.0", [ref(never)]) },
71 { path: "waves/0.4.0.md", content: waveNaming("0.4.0", []) },
72 ],
73 });
74 if (!c.ok) throw new Error(JSON.stringify(c.error));
75 }, 60_000);
76
77 afterAll(async () => {
78 servers?.stop();
79 app?.close();
80 await rm(dataDir, { recursive: true, force: true });
81 });
82
83 const page = async (v: string) => (await fetch(`${servers.url}/alice/plan/waves/${v}`, { headers: { cookie } })).text();
84 const mcp = async (version: string) => {
85 const res = await fetch(`${servers.url}/mcp`, {
86 method: "POST",
87 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
88 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "waves", arguments: { repo: "alice/plan", version } } }),
89 });
90 return JSON.parse(((await res.json()) as any).result.content[0].text).wave;
91 };
92
93 test("a closed wave says it took 3 days, on the page and in the MCP", async () => {
94 expect(await page("0.1.0")).toContain("<span data-wave-duration>took 3 days</span>");
95 expect((await mcp("0.1.0")).took).toBe("took 3 days");
96 });
97
98 test("an open wave says open for N days, counted to now", async () => {
99 expect(await page("0.2.0")).toContain("<span data-wave-duration>open for 5 days</span>");
100 expect((await mcp("0.2.0")).took).toBe("open for 5 days");
101 });
102
103 test("a wave with no landings is open from its first issue", async () => {
104 expect(await page("0.3.0")).toContain("<span data-wave-duration>open for 2 days</span>");
105 expect((await mcp("0.3.0")).took).toBe("open for 2 days");
106 });
107
108 test("a wave with no changes says nothing of time", async () => {
109 expect(await page("0.4.0")).not.toContain("data-wave-duration");
110 expect((await mcp("0.4.0")).took).toBeUndefined();
111 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs