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

The Next up cut line still falls when the week's dollar capacity is unknown, by the pace the crew is landing issues #12103

Parked opened this
Closed without merging

scout/forge:scout/12080-the-next-up-cut-line-still-falls-when-th → main 7 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +123 −11
src/flow/week.ts +61 −3
@@ -11,6 +11,7 @@ import type { Database } from "bun:sqlite";
1111 import type { NextRow } from "../core/next_up.ts";
1212 import { standings } from "../core/standing.ts";
1313 import { listCredentials } from "../core/subscriptions.ts";
14 import { windowShipped } from "./retro.ts";
1415 import { estimate, issueHistory, kindOf, labelsOf, MIN_SAMPLES, SURE_SAMPLES, sizeOf, type Estimate, type Sample } from "./estimate.ts";
1516
1617 export interface Capacity {
@@ -51,6 +52,8 @@ export interface Cut {
5152 readonly shipLow: number;
5253 readonly shipHigh: number;
5354 readonly confidence: Confidence;
55 /** What drew the line: the dollars (`cost`) or the issues landed a day (`pace`). */
56 readonly by: "cost" | "pace";
5457 /** Why there is no line: capacity or history missing. Null when drawn. */
5558 readonly unsure: string | null;
5659 }
@@ -78,6 +81,8 @@ export const FIT_COUNT_JS = `function fitCount(costs, usd) {
7881 export const CUT_TOP_WORDS = "Nothing here fits what is left of this week: all of this reads as next week.";
7982 export const cutWords = (fit: number | string): string => `This week ends here (${fit} fit): below this line reads as next week.`;
8083
84 export const paceCutWords = (fit: number | string): string => `This week ends here by pace (${fit} reach it): below this line reads as next week.`;
85
8186 /** What each row counts for against the week: its mid, or the median mid when it has no estimate; null when no line can be drawn. */
8287 export function rowCosts(rows: readonly Priced[]): number[] | null {
8388 const known = rows.flatMap((r) => (r.estimate.known ? [r.estimate.mid] : []));
@@ -92,7 +97,7 @@ export function rowCosts(rows: readonly Priced[]): number[] | null {
9297 * there is no line, and it says so.
9398 */
9499 export function cutLine(rows: readonly Priced[], capacity: Capacity | null): Cut {
95 const none = (unsure: string): Cut => ({ fits: [], shipLow: 0, shipHigh: 0, confidence: "low", unsure });
100 const none = (unsure: string): Cut => ({ fits: [], shipLow: 0, shipHigh: 0, confidence: "low", by: "cost", unsure });
96101 if (capacity === null) return none("the weekly capacity has not been read yet");
97102 const known = rows.flatMap((r) => (r.estimate.known ? [r.estimate] : []));
98103 if (known.length === 0) return none("there is too little history to estimate any issue");
@@ -104,7 +109,7 @@ export function cutLine(rows: readonly Priced[], capacity: Capacity | null): Cut
104109 const weakest = Math.min(...rows.map((r) => r.estimate.samples));
105110 const confidence: Confidence =
106111 known.length < rows.length ? "low" : weakest >= SURE_SAMPLES ? "high" : weakest >= MIN_SAMPLES ? "medium" : "low";
107 return { fits, shipLow: least, shipHigh: most, confidence, unsure: null };
112 return { fits, shipLow: least, shipHigh: most, confidence, by: "cost", unsure: null };
108113 }
109114
110115 /** The projection in one sentence. */
@@ -131,6 +136,45 @@ export function rangeWords(e: Estimate): string {
131136 return e.known ? `$${e.low.toFixed(2)}–$${e.high.toFixed(2)} (${e.basis})` : e.basis;
132137 }
133138
139 const DAY_MS = 86_400_000;
140 /** Fewer landed issues than this in the window and the pace is a guess. */
141 export const PACE_SAMPLES = 3;
142
143 export interface PaceIn {
144 readonly landedPerDay: number;
145 readonly daysLeft: number;
146 readonly total: number;
147 }
148 export interface Pace {
149 /** How many rows from the top the pace covers. */
150 readonly rows: number;
151 readonly reason: string;
152 }
153
154 /** How many rows from the top the pace covers: floor(perDay * daysLeft), never past the list. */
155 export function paceCut({ landedPerDay, daysLeft, total }: PaceIn): Pace {
156 const raw = Math.floor(Math.max(0, landedPerDay) * Math.max(0, daysLeft));
157 const rows = Math.min(Math.max(0, total), Number.isFinite(raw) ? raw : 0);
158 const rate = `${round1(landedPerDay)} issues a day, ${round1(daysLeft)} days left`;
159 return { rows, reason: `by pace: ${rate}${rows === 0 ? "; none reaches the reset" : ""}` };
160 }
161
162 const round1 = (n: number): string => String(Math.round(n * 10) / 10);
163
164 /** Days from `now` to the reset, or to the ISO week's end (Monday 00:00 UTC) when none is known. */
165 export function daysLeft(capacity: Capacity | null, now: Date): number {
166 const at = capacity?.resetsAt == null ? NaN : Date.parse(capacity.resetsAt);
167 if (Number.isFinite(at) && at > now.getTime()) return (at - now.getTime()) / DAY_MS;
168 const toMonday = 7 - ((now.getUTCDay() + 6) % 7);
169 const end = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + toMonday);
170 return (end - now.getTime()) / DAY_MS;
171 }
172
173 /** Issues closed done in the last 7 days, read once through the retro's reader. */
174 function landedIn7Days(db: Database, repoId: string, now: Date): number {
175 return windowShipped(db, repoId, new Date(now.getTime() - 7 * DAY_MS).toISOString(), now.toISOString()).length;
176 }
177
134178 /** Everything the page, the terminal and MCP draw of the week on Next up, from one read. */
135179 export interface WeekView {
136180 readonly priced: readonly Priced[];
@@ -143,5 +187,19 @@ export function weekView(db: Database, repoId: string, rows: readonly NextRow[],
143187 const capacity = weekCapacity(db, now);
144188 const priced = priceRows(db, repoId, rows);
145189 const cut = cutLine(priced, capacity);
146 return { priced, cut, capacity, sentence: projection(cut, rows.length, capacity) };
190 if (cut.unsure === null) return { priced, cut, capacity, sentence: projection(cut, rows.length, capacity) };
191 // No dollar line: fall back to the pace, and say it is the issues a day that drew it.
192 const landed = landedIn7Days(db, repoId, now);
193 const left = daysLeft(capacity, now);
194 const pace = paceCut({ landedPerDay: landed / 7, daysLeft: left, total: rows.length });
195 const guess = landed < PACE_SAMPLES ? "; pace is a guess" : "";
196 const paced: Cut = {
197 fits: rows.slice(0, pace.rows).map((r) => r.issue.number),
198 shipLow: pace.rows,
199 shipHigh: pace.rows,
200 confidence: "low",
201 by: "pace",
202 unsure: null,
203 };
204 return { priced, cut: paced, capacity, sentence: `Line ${pace.reason.split(";")[0]}${guess}.` };
147205 }
src/tui/screens/next.ts +1 −1
@@ -144,7 +144,7 @@ export function nextScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
144144 meta: [stateWord(r, { stage: stages.get(r.issue.number) ?? "issue", waits: r.waits, held: r.state === "held", onIt: r.onIt !== null }), r.onIt ?? "next", estimate === undefined ? "" : rangeWords(estimate), r.why ?? ""]
145145 .filter((x) => x !== "")
146146 .join(" · "),
147 ...(ends ? { note: `── this week ends here (${cut.fits.length} fit): below reads as next week ──` } : {}),
147 ...(ends ? { note: `── this week ends here ${cut.by === "pace" ? "by pace " : ""}(${cut.fits.length} ${cut.by === "pace" ? "reach it" : "fit"}): below reads as next week ──` } : {}),
148148 };
149149 });
150150
src/web/pages/next.ts +3 −3
@@ -17,7 +17,7 @@ import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1717 import { pillarsOf, servedBy } from "../../core/pillars.ts";
1818 import { sealedScope } from "../../core/sealed.ts";
1919 import { notStartable } from "../../crew/not_startable.ts";
20 import { CUT_TOP_WORDS, cutWords, FIT_COUNT_JS, rangeWords, rowCosts, weekView, type Cut, type Priced } from "../../flow/week.ts";
20 import { CUT_TOP_WORDS, cutWords, paceCutWords, FIT_COUNT_JS, rangeWords, rowCosts, weekView, type Cut, type Priced } from "../../flow/week.ts";
2121 import type { Ctx } from "../../http/context.ts";
2222 import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, repoHeader, repoPalette, signInFirst } from "../chrome.ts";
2323 import { backTo, field, readForm } from "../form.ts";
@@ -189,7 +189,7 @@ function line(
189189 function cutMark(cut: Cut, top: boolean): Html {
190190 return html`<li class="cut-line" role="separator">${top
191191 ? CUT_TOP_WORDS
192 : cutWords(cut.fits.length)}</li>`;
192 : cut.by === "pace" ? paceCutWords(cut.fits.length) : cutWords(cut.fits.length)}</li>`;
193193 }
194194
195195 export function nextPage(ctx: Ctx): Response {
@@ -223,7 +223,7 @@ export function nextPage(ctx: Ctx): Response {
223223 const section = (title: string, list: readonly number[], open: boolean, id?: string): Html => {
224224 const mark = markBefore(list, cutAt);
225225 return html`<details class="mt"${open ? raw(" open") : null}><summary><h2>${title} · ${String(list.length)}</h2></summary>
226 <ul class="list setting-list"${id === undefined ? null : html` id="${id}"`}${id !== undefined && !isFiltered && costs !== null && capacity !== null && cut.unsure === null ? html` data-capacity="${String(capacity.usd)}"` : null}>
226 <ul class="list setting-list"${id === undefined ? null : html` id="${id}"`}${id !== undefined && !isFiltered && costs !== null && capacity !== null && cut.unsure === null && cut.by === "cost" ? html` data-capacity="${String(capacity.usd)}"` : null}>
227227 ${list.flatMap((at, i) => [
228228 ...(i === mark && cut.unsure === null && id !== undefined ? [cutMark(cut, false)] : []),
229229 line(base, rows, at, writer, back, false, priced, costs?.[at], at + 1, stateWord(rows[at]!, facts(rows[at]!)), rows[at]!.byOwner, promise(rows[at]!)),
test/pages-budget.test.ts +1 −1
@@ -37,7 +37,7 @@ const DEFAULT = { statements: 60, git: 8 };
3737 /** Pages that cost more today, with the most they may: lower these, never raise them. */
3838 const HEAVIER: Record<string, { statements?: number; git?: number }> = {
3939 "/:owner/:name/issues/:number": { statements: 70 },
40 "/:owner/:name/next": { statements: 64 },
40 "/:owner/:name/next": { statements: 65 }, // +1: the issues landed in the week, read only when no dollar line can be drawn, for the pace line
4141 "/:owner/:name/pulls/:number": { statements: 113 }, // +1: whether a repository is the forge's own copy, one read of the source setting for the tell box (#12037); +1: the paused sentence, one read of a queued paused run on the pull (#12010); +1: the header Talk count (#10327); +1: the landing line (#10860); +1: whether a reviewer is seated, read only when Require review is off and the pull would otherwise wait on one; the page loads no crew besides (#11666)
4242 "/board": { statements: 72 }, // +1: the forge-copy read for the tell box (#12037); +1: the vitals read the database's growth (#12025); +6: the money line (#510) — one settings read, then the month's and the 30 days' meter, storage and ledger reads; constant in the number of apps
4343 "/settings/capacity": { statements: 71 },
test/week-sprint.test.ts +3 −3
@@ -168,13 +168,13 @@ describe("the week, in a forge", () => {
168168 expect(one.every((p) => p.estimate.known)).toBe(true);
169169 });
170170
171 test("the page shows ranges and the projection sentence; no capacity read means no line", async () => {
171 test("the page shows ranges and the projection sentence; no capacity read draws the line by pace", async () => {
172172 const res = await fetch(`${servers.url}/alice/plan/next`, { headers: { cookie } });
173173 expect(res.status).toBe(200);
174174 const text = await res.text();
175175 expect(text).toContain("$2.00–$4.00");
176 expect(text).toContain("No projection yet: the weekly capacity has not been read yet.");
177 expect(text).not.toContain('role="separator"');
176 expect(text).toContain("Line by pace:");
177 expect(text).not.toContain("No projection yet");
178178 });
179179
180180 test("capacity is what the weekly window leaves, read from the ledger", () => {
test/week.test.ts +54
@@ -80,3 +80,57 @@ describe("efficiency", () => {
8080 expect(efficiencyWords({ landings: 0, runs: 2, costUsd: 4 })).toContain("Nothing has landed");
8181 });
8282 });
83
84 describe("paceCut and the pace line on Next up", () => {
85 const { paceCut, daysLeft, weekView, cutLine } = require("../src/flow/week.ts") as typeof import("../src/flow/week.ts");
86 const { nextUp } = require("../src/core/next_up.ts") as typeof import("../src/core/next_up.ts");
87
88 test("zero pace reaches zero rows and says so; a faster pace moves the line down; never past the list", () => {
89 const zero = paceCut({ landedPerDay: 0, daysLeft: 3, total: 10 });
90 expect(zero.rows).toBe(0);
91 expect(zero.reason).toContain("none reaches");
92 const slow = paceCut({ landedPerDay: 1, daysLeft: 3.5, total: 10 });
93 const fast = paceCut({ landedPerDay: 2, daysLeft: 3.5, total: 10 });
94 expect(slow.rows).toBe(3);
95 expect(fast.rows).toBe(7);
96 expect(paceCut({ landedPerDay: 50, daysLeft: 6, total: 4 }).rows).toBe(4);
97 expect(fast.reason).toContain("2 issues a day, 3.5 days left");
98 });
99
100 test("days left come from the reset, or else the end of the ISO week", () => {
101 expect(daysLeft({ usd: 1, resetsAt: new Date(NOW.getTime() + 2 * DAY).toISOString() }, NOW)).toBe(2);
102 // Monday noon: 6.5 days to the next Monday.
103 expect(daysLeft(null, NOW)).toBe(6.5);
104 });
105
106 test("weekView draws the pace line when no dollar line exists, and the cost line wins when it does", async () => {
107 const app = createApp({ dataDir: mkdtempSync(join(tmpdir(), "forge-week-")), port: 0 });
108 const u = await createUser(app.db, { username: "alice", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, adminIfFirst: true });
109 if (!u.ok) throw new Error(u.error);
110 const made = await createRepo(app.db, app.reposRoot, { ownerId: u.value.id, name: "r", visibility: "public", description: "r" });
111 if (!made.ok) throw new Error(made.error);
112 const repo = made.value;
113 const put = (n: number, state: string, closedAt: string | null) =>
114 app.db
115 .query(`INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at, closed_at, close_reason) VALUES (?1, ?2, ?3, 'issue', ?4, '', ?5, ?6, ?7, ?8, ?9)`)
116 .run(id(), repo.id, n, `Issue ${n}`, u.value.id, state, NOW.toISOString(), closedAt, closedAt === null ? null : "done");
117 for (let n = 1; n <= 14; n++) put(n, "closed", new Date(NOW.getTime() - (n % 6) * DAY - 1000).toISOString());
118 for (let n = 15; n <= 24; n++) put(n, "open", null);
119 const next = nextUp(app.db, repo);
120 const view = weekView(app.db, repo.id, next.rows, NOW);
121 // 14 landed in 7 days is 2 a day; 6.5 days left: 13 rows, capped at the list.
122 expect(view.cut.by).toBe("pace");
123 expect(view.cut.fits.length).toBe(Math.min(13, next.rows.length));
124 expect(view.sentence).toContain("by pace: 2 issues a day, 6.5 days left");
125 expect(view.cut.fits).toEqual(next.rows.slice(0, view.cut.fits.length).map((r) => r.issue.number));
126 // Few landings: the sentence says the pace is a guess.
127 const few = weekView(app.db, repo.id, next.rows, new Date(NOW.getTime() + 30 * DAY));
128 expect(few.sentence).toContain("pace is a guess");
129 // With a dollar line the cost wins.
130 const priced = next.rows.map((r) => ({ number: r.issue.number, estimate: { known: true as const, low: 1, mid: 2, high: 3, samples: 5, basis: "x" } }));
131 const cost = cutLine(priced, { usd: 4, resetsAt: null });
132 expect(cost.by).toBe("cost");
133 expect(cost.unsure).toBeNull();
134 app.close();
135 });
136 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs