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

A forge's people list ranks by ships and forks and says why, on the page and in a test #15787

Merged opened this

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

Merged

mason/forge:mason/15754-a-forge-s-people-list-ranks-by-ships-and → main 0 commits fork 4 threads · 4 unresolved

  • Merged. mason/15754-a-forge-s-people-list-ranks-by-ships-and was merged into main as cc59e0f.

Review

Sign in to review this change.
7 files changed +194 −16
docs/design/attention-budget.json +3 −3
@@ -187,14 +187,14 @@
187187 "note": "Measured on the test forge's empty state with the machine reading replaced by an empty one and the two cell-cap sentences fixed (the live page's counts depend on the host's cores, disks, processes and cgroups); nothing seeded or waited for. Blocks 65 -> 67 (#11805): the off-site backup section's heading and one-sentence state stay on first view so a red lane is seen without a click; its rows sit behind the disclosure. Blocks 67 -> 69 (#12010): the database size section's heading and its one-sentence state (the file's size and growth, a badge when either is worth a look) stay on first view, as the off-site lane's do; its fact rows and the table of the ten largest tables and indexes sit behind the disclosure. Words +22, blocks +1 (#12092): the footprint section's heading and its one-sentence state (on an empty forge, not read yet and the memory budget) stay on first view; the measured facts and the optional parts sit behind the disclosure. Words +6, blocks +2 (#12420): the stale-pulls section's heading and \"None.\" on a forge with no quiet pull. Words +4, blocks +2 (#13052): the Restore section's heading and its one sentence (\"Restore never proven.\" on an empty forge) stay on first view, so the owner sees whether a restore works without a click. Words +16, blocks +2 (#15073): the least-used-routes section's heading and its one-sentence count stay on first view (how many route groups had no request in 30 days); the table sits behind the disclosure. Words +6, blocks +2 (#15309): the heap census section's heading and its one-sentence state (\"No heap census yet.\" on an empty forge) stay on first view; the button, what a census costs and the table of types that grew sit behind the disclosure."
188188 },
189189 "explore": {
190 "note": "Measured as an admin: the unfiltered count reads 'N apps, forges and people' (+3 words over 'N results'); a guest reads two fewer. An app row says forks by people (+1 word, #14323).",
190 "note": "Measured as an admin: the unfiltered count reads 'N apps, forges and people' (+3 words over 'N results'); a guest reads two fewer. An app row says forks by people (+1 word, #14323). A person row says its ships and forks in 30 days, the figures its place is made of: words +3 (#15754).",
191191 "390": {
192 "words": 43,
192 "words": 46,
193193 "blocks": 9,
194194 "colours": 0
195195 },
196196 "1280": {
197 "words": 43,
197 "words": 46,
198198 "blocks": 9,
199199 "colours": 0
200200 }
docs/features/explore.md +2
@@ -41,6 +41,8 @@ An app whose last change is more than 90 days old (`QUIET_DAYS` in `src/actions/
4141
4242 A like is a `feed_like` row (one per person and post, `src/feed/likes.ts`). An app's count is the likes on posts about its repository, read only for repositories the viewer may read: a private app's likes are never in a public row, and a stranger never sees the private app at all. A person's count is the sum over the apps shown to the viewer.
4343
44 People rank by the ships and forks of their apps in the last 30 days, then by how lately they shipped (`personScore`); a private app counts for nobody but those who may read it. The people view says so in one sentence above the list, each row says its numbers in words (`3 ships, 2 forks in 30 days, shipped 4 days ago`, or `never shipped`), and the terminal's search line says the same sentence under `kind:person` and the same row words (`test/people-rank.test.ts`).
45
4446 In `score`, likes add `0.5 × ln(1 + likes)`, small next to forks (3) and ships (2). The weight is a constant in `explore.ts`, not one of the front page's admin weights.
4547
4648 An unknown `sort:` word is refused as every unknown value is: a 303 on the page, a 422 on the API (see the end of this page).
src/actions/explore.ts +40 −4
@@ -12,7 +12,7 @@
1212 * - A private app's hours awake are told only to those who may enter it,
1313 * as on the front page.
1414 * - People are the owners of the apps shown, their numbers summed and
15 * ranked by their best app.
15 * ranked by `personScore`: ships and forks in the last 30 days, then freshness.
1616 * - Forges are the children this forge spawned, for a site admin.
1717 */
1818
@@ -482,6 +482,34 @@ function shippedWords(shippedAt: string | null, now: number): string {
482482 */
483483 export const forkWords = (forks: number): string => plural(forks, "fork by a person", "forks by people");
484484
485 /**
486 * A person's place: the ships and forks of their apps in the last 30 days, then how lately they
487 * shipped, as a fraction under one so it only ever breaks a tie. Everything counted is what the
488 * viewer may read: a private app's ships and forks never reach a stranger's figures.
489 */
490 export function personScore(
491 lately: { readonly ships: number; readonly forks: number },
492 shippedAt: string | null,
493 now: number,
494 ): number {
495 const days = shippedAt === null ? Infinity : Math.max(0, (now - Date.parse(shippedAt)) / 86_400_000);
496 const fresh = Number.isFinite(days) ? Math.max(0, 1 - days / 365) : 0;
497 return lately.ships + lately.forks + fresh * 0.99;
498 }
499
500 /** Why people are in the order they are, said once above the list. */
501 export const PEOPLE_ORDER_WORDS = "People are ranked by ships and forks in the last 30 days, then by how lately they shipped.";
502
503 /**
504 * A person's numbers in words: "3 ships, 2 forks in 30 days, shipped 4 days ago", or "never
505 * shipped" at the end. Empty for a row that is not a person.
506 */
507 export function peopleWords(row: ExploreRow, now: number): string {
508 if (row.kind !== "person" || row.lately === undefined) return "";
509 const last = row.shippedAt === null ? "never shipped" : `shipped ${shippedAgo(row.shippedAt, now)}`;
510 return `${plural(row.lately.ships, "ship", "ships")}, ${plural(row.lately.forks, "fork", "forks")} in 30 days, ${last}`;
511 }
512
485513 /**
486514 * The counts of an app row's line, said in full ("3 forks by people, 5 ships, 2 likes"): forks and ships
487515 * always, likes when there are some or the sort ranks by them, hours awake when the sort ranks by
@@ -595,6 +623,10 @@ export interface ExploreRow {
595623 readonly apps: number;
596624 };
597625 readonly shippedAt: string | null;
626 /**
627 * A person: the ships and forks of their apps in the last 30 days, what their place is made of.
628 */
629 readonly lately?: { readonly ships: number; readonly forks: number };
598630 /** When the app was made (a person: their newest app); read only for `sort:new`. */
599631 readonly createdAt?: string;
600632 readonly score: number;
@@ -1001,6 +1033,7 @@ function rank(
10011033 awakeHours: Math.round(s.awakeHours * 10) / 10,
10021034 apps: 1,
10031035 },
1036 lately: { ships: s.ships, forks: s.recentForks ?? 0 },
10041037 shippedAt: s.shippedAt,
10051038 ...(dates?.get(repo.id) === undefined ? {} : { createdAt: dates.get(repo.id)!.createdAt }),
10061039 score: t.forks + t.ships + t.use + t.fresh + terms.likes + terms.quiet,
@@ -1029,6 +1062,10 @@ function rank(
10291062 const newest = [was?.createdAt, row.createdAt].filter((t): t is string => t !== undefined).sort().at(-1);
10301063 const owner = owners.get(repo.ownerId);
10311064 const mark = markOf(owner);
1065 const lately = {
1066 ships: (was?.lately?.ships ?? 0) + (row.lately?.ships ?? 0),
1067 forks: (was?.lately?.forks ?? 0) + (row.lately?.forks ?? 0),
1068 };
10321069 people.set(repo.ownerName, {
10331070 kind: "person",
10341071 name: repo.ownerName,
@@ -1044,10 +1081,9 @@ function rank(
10441081 apps: (was?.numbers.apps ?? 0) + 1,
10451082 },
10461083 shippedAt: latest ?? null,
1084 lately,
10471085 ...(newest === undefined ? {} : { createdAt: newest }),
1048 // A person ranks by their best app, so one with many small ones
1049 // does not crowd out everything else.
1050 score: Math.max(was?.score ?? 0, row.score),
1086 score: personScore(lately, latest ?? null, now),
10511087 });
10521088 });
10531089
src/core/front.ts +7 −4
@@ -61,6 +61,8 @@ export interface FrontSignals {
6161 * not a private fork, whose existence is its owner's to tell.
6262 */
6363 readonly forks: number;
64 /** Of `forks`, those made in the last 30 days; absent where nobody asked. */
65 readonly recentForks?: number;
6466 /**
6567 * The last pull merged, ever, or null: a ship. A deploy is not one — a
6668 * forge redeploys everything when it boots.
@@ -121,15 +123,16 @@ export function frontSignals(
121123 merge(r.repo_id, { ships: r.n, shippedAt: r.last });
122124
123125 const forks = db
124 .query<{ parent: string; n: number }, string[]>(
125 `SELECT repo.fork_parent_id AS parent, COUNT(*) AS n
126 .query<{ parent: string; n: number; recent: number }, string[]>(
127 `SELECT repo.fork_parent_id AS parent, COUNT(*) AS n,
128 SUM(repo.created_at >= ?${ids.length + 1}) AS recent
126129 FROM repo JOIN user ON user.id = repo.owner_id
127130 WHERE user.is_agent = 0 AND ${PUBLIC_VISIBLE}
128131 AND repo.fork_parent_id IN (${list(0)})
129132 GROUP BY repo.fork_parent_id`,
130133 )
131 .all(...ids);
132 for (const r of forks) merge(r.parent, { forks: r.n });
134 .all(...ids, since);
135 for (const r of forks) merge(r.parent, { forks: r.n, recentForks: r.recent });
133136
134137 return out;
135138 }
src/tui/screens/dashboard.ts +6 −2
@@ -16,7 +16,7 @@
1616
1717 import { readyAsk } from "../../spawn/template_record.ts";
1818 import { DEFAULT_WEIGHTS, frontWeights, type FrontWeights } from "../../core/front.ts";
19 import { quietSince, exploreCount, exploreFiltered, exploreLine, isExploreLine, exploreNote, exploreSuggestion, explorePage, groupForks, parseExploreQuery, readExploreLine, whyOf, figuresOf, type ExploreRow } from "../../actions/explore.ts";
19 import { quietSince, exploreCount, exploreFiltered, exploreLine, isExploreLine, exploreNote, exploreSuggestion, explorePage, groupForks, parseExploreQuery, readExploreLine, whyOf, figuresOf, peopleWords, PEOPLE_ORDER_WORDS, type ExploreRow } from "../../actions/explore.ts";
2020 import { protectionNotice } from "../../kernel/protection.ts";
2121 import { holdWords, plannerHold } from "../../crew/autonomy.ts";
2222 import { governorLine, governorSeen } from "../../crew/governed.ts";
@@ -1698,6 +1698,9 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
16981698 // A quiet app says so, as the page and the API do.
16991699 const quiet = row.kind === "app" ? quietSince(row.shippedAt, Date.now()) : "";
17001700 if (figures !== "") return metaOf(figures, quiet);
1701 // A person says what their place is made of, as the page does, with their apps.
1702 const people = peopleWords(row, Date.now());
1703 if (people !== "") return metaOf(people, plural(n.apps, "app"));
17011704 return metaOf(
17021705 why?.text ?? "",
17031706 row.kind === "person" ? plural(n.apps, "app") : "",
@@ -1713,7 +1716,8 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
17131716 function drawExplored(s: Surface, r: Rect, c: Tokens): void {
17141717 const rows = exploredRows();
17151718 const on = focus === "repos";
1716 const tail = [explored?.note ?? "", explored?.next != null ? "more results — n" : ""].filter((x) => x !== "").join(" · ");
1719 const peopleOrder = parseExploreQuery(explored?.line ?? "").kind === "person" ? PEOPLE_ORDER_WORDS : "";
1720 const tail = [explored?.note ?? "", peopleOrder, explored?.next != null ? "more results — n" : ""].filter((x) => x !== "").join(" · ");
17171721 if (tail !== "" && r.h >= 2) {
17181722 const [body, line] = split(r, "v", [fill(1), len(1)]);
17191723 s.text(line!.x, line!.y, truncate(tail, line!.w), style(c.attn, c.bg), line!.x + line!.w);
src/web/studio/explore.ts +6 −3
@@ -26,6 +26,8 @@ import {
2626 quietTitle,
2727 quietNote,
2828 figureParts,
29 peopleWords,
30 PEOPLE_ORDER_WORDS,
2931 readExploreLine,
3032 type ExploreQuery,
3133 type ExploreRow,
@@ -84,7 +86,8 @@ function rowHtml(row: ExploreRow, query: ExploreQuery, now: number, weights: Fro
8486 const forkPiece: Html = n.forks === 0 ? html`` : row.repo === undefined ? html`${parts0.forks}` : html`<a href="/${row.repo.owner}/${row.repo.name}/forks">${parts0.forks}</a>`;
outdated

Principle 1: the page needs one sentence saying why people are in this order; the row alone does not say it. Also this ternary line is already unreadable; give the people case its own small piece.

8587 const figured: Html = [forkPiece, html`${parts0.rest}`].filter((p) => p.toString() !== "").reduce((all, p, i) => (i === 0 ? p : html`${all}, ${p}`), html``);
8688 const figures = figured.toString();
87 const signal = figures !== "" ? (row.shippedAt === null ? html`${figured}, never shipped` : html`${figured}, shipped ${time(row.shippedAt, { text: shippedAgo(row.shippedAt, now) })}`) : why === undefined ? "" : why.signal === "fresh" && row.shippedAt !== null ? html`shipped ${time(row.shippedAt, { text: shippedAgo(row.shippedAt, now) })}` : html`${why.text}`;
89 const people = peopleWords(row, now);
90 const signal = people !== "" ? html`${people}` : figures !== "" ? (row.shippedAt === null ? html`${figured}, never shipped` : html`${figured}, shipped ${time(row.shippedAt, { text: shippedAgo(row.shippedAt, now) })}`) : why === undefined ? "" : why.signal === "fresh" && row.shippedAt !== null ? html`shipped ${time(row.shippedAt, { text: shippedAgo(row.shippedAt, now) })}` : html`${why.text}`;
8891 // One tap from a person to their apps; with none, the count is plain text.
8992 const theirs = href({ kind: "app", sort: "score", text: "", archived: false, updated: "all", owner: row.name });
9093 const apps = row.kind === "person" ? `${row.numbers.apps} app${row.numbers.apps === 1 ? "" : "s"}` : "";
@@ -324,7 +327,7 @@ export async function explorePage(ctx: Ctx): Promise<Response> {
324327 { label: "This month", updated: "30d" as const },
325328 ];
326329 const body = html`<div data-explore>${pageHead("Explore", {
327 sub: "Public apps and their builders, ranked by use, forks, deployments and recency.",
330 sub: query.kind === "person" ? PEOPLE_ORDER_WORDS : "Public apps and their builders, ranked by use, forks, deployments and recency.",
328331 })}
329332 <div class="bar mb" data-filter-line>
330333 <form method="get" action="/explore" class="bar">
@@ -407,7 +410,7 @@ export async function explorePage(ctx: Ctx): Promise<Response> {
407410 pad: false,
408411 extra: "bare",
409412 })}${rows.some((r) => r.kind === "app" && quietSince(r.shippedAt, now) !== "") ? html`<p class="mb small muted" data-quiet-note>${quietNote}</p>` : html``}${pager(query, shown.page, shown.pages)}</div>`;
410 const drawn = page({ ctx, title: "Explore", description: "Public apps, forges and people on this forge, ranked by use, forks, deployments and recency.", body: compact(body), feed: { href: "/explore.atom", title: "Explore" }, ...(tag === undefined ? {} : { etag: tag }) });
413 const drawn = page({ ctx, title: "Explore", description: query.kind === "person" ? `People on this forge. ${PEOPLE_ORDER_WORDS}` : "Public apps, forges and people on this forge, ranked by use, forks, deployments and recency.", body: compact(body), feed: { href: "/explore.atom", title: "Explore" }, ...(tag === undefined ? {} : { etag: tag }) });
411414 notePhase(ctx.request, "render", performance.now() - rendering);
412415 return badKind ? new Response(drawn.body, { status: 400, headers: drawn.headers }) : drawn;
413416 }
test/people-rank.test.ts added +130
@@ -0,0 +1,130 @@
1 /**
2 * #15754: the explorer's people rank by ships and forks in the last 30 days, then by how lately
3 * they shipped; each row says its numbers in words; a private app counts for nobody else's view.
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 { createApp, type App } from "../src/app.ts";
10 import { explore, parseExploreQuery, peopleWords, personScore, PEOPLE_ORDER_WORDS } from "../src/actions/explore.ts";
11 import { newApp } from "../src/actions/apps.ts";
12 import { createIssue } from "../src/core/issues.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve } from "../src/http/server.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { promote } from "./helpers/members.ts";
17
18 quietLogs();
19
20 const DAY = 86_400_000;
21 let dataDir: string;
22 let app: App;
23
24 const repoId = (owner: string, name: string): string =>
25 app.db.query<{ id: string }, [string, string]>(`SELECT repo.id AS id FROM repo JOIN user ON user.id = repo.owner_id WHERE user.username = ?1 AND repo.name = ?2`).get(owner, name)!.id;
26
27 function ship(repoId: string, authorId: string, daysAgo: number): void {
28 const issue = createIssue(app.db, { repoId, authorId, title: "change", kind: "pull" });
29 if (!issue.ok) throw new Error(issue.error);
30 app.db
31 .query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES (?1, 'main', 'b', '', '', ?2)`)
32 .run(issue.value.id, new Date(Date.now() - daysAgo * DAY).toISOString());
33 }
34
35 beforeAll(async () => {
36 dataDir = await mkdtemp(join(tmpdir(), "forge-people-rank-"));
37 app = createApp({ dataDir, port: 0 });
38 // Sign-up order: bea, ann, cid, dee. Place: cid, bea, ann, dee.
39 for (const [i, username] of ["bea", "ann", "cid", "dee"].entries()) {
40 const r = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: i === 0 });
41 if (!r.ok) throw new Error(r.error);
42 promote(app.db, r.value);
43 const made = await newApp(app, r.value, { name: `${username}-work`, description: "", visibility: "public" });
44 if (!made.ok) throw new Error(String(made.error));
45 const shown = { bea: [10], ann: [2], cid: [3, 4], dee: [40] }[username]!;
46 for (const d of shown) ship(repoId(username, `${username}-work`), r.value.id, d);
47 if (username === "dee") {
48 // One fork of bea's app made now, one made 60 days ago: only the first is recent.
49 for (const [name, daysAgo] of [["dee-fork-new", 0], ["dee-fork-old", 60]] as const) {
50 const f = await newApp(app, r.value, { name, description: "", visibility: "public" });
51 if (!f.ok) throw new Error(String(f.error));
52 app.db
53 .query(`UPDATE repo SET fork_parent_id = ?1, created_at = ?2 WHERE id = ?3`)
54 .run(repoId("bea", "bea-work"), new Date(Date.now() - daysAgo * DAY).toISOString(), repoId("dee", name));
55 }
56 }
57 if (username === "cid") {
58 // Private work: five ships nobody else may count.
59 const secret = await newApp(app, r.value, { name: `${username}-secret`, description: "", visibility: "private" });
60 if (!secret.ok) throw new Error(String(secret.error));
61 for (let k = 0; k < 5; k++) ship(repoId(username, `${username}-secret`), r.value.id, 1);
62 }
63 }
64 }, 60_000);
65

Passes on main too (numbers.ships ignored private apps already). Pin lately/order instead.

66 afterAll(async () => {
67 app.close();
68 await rm(dataDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
69 });
70
71 const people = () => explore(app, undefined, parseExploreQuery("kind:person"));
72
73 test("people rank by ships and forks in 30 days, a tie by freshness, not by sign-up order", async () => {
74 const rows = await people();
75 // cid and bea both have two; cid shipped three days ago, bea ten. ann has one. dee has none
76 // lately.
77 expect(rows.map((r) => r.name)).toEqual(["cid", "bea", "ann", "dee"]);
78 expect(rows[0]!.lately).toEqual({ ships: 2, forks: 0 });
outdated

+ 0.99 - 1e-9 + 0 is noise; and no test exercises recentForks from the SQL or a ship older than 30 days.

79 });
80
81 test("a stranger's view counts no private app: five private ships leave cid at two, in first place", async () => {
82 const cid = (await people()).find((r) => r.name === "cid")!;
83 expect(cid.lately).toEqual({ ships: 2, forks: 0 });
84 expect((await people())[0]!.name).toBe("cid");
85 });
86
87 test("only forks made in the last 30 days count, though every fork is still a fork", async () => {
88 const bea = (await people()).find((r) => r.name === "bea")!;
89 expect(bea.numbers.forks).toBe(2);
90 expect(bea.lately).toEqual({ ships: 1, forks: 1 });
91 });
92
93 test("a ship older than 30 days is not counted, and the row still says when it was", async () => {
94 const dee = (await people()).find((r) => r.name === "dee")!;
95 expect(dee.lately).toEqual({ ships: 0, forks: 0 });
96 expect(peopleWords(dee, Date.now())).toBe("0 ships, 0 forks in 30 days, shipped 40 days ago");
97 });
98
99 test("each row says ships, forks and last active in words; no ship says so", async () => {
100 const rows = await people();
101 expect(peopleWords(rows.find((r) => r.name === "ann")!, Date.now())).toBe("1 ship, 0 forks in 30 days, shipped 2 days ago");
102 const never = { ...rows[0]!, shippedAt: null, lately: { ships: 0, forks: 0 } };
103 expect(peopleWords(never, Date.now())).toBe("0 ships, 0 forks in 30 days, never shipped");
104 });
105
106 test("a fork counts as much as a ship, and freshness only breaks ties", () => {
107 const now = Date.now();
108 const at = new Date(now - DAY).toISOString();
109 const forkNotFresh = personScore({ ships: 1, forks: 1 }, null, now);
110 const shipFresh = personScore({ ships: 1, forks: 0 }, at, now);
111 expect(forkNotFresh).toBeGreaterThan(shipFresh);
112 const noShipFresh = personScore({ ships: 0, forks: 0 }, at, now);
113 expect(shipFresh).toBeGreaterThan(noShipFresh);
114 expect(personScore({ ships: 1, forks: 0 }, null, now)).toBeGreaterThan(noShipFresh);
115 });
116
117 test("the people view says why in one sentence; the apps view does not claim it", async () => {
118 const servers = await serve(app);
119 try {
120 const people = await (await fetch(`${servers.url}/explore?kind=person`)).text();
121 expect(people).toContain(PEOPLE_ORDER_WORDS);
122 expect(people).not.toContain("ranked by use, forks, deployments and recency");
123 expect(people).toContain("2 ships, 0 forks in 30 days");
124 expect(people).not.toContain("30d,");
125 const apps = await (await fetch(`${servers.url}/explore?kind=app`)).text();
126 expect(apps).not.toContain(PEOPLE_ORDER_WORDS);
127 } finally {
128 await servers.stop();
129 }
130 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs