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

A repository's home carries the growth panel: the two plain sentences from /queue and a link #15272

Merged opened this

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

Merged

scout/forge:scout/15261-a-repository-s-home-carries-the-growth-p → main 10 commits fork 6 threads · 6 unresolved

  • Merged. scout/15261-a-repository-s-home-carries-the-growth-p was merged into main as 9e950cd.

Review

Sign in to review this change.
8 files changed +318 −3
docs/features/growth.md +10 −1
@@ -45,4 +45,13 @@ to wait for." and nothing changes. The pause is a row in `planner_pause` at `CHA
4545 without touching the close. Any other pause or a switch-on forgets the chapter. Pinned by
4646 `test/planner-pause-chapter.test.ts`.
4747
48 Not done: the panel on the repository home, and one action per aged item.
48 **On the repository home** (#15261). For a person who administers the repository, the home carries the
49 queue's two sentences, whether the planner is on or paused, and a link to `/queue` (`web/pages/growth_panel.ts`).
50 On a code home it folds behind the wallet line (`$N.NN this month · growth`); on an app's home it is its own
51 "Growth" fold. The read is the queue page's own in the viewer's sealed scope, kept 30 seconds per repository and
52 scope by `core/growth_panel.ts` (a pause or switch-on forgets it at once), and the admin check is the one the
53 wallet line already makes, so the home gains no query warm. In the terminal, "Growth" in the palette while the
54 repository is open says the same (`src/tui/screens/queuegrowth.ts`). Anyone else, and any agent, sees nothing new.
55 Pinned by `test/repo-growth-panel.test.ts`.
56
57 Not done: one action per aged item.
src/actions/planner_switch.ts +2
@@ -4,6 +4,7 @@
44 * rule (what a pause stops) lives in `core/planner_pause.ts`.
55 */
66
7 import { forgetGrowthPanel } from "../core/growth_panel.ts";
78 import type { App } from "../app.ts";
89 import { canAdmin, type Repo } from "../core/repos.ts";
910 import type { User } from "../core/users.ts";
@@ -64,6 +65,7 @@ export function setPlannerSwitch(
6465 }
6566 pausePlanner(app.db, repo.id, until, actor.id);
6667 }
68 forgetGrowthPanel(app.db, repo.id);
6769 const until = pausedUntil(app.db, repo.id, now);
6870 app.bus.append({
6971 kind: until === null ? "planner.resumed" : "planner.paused",
src/core/growth_panel.ts added +61
@@ -0,0 +1,61 @@
1 /**
2 * What a repository's home says about its growth (#15261), for a person who administers it: the
3 * queue's two sentences (`core/growth.ts`, with the viewer's sealed scope, so sealed issues stay
4 * out of every number) and whether the planner is paused. The home is hot and the read is a range
5 * walk, so the answer is kept for `KEEP_MS` per repository and scope; a pause or a switch-on
6 * forgets it at once (`actions/planner_switch.ts`). Plain data out; the page and the terminal draw
7 * it.
8 */
9 import type { Database } from "bun:sqlite";
10 import type { User } from "./users.ts";
11 import { growth } from "./growth.ts";
12 import { pausedUntil } from "./planner_pause.ts";
13 import type { Repo } from "./repos.ts";
14 import { sealedScope } from "./sealed.ts";
15
16 /** The window the queue page reads, in days. */
17 export const GROWTH_DAYS = 14;
18 export const KEEP_MS = 30_000;
19 const MAX_KEPT = 500;
20
21 export interface GrowthPanel {
22 readonly sentences: readonly string[];
23 /** When the planner's pause lifts, `null` when the planner is on. */
24 readonly until: string | null;
25 }
26
27 type Kept = Map<string, { at: number; panel: GrowthPanel }>;
28 /** Kept per database, so two forges in one process never share an answer. */
29 const keptOf = new WeakMap<Database, Kept>();
30 const keptFor = (db: Database): Kept => {
31 let m = keptOf.get(db);
32 if (m === undefined) keptOf.set(db, (m = new Map()));
33 return m;
34 };
35
36 /** Drop what is kept in `db`: one repository's, or all. */
37 export function forgetGrowthPanel(db: Database, repoId?: string): void {
38 const kept = keptFor(db);
39 if (repoId === undefined) kept.clear();
40 else for (const k of kept.keys()) if (k.startsWith(`${repoId}|`)) kept.delete(k);
41 }
42
43 /**
44 * The panel for `user`, or null for anyone who is not a person administering the repository.
45 * `admin` is the answer of the check the caller has already made.
46 */
47 export function growthPanelFor(db: Database, repo: Repo, user: User | undefined, admin: boolean, now = new Date()): GrowthPanel | null {
48 if (!admin || user === undefined || user.kind === "agent") return null;
49 const scope = sealedScope(db, repo, user);
50 const key = `${repo.id}|${scope.sealed === true ? "all" : (scope.sealedBy ?? "none")}`;
51 const kept = keptFor(db);
52 const hit = kept.get(key);
53 if (hit !== undefined && now.getTime() - hit.at < KEEP_MS && now.getTime() >= hit.at) return hit.panel;
54 const panel: GrowthPanel = {
55 sentences: growth(db, repo, GROWTH_DAYS, now, scope).sentences,
56 until: pausedUntil(db, repo.id, now),
57 };
58 if (kept.size >= MAX_KEPT) kept.clear();
59 kept.set(key, { at: now.getTime(), panel });
60 return panel;
61 }
src/tui/screens/queuegrowth.ts +30
@@ -12,6 +12,7 @@
1212 import { DEFER_TOO_LATE, deferOldest, hasGate, recentDefer, undoDefer } from "../../actions/defer_aged.ts";
1313 import { setCeiling, setPlannerSwitch, SWITCH_REFUSED, switchInput, type SwitchInput } from "../../actions/planner_switch.ts";
1414 import { growth, oldest, WHO } from "../../core/growth.ts";
15 import { growthPanelFor } from "../../core/growth_panel.ts";
1516 import { ceilingHold, CEILING_REASON, openCeiling, PAUSE_STOPS, pauseSentence, pausedUntil } from "../../core/planner_pause.ts";
1617 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
1718 import { sealedScope } from "../../core/sealed.ts";
@@ -149,10 +150,39 @@ export function queueScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
149150 return screen;
150151 }
151152
153 /**
154 * The home's growth line (#15261), as the web home shows its admins (`web/pages/growth_panel.ts`)
155 * from the same read (`core/growth_panel.ts`): the two sentences, the planner's state, a pointer to
156 * Queue. A person who administers the repository, never an agent; anyone else is told so.
157 */
158 export function growthPanelLines(f: Session, repo: Repo, now = new Date()): string[] {
159 const panel = growthPanelFor(f.db, repo, f.user, f.user !== undefined && canAdmin(f.db, repo, f.user), now);
160 if (panel === null) return ["An admin of this repository reads its growth here."];
161 return [...panel.sentences, pauseSentence(panel.until), "Queue has the days and the planner's switch."];
162 }
163
164 export function growthPanelScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
165 return {
166 title: `${repo.ownerName}/${repo.name} — Growth`,
167 keys: [],
168 key: () => false,
169 render(area, s) {
170 const c = ctx.theme.c;
171 growthPanelLines(f, repo).forEach((line, i) => {
172 if (i < area.h) s.text(area.x, area.y + i, truncate(line, area.w), style(i === 0 ? c.fg : c.mutedFg, c.bg), area.x + area.w);
173 });
174 },
175 };
176 }
177
152178 /** The palette's "Queue" while a repository is open: anyone who can read it sees the growth. */
153179 export function queueCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
154180 if (repo === undefined) return [];
181 const admin = f.user !== undefined && f.user.kind !== "agent" && canAdmin(f.db, repo, f.user);
155182 return [
183 ...(admin
184 ? [{ id: "growth-panel", title: `${repo.ownerName}/${repo.name} — Growth`, hint: "how fast the list grows, and whether the planner is on", run: () => ctx.push(growthPanelScreen(f, ctx, repo)) }]
185 : []),
156186 {
157187 id: "queue-growth",
158188 title: `${repo.ownerName}/${repo.name} — Queue`,
src/web/pages/growth_panel.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * The growth panel on a repository's home (#15261): the two plain sentences from /queue (how fast
3 * the list grows, how many days of work are queued), whether the planner is on or paused, and a
4 * link to /queue. For a person who administers the repository, nobody else. The read is
5 * `core/growth_panel.ts`'s (the queue page's own, in the viewer's sealed scope, kept for a few
6 * seconds); the terminal draws the same lines (`tui/screens/queuegrowth.ts`).
7 *
8 * `isAdmin` is the one admin check a home render makes, kept per request so the wallet line and the
9 * panel share it and a visitor pays for it once.
10 */
11 import { growthPanelFor } from "../../core/growth_panel.ts";
12 import { pauseSentence } from "../../core/planner_pause.ts";
13 import { canAdmin, type Repo } from "../../core/repos.ts";
14 import type { Ctx } from "../../http/context.ts";
15 import { repoBase } from "../chrome.ts";
16 import { html, type Html } from "../html.ts";
17 import { icon } from "../icons.ts";
18
19 const asked = new WeakMap<Request, Map<string, boolean>>();
20
21 /** Whether the viewer administers `repo`, asked of the database once per request. */
outdated

Box 4: this adds growth() (3 queries) plus pausedUntil plus canAdmin on every home render for admins, beyond /queue's single read. Cut or cache it; add a test for the sealed scope here, since box 3 is untested.

22 export function isAdmin(ctx: Ctx, repo: Repo): boolean {
23 const per = asked.get(ctx.request) ?? new Map<string, boolean>();
24 asked.set(ctx.request, per);
25 const known = per.get(repo.id);
26 if (known !== undefined) return known;
27 const answer = canAdmin(ctx.app.db, repo, ctx.auth.user);
28 per.set(repo.id, answer);
29 return answer;
30 }
31
32 /** The panel's words and link, with no wrapper; null when this viewer is shown none. */
33 export function growthBody(ctx: Ctx, repo: Repo): Html | null {
34 const panel = growthPanelFor(ctx.app.db, repo, ctx.auth.user, isAdmin(ctx, repo));
35 if (panel === null) return null;
36 return html`<span id="growth-panel" data-growth-panel>${panel.sentences.join(" ")}
37 <span data-planner-state="${panel.until === null ? "on" : "paused"}">${pauseSentence(panel.until)}</span>
38 <a href="${repoBase(repo)}/queue">Queue</a></span>`;
39 }
40
41 /** The panel on its own, folded behind one icon, for a page with no wallet line to carry it. */
42 export function growthPanel(ctx: Ctx, repo: Repo): Html | null {
43 const body = growthBody(ctx, repo);

Non-blocking, principle 1: the icon-only summary says nothing to sighted people; give it one visible word if the budget allows.

44 if (body === null) return null;
45 return html`<details class="muted small mt"><summary title="Growth"><span class="sr-only">Growth</span>${icon("activity")}</summary><p>${body}</p></details>`;
46 }
src/web/pages/repo.ts +7 −2
@@ -94,6 +94,7 @@ import { latestWave } from "../../story/waves.ts";
9494 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
9595 import { liveClientJs, liveMount } from "../live.ts";
9696 import { appStrip } from "./apps.ts";
97 import { growthBody, isAdmin } from "./growth_panel.ts";
9798 import { studioApp } from "../studio/app.ts";
9899 import { declaresFeature } from "../../actions/features.ts";
99100 import { getAppByRepo } from "../../core/apps.ts";
@@ -1472,14 +1473,18 @@ function movedLine(ctx: Ctx, repo: Repo): Html | null {
14721473 * read once, one indexed query; no banner.
14731474 */
14741475 function walletLine(ctx: Ctx, repo: Repo): Html | null {
1475 if (!canAdmin(ctx.app.db, repo, ctx.auth.user)) return null;
1476 if (!isAdmin(ctx, repo)) return null;
14761477 const now = new Date();
14771478 const { cap, spent } = walletStanding(ctx.app.db, repo.id, now);
14781479 // No cap: skip both, whose default would read the cap row again when passed undefined.
14791480 const said =
14801481 (cap === undefined ? undefined : (capReached(ctx.app.db, repo.id, now, cap, spent) ?? lowWallet(ctx.app.db, repo.id, now, cap, spent))) ??
14811482 `${money(spent)} this month`;
1482 return html`<p class="muted small mt" id="wallet-line">${said} <a href="${repoBase(repo)}/wallet">Wallet</a></p>`;
1483 const wallet = html`<a href="${repoBase(repo)}/wallet">Wallet</a>`;
1484 // The growth panel (#15261) folds behind the wallet line, so the first view gains no block.
1485 const grown = growthBody(ctx, repo);
1486 if (grown === null) return html`<p class="muted small mt" id="wallet-line">${said} ${wallet}</p>`;
1487 return html`<details class="muted small mt" id="wallet-line"><summary>${said} · growth</summary><p>${grown} ${wallet}</p></details>`;
14831488 }
14841489
14851490 /**
src/web/studio/app.ts +3
@@ -25,6 +25,7 @@ import { TELL_LIMIT_WORDS, TELL_TEXT_MAX } from "../../actions/tell_from.ts";
2525 import { listCrewRoles } from "../../core/agents.ts";
2626 import type { AppRecord } from "../../core/apps.ts";
2727 import type { DecisionStat } from "../../core/decisions.ts";
28 import { growthPanel } from "../pages/growth_panel.ts";
2829 import { canAdmin, canSeeOwnerFacts, canWrite, type Repo } from "../../core/repos.ts";
2930 import type { PreviewLatency } from "../../core/runs.ts";
3031 import { autonomyStatus } from "../../crew/autonomy.ts";
@@ -520,6 +521,7 @@ export async function studioApp(
520521 ${ownerFacts ? crewKeyCard(ctx, true) : null}
521522 ${ownerFacts ? landOnApp(ctx, repo) : null}
522523 ${pausedLine(ctx, repo)}
524 ${ownerFacts ? growthPanel(ctx, repo) : null}
523525 ${contributeSteps(ctx, repo)}
524526 <div class="stack">
525527 ${adapter}
@@ -548,6 +550,7 @@ export async function studioApp(
548550 ${ownerFacts ? crewKeyCard(ctx, true) : null}
549551 ${ownerFacts ? landOnApp(ctx, repo) : null}
550552 ${pausedLine(ctx, repo)}
553 ${ownerFacts ? growthPanel(ctx, repo) : null}
551554 ${contributeSteps(ctx, repo)}
552555 ${ownerFacts
553556 ? egressNote(
test/repo-growth-panel.test.ts added +159
@@ -0,0 +1,159 @@
1 /**
2 * The growth panel on a repository's home (#15261): the owner reads the queue's two sentences, the
3 * planner's state and a link to /queue; a visitor reads nothing new; the sentences are the queue's
4 * own.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp } from "../src/app.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { openIssue } from "../src/actions/issues.ts";
13 import { setPlannerSwitch } from "../src/actions/planner_switch.ts";
14 import { getRepo } from "../src/core/repos.ts";
15 import { createUser } from "../src/core/users.ts";
16 import { serve } from "../src/http/server.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 let dir = "";
22 let app: ReturnType<typeof createApp>;
23 let servers: Awaited<ReturnType<typeof serve>>;
24 let cookie = "";
25 let user: any;
26
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "forge-growth-panel-"));
29 app = createApp({ dataDir: dir, port: 0 });
30 servers = await serve(app);
31 const made: any = await createUser(app.db, {
32 origin: "seed", trusted: true, username: "trevato", email: "[email protected]",
33 password: "a-good-passphrase", adminIfFirst: true,
34 });
35 user = made.value ?? made;
36 const res = await fetch(servers.url + "/signin", {
37 method: "POST", redirect: "manual",
38 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
39 body: new URLSearchParams({ username: "trevato", password: "a-good-passphrase" }),
40 });
41 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
42 await createRepo(app, user, { name: "garden", visibility: "public" });
43 });
44 afterAll(async () => {
45 servers.stop();
46 app.close();
47 await rm(dir, { recursive: true, force: true });
48 });
49
50 const get = async (path: string, as: string) =>
51 (await fetch(servers.url + path, { redirect: "manual", headers: as ? { cookie: as } : {} })).text();
52 const text = (h: string) => h.replace(/<[^>]*>/g, " ").replace(/&#39;|&apos;/g, "'").replace(/\s+/g, " ");
53
54 test("the owner reads the queue's sentences, the planner state and a link; a visitor reads nothing", async () => {
55 const repo = getRepo(app.db, "trevato", "garden")!;
56 await openIssue(app, user, repo, { title: "Water the beds" });
57 const queue = text(await get("/trevato/garden/queue", cookie));
58 const owner = await get("/trevato/garden", cookie);
59 expect(owner).toContain('id="growth-panel"');
60 expect(owner).toContain('data-planner-state="on"');
61 expect(owner).toContain('href="/trevato/garden/queue"');
62 expect(owner).toContain("The planner is on.");
63 const panel = text(owner.match(/<span id="growth-panel"[\s\S]*?<\/details>/)![0]);
64 const sentence = panel.split("The planner is on.")[0]!.trim();
65 expect(sentence.length).toBeGreaterThan(10);
66 expect(queue).toContain(sentence);
67 const visitor = await get("/trevato/garden", "");
68 expect(visitor).not.toContain("growth-panel");
69 expect(visitor).not.toContain("planner");
70 });
71
72 test("paused, the panel says so", async () => {
73 const repo = getRepo(app.db, "trevato", "garden")!;
74 const done = setPlannerSwitch(app, user, repo, { mode: "owner" } as any);
75 expect(done.ok).toBe(true);
76 const owner = await get("/trevato/garden", cookie);
77 expect(owner).toContain('data-planner-state="paused"');
78 expect(text(owner)).toContain("paused until you switch it on");
79 });
80
81 // ---- the read, the gate, the cache, the studio app home and the terminal (#15261) ----
82 import { newApp } from "../src/actions/apps.ts";
83 import { forgetGrowthPanel, growthPanelFor } from "../src/core/growth_panel.ts";
84 import { createSession } from "../src/core/sessions.ts";
85 import { createIssue } from "../src/core/issues.ts";
86 import { growthPanelLines } from "../src/tui/screens/queuegrowth.ts";
87 import { canAdmin } from "../src/core/repos.ts";
88
89 async function person(name: string) {
90 const r: any = await createUser(app.db, {
91 origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase",
92 });
93 const u = r.value ?? r;
94 return { u, cookie: `forge_session=${createSession(app.db, u.id).token}` };
95 }
96
97 test("an agent and a signed-in non-admin get no panel, on the page or from the read", async () => {
98 forgetGrowthPanel(app.db);
99 const repo = getRepo(app.db, "trevato", "garden")!;
100 const bob = await person("bob");
101 const page = await get("/trevato/garden", bob.cookie);
102 expect(page).not.toContain("growth-panel");
103 expect(page).not.toContain("planner");
104 expect(growthPanelFor(app.db, repo, bob.u, canAdmin(app.db, repo, bob.u))).toBeNull();
105 // An agent is refused even when the admin check says yes.
106 expect(growthPanelFor(app.db, repo, { ...user, kind: "agent" }, true)).toBeNull();
107 expect(growthPanelFor(app.db, repo, undefined, true)).toBeNull();
108 });
109
110 test("the panel is the viewer's own sealed scope, and the cache never lends one scope to another", async () => {
111 forgetGrowthPanel(app.db);
112 const repo = getRepo(app.db, "trevato", "garden")!;
113 const bob = await person("carol");
114 createIssue(app.db, { repoId: repo.id, authorId: bob.u.id, title: "secret", sealed: true });
115 const owner = growthPanelFor(app.db, repo, user, true)!;
116 const queue = await get("/trevato/garden/queue", cookie);
117 // The owner may see sealed issues, so the panel counts them, as the queue does.
118 expect(queue).toContain(owner.sentences[0]!);
119 // A viewer who may not see them is read in their own scope (the admin gate is the caller's).
120 const asBob = growthPanelFor(app.db, repo, bob.u, true)!;
121 const again = growthPanelFor(app.db, repo, user, true)!;
122 expect(again).toBe(owner);
123 expect(asBob).not.toBe(owner);
124 });
125
126 test("the answer is kept briefly, and a pause forgets it at once", async () => {
127 forgetGrowthPanel(app.db);
128 const repo = getRepo(app.db, "trevato", "garden")!;
129 const t = new Date();
130 const first = growthPanelFor(app.db, repo, user, true, t)!;
131 expect(growthPanelFor(app.db, repo, user, true, new Date(t.getTime() + 1000))).toBe(first);
132 expect(growthPanelFor(app.db, repo, user, true, new Date(t.getTime() + 60_000))).not.toBe(first);
133 const kept = growthPanelFor(app.db, repo, user, true)!;
134 setPlannerSwitch(app, user, repo, { mode: "on" } as any);
135 expect(growthPanelFor(app.db, repo, user, true)).not.toBe(kept);
136 });
137
138 test("the studio app home carries the panel for its admin and for nobody else", async () => {
139 forgetGrowthPanel(app.db);
140 const made = await newApp(app, user, { name: "orchard", description: "trees", visibility: "public" });
141 if (!made.ok) throw new Error(String(made.error));
142 const bob = await person("dana");
143 const owner = await get("/trevato/orchard", cookie);
144 expect(owner).toContain('id="app-head"');
145 expect(owner).toContain('data-growth-panel');
146 expect(owner).toContain('href="/trevato/orchard/queue"');
147 expect(await get("/trevato/orchard", bob.cookie)).not.toContain("growth-panel");
148 expect(await get("/trevato/orchard", "")).not.toContain("growth-panel");
149 });
150
151 test("the terminal says the same, to an admin only", () => {
152 forgetGrowthPanel(app.db);
153 const repo = getRepo(app.db, "trevato", "garden")!;
154 const f: any = { db: app.db, app, user };
155 const lines = growthPanelLines(f, repo);
156 expect(lines[0]).toBe(growthPanelFor(app.db, repo, user, true)!.sentences[0]!);
157 expect(lines.join(" ")).toContain("planner");
158 expect(growthPanelLines({ ...f, user: undefined }, repo)).toEqual(["An admin of this repository reads its growth here."]);
159 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs