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

`This week` is counted, not sampled: the app page's numbers come from queries #98

Closed opened this
Closed without merging

scout/forge:scout/91-this-week-is-counted-not-sampled-the-app → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +356 −24
src/core/pulls.ts +45
@@ -288,6 +288,51 @@ export function mergedPullsForRepos(
288288 );
289289 }
290290
291 /**
292 * How many pulls merged on this repository since a moment — one query, for
293 * the *This week* card's *Shipped* count, correct past any number of pulls.
294 */
295 export function mergedCountSince(
296 db: Database,
297 repoId: string,
298 since: string,
299 ): number {
300 const row = db
301 .query<{ n: number }, [string, string]>(
302 `SELECT COUNT(*) AS n FROM pull JOIN issue ON issue.id = pull.issue_id
303 WHERE issue.repo_id = ?1 AND pull.merged_at IS NOT NULL AND pull.merged_at >= ?2`,
304 )
305 .get(repoId, since);
306 return row?.n ?? 0;
307 }
308
309 /**
310 * The pull whose merge closed an issue, read straight from the
311 * `issue.closed` event it left behind (`actions/pulls.ts`) — one indexed
312 * query, by repository and the issue's own number, rather than paging
313 * recent events and searching them in JavaScript. An issue closed a
314 * thousand events ago still finds it. Undefined for an issue closed by
315 * hand, or still open.
316 */
317 export function pullThatClosed(
318 db: Database,
319 repoId: string,
320 issueNumber: number,
321 ): Pull | undefined {
322 const row = db
323 .query<{ pull: number | null }, [string, number]>(
324 `SELECT json_extract(payload, '$.pull') AS pull FROM event
325 WHERE repo_id = ?1 AND kind = 'issue.closed'
326 AND json_extract(payload, '$.number') = ?2
327 AND json_extract(payload, '$.by') = 'merge'
328 ORDER BY id DESC LIMIT 1`,
329 )
330 .get(repoId, issueNumber);
331 return row?.pull === null || row?.pull === undefined
332 ? undefined
333 : getPull(db, repoId, row.pull);
334 }
335
291336 /** The pull rows for a page of issues, keyed by issue id. */
292337 export function pullsForIssues(
293338 db: Database,
src/core/runs.ts +29
@@ -590,6 +590,35 @@ export function latestAgentRunsForRepos(
590590 return out;
591591 }
592592
593 export interface RunTotals {
594 readonly runs: number;
595 readonly spentUsd: number;
596 }
597
598 /**
599 * Runs of one kind on a repository since a moment, counted and summed in
600 * one query — correct past any number of rows, unlike paging the rows in
601 * and counting them in JavaScript (`studio.ts`'s *This week* card, and
602 * `spentToday` in `crew/autonomy.ts`, are the same shape).
603 */
604 export function runTotalsSince(
605 db: Database,
606 repoId: string,
607 kind: RunKind,
608 since: string,
609 ): RunTotals {
610 const row = db
611 .query<
612 { runs: number; spent: number | null },
613 [string, RunKind, string]
614 >(
615 `SELECT COUNT(*) AS runs, SUM(cost_usd) AS spent FROM run
616 WHERE repo_id = ?1 AND kind = ?2 AND created_at >= ?3`,
617 )
618 .get(repoId, kind, since)!;
619 return { runs: row.runs, spentUsd: row.spent ?? 0 };
620 }
621
593622 /** Agent runs queued or running across many repositories, newest first. */
594623 export function listActiveRuns(
595624 db: Database,
src/web/pages/studio.ts +42 −23
@@ -34,8 +34,8 @@ import {
3434 import { listCrewRoles, type Agent } from "../../core/agents.ts";
3535 import { appsForRepos, getAppByRepo, type AppRecord } from "../../core/apps.ts";
3636 import { dependenciesOf } from "../../core/dependencies.ts";
37 import { listEvents } from "../../core/events.ts";
3837 import {
38 countIssues,
3939 getIssueById,
4040 listComments,
4141 listIssues,
@@ -46,8 +46,10 @@ import {
4646 getPull,
4747 joinMany,
4848 listPulls,
49 mergedCountSince,
4950 openPullsClosing,
5051 pullForBranch,
52 pullThatClosed,
5153 type Pull,
5254 } from "../../core/pulls.ts";
5355 import { canSeeOwnerFacts, listReposVisibleTo, type Repo } from "../../core/repos.ts";
@@ -61,6 +63,7 @@ import {
6163 latestRunsForIssues,
6264 listActiveRuns,
6365 listRuns,
66 runTotalsSince,
6467 type CheckSummary,
6568 type Run,
6669 } from "../../core/runs.ts";
@@ -823,6 +826,7 @@ function previewsPanel(
823826 record: AppRecord,
824827 openPulls: readonly Pull[],
825828 envs: readonly EnvStatus[],
829 openCount: number,
826830 ): Html | null {
827831 if (openPulls.length === 0) return null;
828832 const byPull = new Map(
@@ -830,6 +834,7 @@ function previewsPanel(
830834 .filter((e) => e.env !== "production")
831835 .map((e) => [envPull(e.env), e] as const),
832836 );
837 const more = openCount - openPulls.length;
833838 return listCard(
834839 openPulls.map((p) =>
835840 previewRow(base, runtime, record, p, byPull.get(p.number)),
@@ -837,6 +842,11 @@ function previewsPanel(
837842 {
838843 head: html`${icon("rocket")}
839844 <h2>Previews</h2>`,
845 ...(more > 0
846 ? {
847 foot: html`<p class="muted small">Showing the first ${openPulls.length} of ${openCount} open changes.</p>`,
848 }
849 : {}),
840850 },
841851 );
842852 }
@@ -852,12 +862,20 @@ function appPanels(
852862 repo: Repo,
853863 record: AppRecord,
854864 openPulls: readonly Pull[],
865 openPullCount: number,
855866 ): { head: Html; previews: Html | null } {
856867 const db = ctx.app.db;
857868 const base = repoBase(repo);
858869 const runtime = appsRuntime(ctx.app);
859870 const envs: EnvStatus[] = runtime === undefined ? [] : runtime.status(record);
860 const previews = previewsPanel(base, runtime, record, openPulls, envs);
871 const previews = previewsPanel(
872 base,
873 runtime,
874 record,
875 openPulls,
876 envs,
877 openPullCount,
878 );
861879 const production = envs.find((e) => e.env === "production");
862880 const url = runtime?.urlFor(record, "production");
863881 const writer = canSeeOwnerFacts(db, repo, ctx.auth.user);
@@ -914,7 +932,14 @@ export function appStateFragment(ctx: Ctx): Response {
914932 state: "open",
915933 limit: 10,
916934 });
917 const { head, previews } = appPanels(ctx, repo, record, openPulls);
935 const openPullCount = countIssues(ctx.app.db, repo.id, "pull", "open");
936 const { head, previews } = appPanels(
937 ctx,
938 repo,
939 record,
940 openPulls,
941 openPullCount,
942 );
918943 return fragment(html`<div id="app-head">${head}</div>
919944 <div id="app-previews">${previews}</div>`);
920945 }
@@ -953,18 +978,14 @@ export async function studioApp(
953978 }
954979 const decisions = withLikely(ctx, decisionsFor(ctx, [repo]));
955980 const openPulls = listPulls(db, repo.id, { state: "open", limit: 10 });
981 const openPullCount = countIssues(db, repo.id, "pull", "open");
956982 const week = new Date(Date.now() - 7 * 24 * 60 * 60_000).toISOString();
957 const shipped = listPulls(db, repo.id, {
958 state: "closed",
959 limit: 100,
960 }).filter((p) => p.mergedAt !== null && p.mergedAt >= week).length;
983 const shipped = mergedCountSince(db, repo.id, week);
961984 // The rest is spend, worked out only for a viewer who is going to see it.
962985 const weekRuns = ownerFacts
963 ? listRuns(db, repo.id, { kind: "agent", limit: 200 }).filter(
964 (r) => r.createdAt >= week,
965 )
966 : [];
967 const spent = weekRuns.reduce((s, r) => s + r.costUsd, 0);
986 ? runTotalsSince(db, repo.id, "agent", week)
987 : { runs: 0, spentUsd: 0 };
988 const spent = weekRuns.spentUsd;
968989 const ledgerWeek = ownerFacts ? decisionStats(db, repo.id, week) : [];
969990 const autonomy =
970991 !ownerFacts || repo.autonomy === "off"
@@ -972,7 +993,13 @@ export async function studioApp(
972993 : autonomyStatus(ctx.app, repo);
973994
974995 // ---- the app itself ----
975 const { head, previews } = appPanels(ctx, repo, record, openPulls);
996 const { head, previews } = appPanels(
997 ctx,
998 repo,
999 record,
1000 openPulls,
1001 openPullCount,
1002 );
9761003
9771004 // ---- the box ----
9781005 // Telling the crew, and who takes it, is the owner's own front door — a
@@ -1160,7 +1187,7 @@ export async function studioApp(
11601187 <dt>Shipped</dt>
11611188 <dd>${shipped} change${shipped === 1 ? "" : "s"}</dd>
11621189 <dt>Runs</dt>
1163 <dd>${weekRuns.length}</dd>
1190 <dd>${weekRuns.runs}</dd>
11641191 <dt>Spent</dt>
11651192 <dd>
11661193 $${spent.toFixed(2)}${shipped > 0
@@ -1654,15 +1681,7 @@ export async function studioPull(
16541681 * shows. Undefined for an issue closed by hand, or still open. */
16551682 function shippedBy(db: Database, repo: Repo, issue: Issue): Pull | undefined {
16561683 if (issue.state !== "closed") return undefined;
1657 const closed = listEvents(db, { repoId: repo.id, limit: 200 }).find(
1658 (e) =>
1659 e.kind === "issue.closed" &&
1660 Number(e.payload.number) === issue.number &&
1661 e.payload.by === "merge",
1662 );
1663 if (closed === undefined) return undefined;
1664 const number = Number(closed.payload.pull);
1665 return Number.isInteger(number) ? getPull(db, repo.id, number) : undefined;
1684 return pullThatClosed(db, repo.id, issue.number);
16661685 }
16671686
16681687 /**
test/studio.test.ts +240 −1
@@ -29,7 +29,7 @@ import { setCrewRole } from "../src/core/agents.ts";
2929 import { recordDecision } from "../src/core/decisions.ts";
3030 import { getIssue, listIssues, type Issue } from "../src/core/issues.ts";
3131 import { recordLook } from "../src/core/looks.ts";
32 import { getPull, type Pull } from "../src/core/pulls.ts";
32 import { getPull, pullThatClosed, type Pull } from "../src/core/pulls.ts";
3333 import { setDirectionIssue, type Repo } from "../src/core/repos.ts";
3434 import {
3535 claimRun,
@@ -2505,3 +2505,242 @@ describe("servedPhrase", () => {
25052505 ).toBeUndefined();
25062506 });
25072507 });
2508
2509 /**
2510 * `This week` used to read a page of recent rows — 200 runs, 100 closed
2511 * pulls — and filter it in JavaScript, so a repository busier than that
2512 * page quietly under-reported. These aggregates are queries, bounded by the
2513 * window instead of a row count, so the numbers hold past that old sample.
2514 */
2515 describe("This week counts every row in the window, past the old sample limits", () => {
2516 let dataDir: string;
2517 let app: App;
2518 let servers: Servers;
2519 let base: string;
2520 let alice: User;
2521 let repo: Repo;
2522 let cookie: string;
2523 // Past the old 200-run and 100-pull samples `studioApp` used to read.
2524 const RUNS = 240;
2525 const PULLS = 120;
2526
2527 const get = (path: string) =>
2528 fetch(`${base}${path}`, {
2529 headers: { cookie: `${cookie}; forge_mode=studio` },
2530 redirect: "manual",
2531 });
2532
2533 beforeAll(async () => {
2534 dataDir = await mkdtemp(join(tmpdir(), "forge-studio-window-"));
2535 app = createApp({ dataDir, port: 0 });
2536 servers = await serve(app);
2537 base = servers.url;
2538 const a = await createUser(app.db, {
2539 username: "alice",
2540 email: "[email protected]",
2541 password: "a-good-passphrase",
2542 adminIfFirst: true,
2543 });
2544 if (!a.ok) throw new Error(a.error);
2545 alice = a.value;
2546 cookie = (
2547 (
2548 await fetch(`${base}/signin`, {
2549 method: "POST",
2550 body: new URLSearchParams({
2551 username: "alice",
2552 password: "a-good-passphrase",
2553 }),
2554 redirect: "manual",
2555 })
2556 ).headers.get("set-cookie") ?? ""
2557 ).split(";")[0]!;
2558 const made = await createRepo(app, alice, {
2559 name: "busy",
2560 visibility: "private",
2561 description: "more history than a sample's worth",
2562 });
2563 if (!made.ok) throw new Error(String(made.error));
2564 repo = made.value;
2565 const seeded = await commitToBranch(app, alice, repo, {
2566 message: "Start",
2567 files: [
2568 {
2569 path: "package.json",
2570 content: '{"name":"busy","scripts":{"start":"bun run server.ts"}}\n',
2571 },
2572 {
2573 path: "server.ts",
2574 content:
2575 "Bun.serve({ port: Number(process.env.PORT), fetch: () => new Response('ok') });\n",
2576 },
2577 ],
2578 });
2579 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
2580 const enabled = await enableApp(app, alice, repo, { slug: "busy" });
2581 if (!enabled.ok) throw new Error(String(enabled.error));
2582 const scout = await createAgent(app, alice, { username: "scout" });
2583 if (!scout.ok) throw new Error(String(scout.error));
2584 expect(addToCrew(app, alice, repo, "scout").ok).toBe(true);
2585 const scoutId = scout.value.user.id;
2586
2587 // More agent runs, this week, than the old sample read.
2588 for (let i = 0; i < RUNS; i++) {
2589 const run = createRun(app.db, {
2590 repoId: repo.id,
2591 kind: "agent",
2592 actorId: scoutId,
2593 reason: "assigned",
2594 });
2595 claimRun(app.db, run.id);
2596 finishRun(app.db, run.id, {
2597 state: "ok",
2598 summary: `run ${i}`,
2599 costUsd: 1,
2600 });
2601 }
2602
2603 // More merged pulls, this week, than the old sample read — the merge
2604 // action itself is a git operation, so the rows are written directly,
2605 // the same way `test/scale.test.ts` seeds a pull for `mergedPullNumbers`.
2606 for (let i = 0; i < PULLS; i++) {
2607 const opened = openIssue(app, alice, repo, { title: `shipped ${i}` });
2608 if (!opened.ok) throw new Error("seed pull");
2609 app.db
2610 .query(
2611 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at)
2612 VALUES (?1, 'main', ?2, 'a', 'b', ?3)`,
2613 )
2614 .run(opened.value.id, `f${i}`, new Date().toISOString());
2615 app.db
2616 .query("UPDATE issue SET kind = 'pull', state = 'closed' WHERE id = ?1")
2617 .run(opened.value.id);
2618 }
2619
2620 // More open pulls than the previews list ever shows at once.
2621 for (let i = 0; i < 11; i++) {
2622 const branch = await commitToBranch(app, alice, repo, {
2623 branch: `open/pr-${i}`,
2624 base: "main",
2625 message: `Open PR ${i}`,
2626 files: [{ path: `open-${i}.md`, content: "x\n" }],
2627 });
2628 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
2629 const openedPull = await openPull(app, alice, repo, {
2630 title: `Open PR ${i}`,
2631 body: "",
2632 baseBranch: "main",
2633 headBranch: `open/pr-${i}`,
2634 });
2635 if (!openedPull.ok) throw new Error(String(openedPull.error));
2636 }
2637 });
2638
2639 afterAll(async () => {
2640 servers.stop();
2641 app.close();
2642 await rm(dataDir, { recursive: true, force: true });
2643 });
2644
2645 test("Runs, Spent, Shipped and the per-change cost all come from the whole window", async () => {
2646 const page = await (await get("/alice/busy")).text();
2647 expect(page).toContain(`<dd>${RUNS}</dd>`);
2648 expect(page).toContain(`$${RUNS.toFixed(2)}`);
2649 expect(page).toContain(`${PULLS} changes`);
2650 const perChange = (RUNS / PULLS).toFixed(2);
2651 expect(page).toContain(`$${perChange} per shipped change`);
2652 });
2653
2654 test("the previews list says it is showing only the first ten of more open changes", async () => {
2655 const page = await (await get("/alice/busy")).text();
2656 expect(page).toContain("Showing the first 10 of 11 open changes.");
2657 });
2658
2659 test("the app page answers in milliseconds — the window is a query, not a page of rows to filter", async () => {
2660 const started = performance.now();
2661 const res = await get("/alice/busy");
2662 await res.text();
2663 expect(performance.now() - started).toBeLessThan(500);
2664 });
2665 });
2666
2667 /**
2668 * `shippedBy` used to page the newest 200 events and search them in
2669 * JavaScript for the one `issue.closed` event it wanted. Past that page, an
2670 * old tell's link to the change that shipped it silently vanished.
2671 */
2672 describe("shippedBy survives being buried under events newer than the merge", () => {
2673 let dataDir: string;
2674 let app: App;
2675 let alice: User;
2676 let repo: Repo;
2677 let tellNumber: number;
2678
2679 beforeAll(async () => {
2680 dataDir = await mkdtemp(join(tmpdir(), "forge-studio-buried-"));
2681 app = createApp({ dataDir, port: 0 });
2682 const a = await createUser(app.db, {
2683 username: "alice",
2684 email: "[email protected]",
2685 password: "a-good-passphrase",
2686 adminIfFirst: true,
2687 });
2688 if (!a.ok) throw new Error(a.error);
2689 alice = a.value;
2690 const made = await createRepo(app, alice, {
2691 name: "buried",
2692 visibility: "private",
2693 });
2694 if (!made.ok) throw new Error(String(made.error));
2695 repo = made.value;
2696 const seeded = await commitToBranch(app, alice, repo, {
2697 message: "Start",
2698 files: [{ path: "README.md", content: "buried\n" }],
2699 });
2700 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
2701 const tell = openIssue(app, alice, repo, { title: "Fix the leak" });
2702 if (!tell.ok) throw new Error(String(tell.error));
2703 tellNumber = tell.value.number;
2704 const branch = await commitToBranch(app, alice, repo, {
2705 branch: "fix/the-leak",
2706 base: "main",
2707 message: "Fix the leak",
2708 files: [{ path: "LEAK.md", content: "fixed\n" }],
2709 });
2710 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
2711 const opened = await openPull(app, alice, repo, {
2712 title: "Fix the leak",
2713 body: `Closes #${tell.value.number}`,
2714 baseBranch: "main",
2715 headBranch: "fix/the-leak",
2716 });
2717 if (!opened.ok) throw new Error(String(opened.error));
2718 const merged = await mergePull(app, alice, repo, opened.value, "squash");
2719 if (!merged.ok) throw new Error(String(merged.error));
2720
2721 // Bury the issue.closed event under 250 events newer than it.
2722 for (let i = 0; i < 250; i++) {
2723 app.bus.append({
2724 kind: "issue.opened",
2725 repoId: repo.id,
2726 payload: { number: 10_000 + i },
2727 });
2728 }
2729 });
2730
2731 afterAll(async () => {
2732 app.close();
2733 await rm(dataDir, { recursive: true, force: true });
2734 });
2735
2736 test("the merge a thousand events back still answers, by one indexed query", () => {
2737 const pull = pullThatClosed(app.db, repo.id, tellNumber);
2738 expect(pull?.title).toBe("Fix the leak");
2739 });
2740
2741 test("an issue nothing merged shut still answers undefined", () => {
2742 const opened = openIssue(app, alice, repo, { title: "Never shipped" });
2743 if (!opened.ok) throw new Error(String(opened.error));
2744 expect(pullThatClosed(app.db, repo.id, opened.value.number)).toBeUndefined();
2745 });
2746 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs