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

Today's card says what the decider did: closed N, deferred N, asked you about N #1957

Parked opened this
Closed without merging

scout/forge:scout/1606-today-s-card-says-what-the-decider-did-c → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +269 −2
scripts/gate.ts +1
@@ -231,6 +231,7 @@ export const GATE: readonly string[] = [
231231 "test/credentials.test.ts",
232232 "test/standing.test.ts",
233233 "test/board.test.ts",
234 "test/decider-day.test.ts",
234235 "test/spawn-plan.test.ts",
235236 "test/spawn-anon.test.ts",
236237 "test/spawn-host.test.ts",
src/core/decisions.ts +62
@@ -357,3 +357,65 @@ export function decisionsSince(
357357 .all(kind, since, Math.min(500, Math.max(1, limit)))
358358 .map(toDecision);
359359 }
360
361 /**
362 * What the decider did with a person's cards, in three piles: `closed`
363 * (a hand-over set aside), `deferred` (a pull the decider held back with a
364 * `stop`, until its check passes) and `asked` (a hand-over it left with the
365 * owner). A rule's `stop` is the crew's own, not the decider's.
366 */
367 export const DECIDER_PILES = ["closed", "deferred", "asked"] as const;
368 export type DeciderPile = (typeof DECIDER_PILES)[number];
369
370 const PILE_WHERE: Record<DeciderPile, string> = {
371 closed: "kind = 'hand' AND answer = 'set_aside' AND outcome = 'set_aside'",
372 deferred: "kind = 'retry' AND answer = 'stop' AND by != 'rule'",
373 asked: "kind = 'hand' AND answer = 'ask_owner'",
374 };
375
376 export function isDeciderPile(s: unknown): s is DeciderPile {
377 return DECIDER_PILES.includes(s as DeciderPile);
378 }
379
380 const inRepos = (n: number, from: number) =>
381 Array.from({ length: n }, (_, i) => `?${i + from}`).join(",");
382
383 /** How many decisions fall in each pile since a moment, across these repositories. */
384 export function deciderCounts(
385 db: Database,
386 repoIds: readonly string[],
387 since: string,
388 ): Record<DeciderPile, number> {
389 const out = { closed: 0, deferred: 0, asked: 0 };
390 const ids = [...new Set(repoIds)].slice(0, 400);
391 if (ids.length === 0) return out;
392 for (const pile of DECIDER_PILES)
393 out[pile] =
394 db
395 .query<{ n: number }, string[]>(
396 `SELECT COUNT(*) AS n FROM decision
397 WHERE created_at >= ?1 AND (${PILE_WHERE[pile]}) AND repo_id IN (${inRepos(ids.length, 2)})`,
398 )
399 .get(since, ...ids)?.n ?? 0;
400 return out;
401 }
402
403 /** The ledger rows behind one pile's count, newest first. */
404 export function listDeciderPile(
405 db: Database,
406 repoIds: readonly string[],
407 pile: DeciderPile,
408 since: string,
409 limit = 50,
410 ): Decision[] {
411 const ids = [...new Set(repoIds)].slice(0, 400);
412 if (ids.length === 0) return [];
413 return db
414 .query<Row, (string | number)[]>(
415 `SELECT * FROM decision
416 WHERE created_at >= ?1 AND (${PILE_WHERE[pile]}) AND repo_id IN (${inRepos(ids.length, 3)})
417 ORDER BY created_at DESC, id DESC LIMIT ?2`,
418 )
419 .all(since, Math.min(500, Math.max(1, limit)), ...ids)
420 .map(toDecision);
421 }
src/web/pages/board.ts +41 −2
@@ -22,7 +22,11 @@ import { tokenReturns } from "../../core/returns.ts";
2222 import { needLine } from "../../actions/health.ts";
2323 import { returnsRepos } from "../../actions/returns.ts";
2424 import {
25 deciderCounts,
26 isDeciderPile,
2527 listDecisionsForRepos,
28 listDeciderPile,
29 type DeciderPile,
2630 type Decision,
2731 type DecisionKind,
2832 } from "../../core/decisions.ts";
@@ -855,7 +859,13 @@ function decided(ctx: Ctx, scope: BoardScope): Html {
855859 const ids = scope.repos
856860 .filter((r) => scope.ownerFacts.has(r.id))
857861 .map((r) => r.id);
858 const decisions = listDecisionsForRepos(db, ids, 12);
862 // `?ledger=closed|deferred|asked` is the rows behind a count on Today's line.
863 const asked = ctx.url.searchParams.get("ledger");
864 const pile = isDeciderPile(asked) ? asked : null;
865 const decisions =
866 pile === null
867 ? listDecisionsForRepos(db, ids, 12)
868 : listDeciderPile(db, ids, pile, startOfTodayUtc(new Date()).toISOString());
859869 const about = getIssuesByIds(
860870 db,
861871 decisions.map((d) => d.issueId).filter((id): id is string => id !== null),
@@ -910,12 +920,40 @@ function decided(ctx: Ctx, scope: BoardScope): Html {
910920 "Decided",
911921 "run.*,pull.*",
912922 rows,
913 "Nothing decided yet.",
923 pile === null ? "Nothing decided yet." : `The decider ${pile} nothing today.`,
924 pile === null
925 ? null
926 : html`<p class="muted small board-context">
927 What the decider ${pile} today.
928 <a href="${boardHref(ctx, null)}#decided">All decisions</a>
929 </p>`,
914930 );
915931 }
916932
917933 // ---- today ----
918934
935 /** The board's own address, keeping `?apps=`, with a ledger pile (or none) in `?ledger=`. */
936 function boardHref(ctx: Ctx, pile: DeciderPile | null): string {
937 const q = new URLSearchParams();
938 const apps = ctx.url.searchParams.get("apps");
939 if (apps) q.set("apps", apps);
940 if (pile !== null) q.set("ledger", pile);
941 const s = q.toString();
942 return s === "" ? "/board" : `/board?${s}`;
943 }
944
945 /** "The decider closed 4, deferred 2, asked you about 1", each count a link to its ledger rows; null on a quiet day. */
946 function deciderLine(ctx: Ctx, scope: BoardScope, since: string): Html | null {
947 const n = deciderCounts(ctx.app.db, [...scope.ownerFacts], since);
948 if (n.closed + n.deferred + n.asked === 0) return null;
949 const link = (pile: DeciderPile) =>
950 html`<a href="${boardHref(ctx, pile)}#decided">${n[pile]}</a>`;
951 return html`<p class="board-context muted small" id="decider-day">
952 The decider closed ${link("closed")}, deferred ${link("deferred")}, asked
953 you about ${link("asked")}.
954 </p>`;
955 }
956
919957 function today(ctx: Ctx, scope: BoardScope): Html {
920958 const db = ctx.app.db;
921959 const now = new Date();
@@ -1003,6 +1041,7 @@ function today(ctx: Ctx, scope: BoardScope): Html {
10031041 scope.repos.length === 0
10041042 ? "No apps to watch."
10051043 : "No app runs on its own yet.",
1044 deciderLine(ctx, scope, since),
10061045 );
10071046 }
10081047
test/decider-day.test.ts added +165
@@ -0,0 +1,165 @@
1 /**
2 * Today's card on the board carries one line — "The decider closed N,
3 * deferred N, asked you about N" — each count linking to the ledger rows
4 * behind it. A fixture day: a yesterday's row never counts, a rule's stop is
5 * not the decider's, and the link shows exactly the counted rows.
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 { openIssue } from "../src/actions/issues.ts";
13 import { enableApp } from "../src/actions/apps.ts";
14 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
15 import {
16 deciderCounts,
17 recordDecision,
18 setOutcome,
19 type DecisionKind,
20 } from "../src/core/decisions.ts";
21 import type { Repo } from "../src/core/repos.ts";
22 import { createUser, type User } from "../src/core/users.ts";
23 import { serve, type Servers } from "../src/http/server.ts";
24
25 describe("the decider's day on Today's card", () => {
26 let dataDir: string;
27 let app: App;
28 let servers: Servers;
29 let alice: User;
30 let repo: Repo;
31 let cookie: string;
32 let cards = 0;
33
34 const get = (path: string) =>
35 fetch(`${servers.url}${path}`, { headers: { cookie } }).then((r) => r.text());
36
37 function row(
38 kind: DecisionKind,
39 answer: string,
40 by: string,
41 outcome?: string,
42 ): string {
43 const issue = openIssue(app, alice, repo, { title: `Card ${++cards}` });
44 if (!issue.ok) throw new Error(String(issue.error));
45 const d = recordDecision(app.db, {
46 kind,
47 repoId: repo.id,
48 issueId: issue.value.id,
49 state: {},
50 answer,
51 p: 0.9,
52 by,
53 ms: 1,
54 });
55 if (outcome !== undefined) setOutcome(app.db, d.id, outcome);
56 return d.id;
57 }
58
59 beforeAll(async () => {
60 dataDir = await mkdtemp(join(tmpdir(), "forge-decider-day-"));
61 app = createApp({ dataDir, port: 0 });
62 servers = await serve(app);
63 const a = await createUser(app.db, {
64 trusted: true,
65 username: "alice",
66 email: "[email protected]",
67 password: "a-good-passphrase",
68 adminIfFirst: true,
69 });
70 if (!a.ok) throw new Error(a.error);
71 alice = a.value;
72 cookie = (
73 (
74 await fetch(`${servers.url}/signin`, {
75 method: "POST",
76 body: new URLSearchParams({
77 username: "alice",
78 password: "a-good-passphrase",
79 }),
80 redirect: "manual",
81 })
82 ).headers.get("set-cookie") ?? ""
83 ).split(";")[0]!;
84 const made = await createRepo(app, alice, { name: "notes", visibility: "private" });
85 if (!made.ok) throw new Error(String(made.error));
86 repo = made.value;
87 const seeded = await commitToBranch(app, alice, repo, {
88 message: "Start",
89 files: [
90 {
91 path: "package.json",
92 content: '{"name":"notes","scripts":{"start":"bun run server.ts"}}\n',
93 },
94 {
95 path: "server.ts",
96 content:
97 "Bun.serve({ port: Number(process.env.PORT), fetch: () => new Response('ok') });\n",
98 },
99 ],
100 });
101 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
102 const enabled = await enableApp(app, alice, repo, { slug: "notes" });
103 if (!enabled.ok) throw new Error(String(enabled.error));
104 }, 30_000);
105
106 afterAll(async () => {
107 servers.stop();
108 app.close();
109 await rm(dataDir, { recursive: true, force: true });
110 });
111
112 test("a quiet day says nothing", async () => {
113 expect(await get("/board")).not.toContain('id="decider-day"');
114 });
115
116 test("counts the day's closed, deferred and asked, and links each to its rows", async () => {
117 const closed = [1, 2, 3].map(() => row("hand", "set_aside", "typesafe", "set_aside"));
118 row("hand", "set_aside", "typesafe", "undone"); // taken back: not closed
119 row("retry", "stop", "typesafe");
120 row("retry", "stop", "typesafe");
121 row("retry", "stop", "rule"); // the rule's own stop is not the decider's
122 row("retry", "retry", "typesafe");
123 row("hand", "ask_owner", "typesafe", "asked");
124 // Yesterday does not count.
125 app.db
126 .query("UPDATE decision SET created_at = '2020-01-01T00:00:00.000Z' WHERE id = ?1")
127 .run(closed[0]!);
128
129 expect(deciderCounts(app.db, [repo.id], "2021-01-01T00:00:00.000Z")).toEqual({
130 closed: 2,
131 deferred: 2,
132 asked: 1,
133 });
134
135 const page = await get("/board");
136 const line = page.slice(page.indexOf('id="decider-day"'));
137 const text = line
138 .slice(0, line.indexOf("</p>"))
139 .replace(/<[^>]+>/g, "")
140 .replace(/\s+/g, " ");
141 expect(text).toContain("The decider closed 2, deferred 2, asked you about 1.");
142 expect(line).toContain('href="/board?ledger=closed#decided"');
143 expect(line).toContain('href="/board?ledger=deferred#decided"');
144 expect(line).toContain('href="/board?ledger=asked#decided"');
145
146 const rowsOf = async (pile: string) => {
147 const html = await get(`/board?ledger=${pile}`);
148 const decided = html.slice(
149 html.indexOf('id="decided"'),
150 html.indexOf('id="today"'),
151 );
152 return (decided.match(/class="board-card board-decision"/g) ?? []).length;
153 };
154 expect(await rowsOf("closed")).toBe(2);
155 expect(await rowsOf("deferred")).toBe(2);
156 expect(await rowsOf("asked")).toBe(1);
157 });
158
159 test("an unknown pile is ignored, and ?apps= is kept in the links", async () => {
160 const plain = await get("/board?ledger=nonsense");
161 expect(plain).not.toContain("What the decider nonsense");
162 const scoped = await get("/board?apps=notes");
163 expect(scoped).toContain('href="/board?apps=notes&amp;ledger=closed#decided"');
164 });
165 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs