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

The owner's open-pull count has a ceiling setting, and past it the planner and builders start nothing new #15808

Merged opened this

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

Merged

mason/forge:mason/15805-the-owner-s-open-pull-count-has-a-ceilin → main 0 commits fork 5 threads · 5 unresolved

  • Merged. mason/15805-the-owner-s-open-pull-count-has-a-ceilin was merged into main as 7247fd1.

Review

Sign in to review this change.
13 files changed +382 −14
docs/features/open-pulls-ceiling.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Tell the crew
3 row: The open-pull ceiling: pause new builds while pulls wait for review
4 ---
5 # The open-pull ceiling
6
7 This page is for a repository's owner. At or over the ceiling (default 20 open pulls) the crew starts no builder run for a new issue, so the pulls waiting for review shrink before more arrive. Reviews, rework on open pulls and the planner carry on. 0 turns it off.
8
9 ## Set it
10
11 - On the web: open `/<owner>/<app>/queue`, type a number in "Pull ceiling" and press "Set the pull ceiling".
12 - Through the MCP: the `system` tool, `{ kind: "growth", repo, action: "pulls_ceiling", pulls: 20 }` is a preview that changes nothing; add `confirm: true` to set it. The same tool without `action` reads `pullsCeiling` and `pullsHeld`.
13 - In the terminal: the Queue screen shows the ceiling and the paused line; press `p`, type a number, and Enter.
14
15 While it holds, the repository home, the queue page and `/flow` say "paused: 50 of 20 pulls open". Only the owner sets it; an agent never does.
src/actions/planner_switch.ts +16
@@ -10,6 +10,7 @@ import { canAdmin, type Repo } from "../core/repos.ts";
1010 import type { User } from "../core/users.ts";
1111 import { err, ok, type Result } from "../kernel/result.ts";
1212 import { FOREVER, liftCeilingOnce, nextWeek, pauseForChapter, parseCeiling, pausePlanner, pausedUntil, resumePlanner, setOpenCeiling } from "../core/planner_pause.ts";
13 import { parsePullsCeiling, setOpenPullsCeiling } from "../core/pulls_ceiling.ts";
1314 import { weekCapacity } from "../flow/week.ts";
1415
1516 export type SwitchInput =
@@ -115,3 +116,18 @@ export function setCeiling(
115116 app.bus.append({ kind: "planner.ceiling", repoId: repo.id, actorId: actor.id, payload: { mode: input.mode, value } });
116117 return ok(value);
117118 }
119
120 /**
121 * The open-pull ceiling (#15805): the owner sets it (a whole number, 0 = off). Same rule as the
122 * others: a person who administers, never an agent.
123 */
124 export function setPullsCeiling(app: App, actor: User | undefined, repo: Repo, raw: string): Result<number, SwitchError> {
125 if (actor === undefined) return err("not_found");
126 if (actor.kind === "agent" || !canAdmin(app.db, repo, actor)) return err("forbidden");
127 const n = parsePullsCeiling(raw);
128 if (n === undefined) return err("invalid");
129 setOpenPullsCeiling(app.db, repo.id, n, actor.id);

The event reuses planner.ceiling with mode "pulls". Check what consumes it, or use its own kind.

130 forgetGrowthPanel(app.db, repo.id);
131 app.bus.append({ kind: "planner.ceiling", repoId: repo.id, actorId: actor.id, payload: { mode: "pulls", value: n } });
132 return ok(n);
133 }
src/core/growth_panel.ts +9 −1
@@ -9,6 +9,7 @@
99 import type { Database } from "bun:sqlite";
1010 import type { User } from "./users.ts";
1111 import { growth } from "./growth.ts";
12 import { pullsCeilingHold } from "./pulls_ceiling.ts";
1213 import { pausedUntil } from "./planner_pause.ts";
1314 import type { Repo } from "./repos.ts";
1415 import { sealedScope } from "./sealed.ts";
@@ -22,6 +23,8 @@ export interface GrowthPanel {
2223 readonly sentences: readonly string[];
2324 /** When the planner's pause lifts, `null` when the planner is on. */
2425 readonly until: string | null;
26 /** "paused: 50 of 20 pulls open" while the open-pull ceiling holds new builds, else null. */
27 readonly pullsHeld: string | null;
2528 }
2629
2730 type Kept = Map<string, { at: number; panel: GrowthPanel }>;
@@ -50,10 +53,15 @@ export function growthPanelFor(db: Database, repo: Repo, user: User | undefined,
5053 const key = `${repo.id}|${scope.sealed === true ? "all" : (scope.sealedBy ?? "none")}`;
5154 const kept = keptFor(db);
5255 const hit = kept.get(key);
53 if (hit !== undefined && now.getTime() - hit.at < KEEP_MS && now.getTime() >= hit.at) return hit.panel;
56 if (hit !== undefined && now.getTime() - hit.at < KEEP_MS && now.getTime() >= hit.at) {
57 // The pull count moves with no setter to clear this, so the line is read fresh; the rest is kept.
58 const held = pullsCeilingHold(db, repo.id);
59 return held === hit.panel.pullsHeld ? hit.panel : { ...hit.panel, pullsHeld: held };
60 }
5461 const panel: GrowthPanel = {
5562 sentences: growth(db, repo, GROWTH_DAYS, now, scope).sentences,
5663 until: pausedUntil(db, repo.id, now),
64 pullsHeld: pullsCeilingHold(db, repo.id),
5765 };
5866 if (kept.size >= MAX_KEPT) kept.clear();
5967 kept.set(key, { at: now.getTime(), panel });
src/core/pulls_ceiling.ts added +66
@@ -0,0 +1,66 @@
1 /**
2 * The open-pull ceiling (#15805): at or over it the dispatcher starts no builder run for a new
3 * issue, so the pulls waiting for a person shrink before more are made. Reviewers, rework on
4 * pulls already open and the planner are not held: the review is how the pile shrinks, and a
5 * held planner could never split work to be done after. Per repository, in `forge_setting`; no
6 * row is the default. 0 turns it off. Plain data in and out.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { parseCeiling } from "./planner_pause.ts";
11
12 export const DEFAULT_PULLS_CEILING = 20;
13 export const MAX_PULLS_CEILING = 100_000;
14 export const PULLS_CEILING_REASON =
15 "At or over this many open pulls the crew starts no builder run for a new issue, so the pulls waiting for review shrink before more arrive. Reviews and rework on open pulls carry on. 0 turns it off.";
16
17 /**
18 * The one line under the cause while the ceiling holds; the reason above is said when it does not.
19 */
20 export const PULLS_HELD_NOTE = "New builds wait for reviews.";
21
22 const key = (repoId: string) => `crew.openPullsCeiling.${repoId}`;
23
24 export function openPullsCeiling(db: Database, repoId: string): number {
25 const row = db.query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1").get(key(repoId));
26 const n = row === null ? NaN : Number(row.value);
27 return Number.isInteger(n) && n >= 0 ? n : DEFAULT_PULLS_CEILING;
28 }
29
30 /** Whole number from 0 to MAX_PULLS_CEILING, or undefined: the open-issue ceiling's rule. */
31 export const parsePullsCeiling = parseCeiling;
32
33 export function setOpenPullsCeiling(db: Database, repoId: string, value: number, byId: string): void {
34 db.query(
35 `INSERT INTO forge_setting (key, value, updated_by, updated_at) VALUES (?1, ?2, ?3, strftime('%Y-%m-%dT%H:%M:%fZ','now'))
36 ON CONFLICT(key) DO UPDATE SET value = ?2, updated_by = ?3, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`,
37 ).run(key(repoId), String(value), byId);
38 }
39
40 export function openPullsNow(db: Database, repoId: string): number {
41 return db.query<{ c: number }, [string]>("SELECT COUNT(*) AS c FROM issue WHERE repo_id = ?1 AND kind = 'pull' AND state = 'open'").get(repoId)?.c ?? 0;
42 }
43
44 /** The words for a count over a ceiling. */
45 export const pullsPausedWords = (open: number, ceiling: number) => `paused: ${open} of ${ceiling} pulls open`;
46
47 /** The cause new builder runs are held, in words, or null when they may start. */
48 export function pullsCeilingHold(db: Database, repoId: string): string | null {
49 const ceiling = openPullsCeiling(db, repoId);
50 if (ceiling === 0) return null;
51 const open = openPullsNow(db, repoId);
52 return open >= ceiling ? pullsPausedWords(open, ceiling) : null;
53 }
54
55 /** Every repository held now, as [repo id, cause]: only repositories with open pulls are walked. */
56 export function pullsCeilingHeld(db: Database): { repoId: string; cause: string }[] {
57 const rows = db
58 .query<{ repo_id: string; c: number }, []>("SELECT repo_id, COUNT(*) AS c FROM issue WHERE kind = 'pull' AND state = 'open' GROUP BY repo_id")
59 .all();
60 const held: { repoId: string; cause: string }[] = [];
61 for (const r of rows) {
62 const ceiling = openPullsCeiling(db, r.repo_id);
63 if (ceiling !== 0 && r.c >= ceiling) held.push({ repoId: r.repo_id, cause: pullsPausedWords(r.c, ceiling) });
64 }
65 return held;
66 }
src/crew/dispatch.ts +16
@@ -9,6 +9,7 @@
99 */
1010
1111 import { ceilingHold, pausedUntil } from "../core/planner_pause.ts";
12 import { pullsCeilingHold } from "../core/pulls_ceiling.ts";
1213 import { chapterHold } from "../core/chapters.ts";
1314 import { crewFilters, isStrangerPull } from "./stranger.ts";
1415 import { TEMP_FULL } from "../checks/disk_full.ts";
@@ -511,6 +512,21 @@ export function queueAgentRun(
511512 (ceilingHold(app.db, repo.id) !== null && !splitPending(app, repo)))
512513 )
513514 return undefined;
515 // The open-pull ceiling (#15805): at or over it no builder starts on a new issue. Reviews, rework
516 // on pulls, a run carrying on and the planner (it splits, it does not build) are not held.
517 if (
518 reason === "assigned" &&
519 again === undefined &&
520 issue.kind === "issue" &&
521 crewRole(app.db, repo.id, agent.user.id) !== "planner" &&
522 issue.id !== repo.directionIssueId
523 ) {
524 const held = pullsCeilingHold(app.db, repo.id);
525 if (held !== null) {
526 log.info("build run refused: the open-pull ceiling holds", { repo: `${repo.ownerName}/${repo.name}`, issue: issue.number, held });
527 return undefined;
528 }
529 }
514530 // `crew builds here` off (#13644): no builder or planner run starts on this repository, however
515531 // it was asked; one already going (`again`) finishes. Reviewers carry on.
516532 if (again === undefined && !crewBuildsHere(app.db, repo.id)) {
src/flow/planner_held.ts +15
@@ -5,6 +5,7 @@
55 */
66 import type { Database } from "bun:sqlite";
77 import { ceilingHold } from "../core/planner_pause.ts";
8 import { pullsCeilingHeld } from "../core/pulls_ceiling.ts";
89
910 export interface Held {
1011 readonly repo: string;
@@ -12,6 +13,20 @@ export interface Held {
1213 }
1314
1415 export function plannerHeld(db: Database): Held[] {
16 return [...ceilingHeld(db), ...pullsHeld(db)];
17 }
18
19 /** Repositories whose open-pull ceiling holds new builds (#15805), the cause beside each. */
20 function pullsHeld(db: Database): Held[] {
21 const held: Held[] = [];
22 for (const h of pullsCeilingHeld(db)) {
23 const r = db.query<{ owner: string; name: string }, [string]>("SELECT u.username AS owner, r.name FROM repo r JOIN user u ON u.id = r.owner_id WHERE r.id = ?1").get(h.repoId);
24 if (r !== null) held.push({ repo: `${r.owner}/${r.name}`, cause: h.cause });
25 }
26 return held;
27 }
28
29 function ceilingHeld(db: Database): Held[] {
1530 const rows = db
1631 .query<{ id: string; owner: string; name: string }, []>(
1732 `SELECT r.id, u.username AS owner, r.name FROM repo r JOIN user u ON u.id = r.owner_id
src/http/mcp/tools/system.ts +17 −5
@@ -18,8 +18,9 @@ import { largestDirs } from "../../../system/largest_dirs.ts";
1818 import { dbSize } from "../../../system/db_size.ts";
1919 import { resultWords, weekRows } from "../../../maintain/week_line.ts";
2020 import { duties } from "../../../maintain/registry.ts";
21 import { maySwitch, setPlannerSwitch, SWITCH_REFUSED, utcAt, validUntil, type SwitchInput } from "../../../actions/planner_switch.ts";
21 import { maySwitch, setPlannerSwitch, setPullsCeiling, SWITCH_REFUSED, utcAt, validUntil, type SwitchInput } from "../../../actions/planner_switch.ts";
2222 import { pauseSentence, pausedUntil } from "../../../core/planner_pause.ts";
23 import { openPullsCeiling, parsePullsCeiling, pullsCeilingHold } from "../../../core/pulls_ceiling.ts";
2324 import { growthCounts } from "../../../core/growth.ts";
2425 import { sealedScope } from "../../../core/sealed.ts";
2526 import { outsideDependencies } from "../../../keeper/at_boot.ts";
@@ -27,12 +28,12 @@ import { good, bad, repoArg, isAnswer, REPO_ARG, type Tool } from "../shared.ts"
2728
2829 export const tool: Tool = {
2930 name: "system",
30 doc: "the machine the forge runs on, now: CPU, load, memory, disk, network, processes, `largestDirs`: the five largest directories under the forge's data as {at, dirs: [{name, bytes}]} (null while first measured; at most once a minute), `stalls`: the last hour's main-thread stalls by route (`<route> (in flight)` when still running at the wake), or `job:<name>`, as {cause, ms, count}, `readings`: the last 20 minutes' worst loop lag as {at, ms, what} beside `barMs` (100) and `over`, and `readers`: who polls the telemetry and how fast, `{ kind: \"routes\" }`: the 10 slowest budgeted routes as {route, p95Ms, budgetMs, n, slowestPhase}, over budget first; a forge admin, or an agent granted `telemetry:read`. `{ kind: \"csp\" }`: the last 24 h of Content-Security-Policy violations browsers reported, `{ directive, n, newest }` per directive (`newest` the blocked host last counted), most first, counted per UTC hour from `since`, and `scriptErrors` `{ page, where, message, n, last }`, as the security page reads them; a forge admin only. `{ kind: \"bottleneck\" }`: what limits the forge now, as /system/bottleneck: `{ says, limited, rows: [{ id, label, now, ceiling, fraction, detail, lever }], unseen }`; a forge admin only. `{ kind: \"footing\" }`: what the forge stands on (#11685), as /system's \"What the forge stands on\": `forgeNode`, and per piece `{ id, need, what, machine, seen, risk, ifDies, issues }` read from the live cluster, with `risks`, one line per piece not on the forge's machine, and `outside`, what still waits on a hand outside the forge (empty when nothing does); a forge admin only. `{ kind: \"offsite\" }`: the off-site backup lane (#11805), as /system's \"Off-site backup\" and the terminal's: `{ health, says, where, sealed, lastSuccess, newest, error, backupFailure: { cause, bytes, seconds, says } | null, drill: { at, verdict, from, offSite, reason } | null }`; a forge admin only. `{ kind: \"size\" }`: the database's size (#12010), as /system's \"Database size\": `{ fileBytes, walBytes, growth: { perDay, days, readings: [{day, bytes}] }, walk: { at, pageSize, freeBytes, tables: [{name, bytes, rows}], indexes: [{name, table, bytes}] } | null }`, ten of each, largest first, the walk at most an hour old (null while the first runs); a forge admin, or an agent granted `telemetry:read`. `{ kind: \"maintenance\" }`: one row per maintenance worker, 7 days, `{ name, found, acted, last }` (`last` null: not yet run); admin or `telemetry:read`. `{ kind: \"adopted\" }`: the child forges found running at this host's boot, `{ rows: [{ name, pid, at, outcome: kept|dropped, says }] }`, as /system lists them; a forge admin only. `{ kind: \"growth\", repo }`: {openIssues, openPulls, openedToday, closedToday, openedWeek, closedWeek}, as /next's line; with `action` pause (`until`: UTC time within a year, or `chapter: true`: until the open chapter closes, refused with no open chapter; else until switched on) or resume, the planner's switch: a preview, and `confirm:true` does it; the repository's owner, never an agent",
31 doc: "the machine the forge runs on, now: CPU, load, memory, disk, network, processes, `largestDirs`: the five largest directories under the forge's data as {at, dirs: [{name, bytes}]} (null while first measured; at most once a minute), `stalls`: the last hour's main-thread stalls by route (`<route> (in flight)` when still running at the wake), or `job:<name>`, as {cause, ms, count}, `readings`: the last 20 minutes' worst loop lag as {at, ms, what} beside `barMs` (100) and `over`, and `readers`: who polls the telemetry and how fast, `{ kind: \"routes\" }`: the 10 slowest budgeted routes as {route, p95Ms, budgetMs, n, slowestPhase}, over budget first; a forge admin, or an agent granted `telemetry:read`. `{ kind: \"csp\" }`: the last 24 h of Content-Security-Policy violations browsers reported, `{ directive, n, newest }` per directive (`newest` the blocked host last counted), most first, counted per UTC hour from `since`, and `scriptErrors` `{ page, where, message, n, last }`, as the security page reads them; a forge admin only. `{ kind: \"bottleneck\" }`: what limits the forge now, as /system/bottleneck: `{ says, limited, rows: [{ id, label, now, ceiling, fraction, detail, lever }], unseen }`; a forge admin only. `{ kind: \"footing\" }`: what the forge stands on (#11685), as /system's \"What the forge stands on\": `forgeNode`, and per piece `{ id, need, what, machine, seen, risk, ifDies, issues }` read from the live cluster, with `risks`, one line per piece not on the forge's machine, and `outside`, what still waits on a hand outside the forge (empty when nothing does); a forge admin only. `{ kind: \"offsite\" }`: the off-site backup lane (#11805), as /system's \"Off-site backup\" and the terminal's: `{ health, says, where, sealed, lastSuccess, newest, error, backupFailure: { cause, bytes, seconds, says } | null, drill: { at, verdict, from, offSite, reason } | null }`; a forge admin only. `{ kind: \"size\" }`: the database's size (#12010), as /system's \"Database size\": `{ fileBytes, walBytes, growth: { perDay, days, readings: [{day, bytes}] }, walk: { at, pageSize, freeBytes, tables: [{name, bytes, rows}], indexes: [{name, table, bytes}] } | null }`, ten of each, largest first, the walk at most an hour old (null while the first runs); a forge admin, or an agent granted `telemetry:read`. `{ kind: \"maintenance\" }`: one row per maintenance worker, 7 days, `{ name, found, acted, last }` (`last` null: not yet run); admin or `telemetry:read`. `{ kind: \"adopted\" }`: the child forges found running at this host's boot, `{ rows: [{ name, pid, at, outcome: kept|dropped, says }] }`, as /system lists them; a forge admin only. `{ kind: \"growth\", repo }`: {openIssues, openPulls, openedToday, closedToday, openedWeek, closedWeek}, as /next's line; with `action` pause (`until`: UTC time within a year, or `chapter: true`: until the open chapter closes, refused with no open chapter; else until switched on) or resume, the planner's switch: a preview, and `confirm:true` does it; the repository's owner, never an agent; `action` pulls_ceiling with `pulls` (0 off) sets the open-pull ceiling (a preview, and `confirm:true` does it; read as pullsCeiling, pullsHeld)",
3132 description:
3233 "The forge machine now: CPU, memory, disk, network. Admin or telemetry:read; `kind: csp`: 24 h of CSP violations (admin).",
33 inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["csp", "routes", "bottleneck", "footing", "offsite", "size", "maintenance", "growth", "adopted"] }, repo: REPO_ARG, action: { type: "string", enum: ["pause", "resume"] }, until: { type: "string" }, chapter: { type: "boolean" }, confirm: { type: "boolean" } } },
34 inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["csp", "routes", "bottleneck", "footing", "offsite", "size", "maintenance", "growth", "adopted"] }, repo: REPO_ARG, action: { type: "string", enum: ["pause", "resume", "pulls_ceiling"] }, pulls: { type: "integer" }, until: { type: "string" }, chapter: { type: "boolean" }, confirm: { type: "boolean" } } },
3435 writes: true,
35 readsWhen: (args) => args["action"] === undefined || args["confirm"] !== true,
36 readsWhen: (args) => args["action"] === undefined || (args["action"] !== "pulls_ceiling" && args["confirm"] !== true),
3637 async run(ctx, user, args) {
3738 if (args["kind"] !== undefined) {
3839 if (args["kind"] === "routes") {
@@ -48,6 +49,17 @@ export const tool: Tool = {
4849 if (args["kind"] === "growth") {
4950 const repo = repoArg(ctx, user, args);
5051 if (isAnswer(repo)) return repo;
52 if (args["action"] === "pulls_ceiling") {

HIGH: this branch writes without confirm, and readsWhen (confirm !== true) treats the call as a read, so read-only access can set the ceiling. Require confirm:true like pause and resume, and make readsWhen false for this action when pulls is present. Test it.

53 const n = args["pulls"];
54 if (typeof n !== "number" || !Number.isInteger(n)) return bad("invalid", "pulls is a whole number, 0 for off");
55 if (args["confirm"] !== undefined && typeof args["confirm"] !== "boolean") return bad("invalid", "confirm is true or false");
56 if (!maySwitch(ctx.app, user, repo)) return bad("forbidden", SWITCH_REFUSED.forbidden);
57 if (parsePullsCeiling(String(n)) === undefined) return bad("invalid", "pulls is a whole number from 0 to 100000");
58 if (args["confirm"] !== true)
59 return good({ done: false, says: `The open-pull ceiling would be ${n === 0 ? "off" : n} (now ${openPullsCeiling(ctx.app.db, repo.id) || "off"}). Nothing changed; call again with confirm:true to do it.` });
60 const done = setPullsCeiling(ctx.app, user, repo, String(n));
61 return done.ok ? good({ done: true, pullsCeiling: done.value }) : bad(done.error, done.error === "invalid" ? "pulls is a whole number from 0 to 100000" : SWITCH_REFUSED[done.error]);
62 }
5163 if (args["action"] !== undefined) {
5264 const a = args["action"];
5365 if (a !== "pause" && a !== "resume") return bad("invalid", "action is pause or resume");
@@ -69,7 +81,7 @@ export const tool: Tool = {
6981 if (!done.ok) return bad(done.error, SWITCH_REFUSED[done.error]);
7082 return good({ done: true, until: done.value, says: pauseSentence(done.value) });
7183 }
72 return good(growthCounts(ctx.app.db, repo, new Date(), sealedScope(ctx.app.db, repo, user)));
84 return good({ ...growthCounts(ctx.app.db, repo, new Date(), sealedScope(ctx.app.db, repo, user)), pullsCeiling: openPullsCeiling(ctx.app.db, repo.id), pullsHeld: pullsCeilingHold(ctx.app.db, repo.id) });
7385 }
7486 if (args["kind"] === "size") {
7587 const reader = telemetryReader(ctx.app, user);
src/http/server.ts +2 −1
@@ -190,7 +190,7 @@ import { auditCsv, auditPage, auditProbeSubmit } from "../web/pages/audit.ts";
190190 import { apiPage, appApiPage } from "../web/pages/api.ts";
191191 import { flowsCheck, flowsMap, flowsPage, flowsProbe, flowsUpdate } from "../web/pages/flows.ts";
192192 import { findingAccept, findingsPage } from "../web/pages/findings.ts";
193 import { queueCeiling, queueDefer, queuePage, queueSwitch } from "../web/pages/queue.ts";
193 import { queueCeiling, queueDefer, queuePage, queuePullsCeiling, queueSwitch } from "../web/pages/queue.ts";
194194 import { chapterAct, chapterPage, chaptersPage } from "../web/pages/chapters.ts";
195195 import { betAct, betPage, betPropose, betsPage } from "../web/pages/bets.ts";
196196 import { editionPage } from "./edition.ts";
@@ -1500,6 +1500,7 @@ export function buildRouter(): Router<Handler> {
15001500 router.add("GET", "/:owner/:name/queue", queuePage);
15011501 router.add("POST", "/:owner/:name/queue/planner", queueSwitch);
15021502 router.add("POST", "/:owner/:name/queue/ceiling", queueCeiling);
1503 router.add("POST", "/:owner/:name/queue/pulls-ceiling", queuePullsCeiling);
15031504 router.add("POST", "/:owner/:name/queue/defer", queueDefer);
15041505 router.add("GET", "/:owner/:name/chapters", chaptersPage);
15051506 router.add("POST", "/:owner/:name/chapters", chapterAct);
src/tui/screens/queuegrowth.ts +27 −3
@@ -10,12 +10,13 @@
1010 */
1111
1212 import { DEFER_TOO_LATE, deferOldest, hasGate, recentDefer, undoDefer } from "../../actions/defer_aged.ts";
13 import { setCeiling, setPlannerSwitch, SWITCH_REFUSED, switchInput, type SwitchInput } from "../../actions/planner_switch.ts";
13 import { setCeiling, setPlannerSwitch, setPullsCeiling, SWITCH_REFUSED, switchInput, type SwitchInput } from "../../actions/planner_switch.ts";
1414 import { openFlowWords } from "../../core/chapters.ts";
1515 import { growth, oldest, WHO } from "../../core/growth.ts";
1616 import { growthPanelFor } from "../../core/growth_panel.ts";
1717 import { ceilingHold, CEILING_REASON, openCeiling, PAUSE_STOPS, pauseSentence, pausedUntil } from "../../core/planner_pause.ts";
1818 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
19 import { openPullsCeiling, pullsCeilingHold, PULLS_CEILING_REASON, PULLS_HELD_NOTE } from "../../core/pulls_ceiling.ts";
1920 import { sealedScope } from "../../core/sealed.ts";
2021 import type { Ctx, Screen } from "../app/app.ts";
2122 import { binding } from "../app/keys.ts";
@@ -52,6 +53,9 @@ export function queueLines(f: Session, repo: Repo, now = new Date()): string[] {
5253 `Open-issue ceiling: ${openCeiling(f.db, repo.id) === 0 ? "off" : String(openCeiling(f.db, repo.id))}. ${CEILING_REASON}`,
5354 ...(ceilingHold(f.db, repo.id) === null ? [] : [`${ceilingHold(f.db, repo.id)}.`]),
5455 "",
56 `Open-pull ceiling: ${openPullsCeiling(f.db, repo.id) === 0 ? "off" : String(openPullsCeiling(f.db, repo.id))}. ${PULLS_CEILING_REASON}`,
57 ...(pullsCeilingHold(f.db, repo.id) === null ? [] : [`${pullsCeilingHold(f.db, repo.id)}. ${PULLS_HELD_NOTE}`]),
58 "",
5559 ...g.sentences,
5660 ...(flow === null ? [] : [`Chapter: ${flow}.`]),
5761 ...(g.suggest === null ? [] : [g.suggest]),
@@ -82,6 +86,12 @@ export function queueScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
8286 else ctx.toast(done.error === "invalid" ? "The ceiling is a whole number from 0 (off) to 100000." : "Only the owner sets the ceiling.", "danger");
8387 ctx.invalidate();
8488 };
89 const pullsCeil = (raw: string): void => {
90 const done = setPullsCeiling(f.app, f.user, current(), raw);
91 if (done.ok) ctx.toast(done.value === 0 ? "Pull ceiling off." : `Pull ceiling set to ${done.value}.`, "success");
92 else ctx.toast(done.error === "invalid" ? "The ceiling is a whole number from 0 (off) to 100000." : "Only the owner sets the ceiling.", "danger");
93 ctx.invalidate();
94 };
8595 const defer = (): void => {
8696 const aged = oldest(f.db, current().id, sealedScope(f.db, current(), f.user)).issue;
8797 if (aged === null) return ctx.toast("No issue waits to be started.", "danger");
@@ -100,7 +110,7 @@ export function queueScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
100110 title: "Queue",
101111 get keys() {
102112 return mayFlip(f, current())
103 ? [binding(["o"], "pause until on"), binding(["w"], "pause to weekly reset"), binding(["h"], "pause until the chapter closes"), binding(["t"], "pause until a time"), binding(["n"], "switch on"), binding(["c"], "set the ceiling"), binding(["r"], "resume past the ceiling"), binding(["d"], "defer the oldest issue"), binding(["u"], "undo the deferral")]
113 ? [binding(["o"], "pause until on"), binding(["w"], "pause to weekly reset"), binding(["h"], "pause until the chapter closes"), binding(["t"], "pause until a time"), binding(["n"], "switch on"), binding(["c"], "set the ceiling"), binding(["p"], "set the pull ceiling"), binding(["r"], "resume past the ceiling"), binding(["d"], "defer the oldest issue"), binding(["u"], "undo the deferral")]
104114 : [];
105115 },
106116 render(area, s) {
@@ -132,6 +142,20 @@ export function queueScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
132142 );
133143 return true;
134144 }
145 if (e.key === "p") {
146 ctx.push(
147 promptScreen(ctx, screen, {
148 title: "Open-pull ceiling",
149 label: "A whole number, 0 for off",
150 placeholder: "20",
151 onSubmit: (raw) => {
152 pullsCeil(raw);
153 return undefined;
154 },
155 }),
156 );
157 return true;
158 }
135159 if (e.key === "t") {
136160 ctx.push(
137161 promptScreen(ctx, screen, {
@@ -161,7 +185,7 @@ export function queueScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
161185 export function growthPanelLines(f: Session, repo: Repo, now = new Date()): string[] {
162186 const panel = growthPanelFor(f.db, repo, f.user, f.user !== undefined && canAdmin(f.db, repo, f.user), now);
163187 if (panel === null) return ["An admin of this repository reads its growth here."];
164 return [...panel.sentences, pauseSentence(panel.until), "Queue has the days and the planner's switch."];
188 return [...panel.sentences, pauseSentence(panel.until), ...(panel.pullsHeld === null ? [] : [`${panel.pullsHeld}.`]), "Queue has the days and the planner's switch."];
165189 }
166190
167191 export function growthPanelScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
src/web/pages/growth_panel.ts +1
@@ -35,6 +35,7 @@ export function growthBody(ctx: Ctx, repo: Repo): Html | null {
3535 if (panel === null) return null;
3636 return html`<span id="growth-panel" data-growth-panel>${panel.sentences.join(" ")}
3737 <span data-planner-state="${panel.until === null ? "on" : "paused"}">${pauseSentence(panel.until)}</span>
38 ${panel.pullsHeld === null ? null : html`<span data-pulls-paused>${panel.pullsHeld.charAt(0).toUpperCase()}${panel.pullsHeld.slice(1)}.</span>`}
outdated

data-pulls-held here is bare, but on the queue page it is yes/no. Use one meaning.

3839 <a href="${repoBase(repo)}/queue">Queue</a></span>`;
3940 }
4041
src/web/pages/queue.ts +34 −3
@@ -6,9 +6,10 @@
66 */
77
88 import { deferOldest, hasGate, recentDefer, undoDefer } from "../../actions/defer_aged.ts";
9 import { setCeiling, setPlannerSwitch, SWITCH_REFUSED, switchInput } from "../../actions/planner_switch.ts";
9 import { setCeiling, setPlannerSwitch, setPullsCeiling, SWITCH_REFUSED, switchInput } from "../../actions/planner_switch.ts";
1010 import { openFlowWords } from "../../core/chapters.ts";
1111 import { growth, oldest, WHO, type Growth } from "../../core/growth.ts";
12 import { openPullsCeiling, pullsCeilingHold, PULLS_CEILING_REASON, PULLS_HELD_NOTE } from "../../core/pulls_ceiling.ts";
1213 import { ceilingHold, CEILING_HELD_NOTE, CEILING_REASON, openCeiling, PAUSE_STOPS, pauseSentence, pausedUntil } from "../../core/planner_pause.ts";
1314 import { canAdmin, type Repo } from "../../core/repos.ts";
1415 import { sealedScope } from "../../core/sealed.ts";
@@ -71,11 +72,12 @@ function switchRow(repo: Repo, until: string | null, owner: boolean): Html {
7172 * planner, the reason otherwise. The owner gets the two forms, plain buttons beside the switch's
7273 * one primary.
7374 */
74 function ceilingRow(repo: Repo, ceiling: number, held: string | null, owner: boolean): Html {
75 function ceilingRow(repo: Repo, ceiling: number, held: string | null, owner: boolean, pulls: Html): Html {
7576 const post = `${repoBase(repo)}/queue/ceiling`;
7677 const line = held === null ? CEILING_REASON : `${held.charAt(0).toUpperCase()}${held.slice(1)}. ${CEILING_HELD_NOTE}`;
7778 return html`<ul class="list setting-list" data-planner-ceiling>
7879 ${row({ title: "Open-issue ceiling", meta: html`<span data-ceiling-held="${held === null ? "no" : "yes"}">${line}</span>`, trail: badge(ceiling === 0 ? "off" : String(ceiling)) })}
80 ${pulls}
7981 </ul>
8082 ${owner
8183 ? html`<form method="post" action="${post}" class="bar"><input type="hidden" name="mode" value="set">
@@ -85,6 +87,20 @@ function ceilingRow(repo: Repo, ceiling: number, held: string | null, owner: boo
8587 : null}`;
8688 }
8789
90 /** The pull ceiling's row, which sits in the issue ceiling's list, and its form for the owner. */
91 function pullsRow(ceiling: number, held: string | null): Html {

Principle 1: the reason is printed in full and again after the paused line. Once is enough.

92 const line = held === null ? PULLS_CEILING_REASON : `${held.charAt(0).toUpperCase()}${held.slice(1)}. ${PULLS_HELD_NOTE}`;
93 return row({ title: "Open-pull ceiling", meta: html`<span data-pulls-ceiling-held="${held === null ? "no" : "yes"}">${line}</span>`, trail: badge(ceiling === 0 ? "off" : String(ceiling)) });
94 }
95
96 function pullsForm(repo: Repo, ceiling: number, owner: boolean): Html | null {
97 return owner
98 ? html`<form method="post" action="${repoBase(repo)}/queue/pulls-ceiling" class="bar">
99 ${field({ label: "Pull ceiling", name: "value", value: String(ceiling), pattern: "[0-9]{1,6}" })}
100 ${btn("Set the pull ceiling")}</form>`
101 : null;
102 }
103
88104 const ago = (iso: string, now: Date) => `${Math.max(0, Math.floor((now.getTime() - Date.parse(iso)) / 86_400_000))} days old`;
89105
90106 // GET /:owner/:name/queue
@@ -96,6 +112,7 @@ export function queuePage(ctx: Ctx): Response {
96112 const now = new Date();
97113 const user = ctx.auth.user;
98114 const owner = user !== undefined && user.kind !== "agent" && canAdmin(ctx.app.db, repo, user);
115 const pullsCeiling = openPullsCeiling(ctx.app.db, repo.id);
99116 const scope = sealedScope(ctx.app.db, repo, user);
100117 const g = growth(ctx.app.db, repo, DAYS, now, scope);
101118 const age = oldest(ctx.app.db, repo.id, scope);
@@ -113,7 +130,8 @@ export function queuePage(ctx: Ctx): Response {
113130 const body = html`${repoHeader(ctx, repo, "issues")}
114131 ${pageHead("Queue", { sub: "Is the work growing or shrinking?" })}
115132 ${switchRow(repo, until, owner)}
116 ${ceilingRow(repo, openCeiling(ctx.app.db, repo.id), ceilingHold(ctx.app.db, repo.id), owner)}
133 ${ceilingRow(repo, openCeiling(ctx.app.db, repo.id), ceilingHold(ctx.app.db, repo.id), owner, pullsRow(pullsCeiling, pullsCeilingHold(ctx.app.db, repo.id)))}
134 ${pullsForm(repo, pullsCeiling, owner)}
117135 <p><a href="${base}/chapters">Chapters</a></p>
118136 ${aged.length === 0 ? null : html`<ul class="list setting-list" data-aged>${aged}</ul>`}
119137 ${growthRows(g, openFlowWords(ctx.app.db, repo.id, scope, now))}`;
@@ -152,6 +170,19 @@ export async function queueCeiling(ctx: Ctx): Promise<Response> {
152170 return flashTo(ctx, back, { message: mode === "set" ? (done.value === 0 ? "Ceiling off." : `Ceiling set to ${done.value}.`) : "The planner may open one plan past the ceiling." });
153171 }
154172
173 // POST /:owner/:name/queue/pulls-ceiling
174 export async function queuePullsCeiling(ctx: Ctx): Promise<Response> {
175 const repo = loadRepo(ctx);
176 if (!repo) return notFoundPage(ctx);
177 const form = await readForm(ctx, "rw");
178 if (form instanceof Response) return form;
179 const back = backTo(form, `${repoBase(repo)}/queue`);
180 const done = setPullsCeiling(ctx.app, ctx.auth.user, repo, formField(form, "value"));
181 if (!done.ok)
182 return flashTo(ctx, back, { tone: "danger", message: done.error === "invalid" ? "The ceiling is a whole number from 0 (off) to 100000." : "Only the owner sets the ceiling." });
183 return flashTo(ctx, back, { message: done.value === 0 ? "Pull ceiling off." : `Pull ceiling set to ${done.value}.` });
184 }
185
155186 // POST /:owner/:name/queue/defer
156187 export async function queueDefer(ctx: Ctx): Promise<Response> {
157188 const repo = loadRepo(ctx);
test/growth-counts.test.ts +35 −1
@@ -6,6 +6,9 @@ import { join } from "node:path";
66 import { createApp, type App } from "../src/app.ts";
77 import { openIssue } from "../src/actions/issues.ts";
88 import { createRepo } from "../src/actions/repos.ts";
9 import { createAgent } from "../src/actions/crew.ts";
10 import { getAgentByName } from "../src/core/agents.ts";
11 import { openPullsCeiling } from "../src/core/pulls_ceiling.ts";
912 import { createSession } from "../src/core/sessions.ts";
1013 import { createToken } from "../src/core/tokens.ts";
1114 import { createUser, type User } from "../src/core/users.ts";
@@ -107,5 +110,36 @@ test("system kind growth answers the same numbers", async () => {
107110 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "system", arguments: { kind: "growth", repo: "alice/g" } } }),
108111 });
109112 const body: any = await res.json();
110 expect(JSON.parse(body.result.content[0].text)).toEqual(growthCounts(app.db, repo, new Date()));
113 expect(JSON.parse(body.result.content[0].text)).toEqual({ ...growthCounts(app.db, repo, new Date()), pullsCeiling: 20, pullsHeld: null });
114 });
115
116 const setCeilingCall = async (bearer: string, repoName: string, extra: Record<string, unknown>) => {
117 const res = await fetch(`${servers.url}/mcp`, {
118 method: "POST",
119 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${bearer}` },
120 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "system", arguments: { kind: "growth", repo: repoName, action: "pulls_ceiling", pulls: 7, ...extra } } }),
121 });
122 return (await res.json()) as any;
123 };
124
125 test("the pull ceiling is previewed without confirm, set with it, and refused to an agent or a read-only token (#15805)", async () => {
126 const ceiling = () => openPullsCeiling(app.db, repo.id);
127 expect(ceiling()).toBe(20);
128 const rw = createToken(app.db, alice.id, "rw", "rw");
129 const preview = await setCeilingCall(rw.token, "alice/g", {});
130 expect(JSON.parse(preview.result.content[0].text).done).toBe(false);
131 expect(ceiling()).toBe(20);
132 const ro = createToken(app.db, alice.id, "ro", "ro");
133 const refused = await setCeilingCall(ro.token, "alice/g", { confirm: true });
134 expect(refused.error !== undefined || refused.result?.isError === true || JSON.parse(refused.result.content[0].text).done !== true).toBe(true);
135 expect(ceiling()).toBe(20);
136 const bot = await createAgent(app, alice, { username: "bot" });
137 if (!bot.ok) throw new Error(String(bot.error));
138 const agent = createToken(app.db, getAgentByName(app.db, "bot")!.user.id, "rw", "rw");
139 const denied = await setCeilingCall(agent.token, "alice/g", { confirm: true });
140 expect(JSON.stringify(denied)).not.toContain('"done":true');
141 expect(ceiling()).toBe(20);
142 const done = await setCeilingCall(rw.token, "alice/g", { confirm: true });
143 expect(JSON.parse(done.result.content[0].text)).toMatchObject({ done: true, pullsCeiling: 7 });
144 expect(ceiling()).toBe(7);
111145 });
test/open-pulls-ceiling.test.ts added +129
@@ -0,0 +1,129 @@
1 /**
2 * The open-pull ceiling (#15805): at or over it a new issue starts no builder run, with the
3 * reason said in words, while a review run and the planner's run still start; only the owner sets
4 * it, it is readable and settable through the MCP's growth kind, and the growth panel, /flow and
5 * the queue page say "paused: 3 of 2 pulls open".
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 { addToCrew, createAgent } from "../src/actions/crew.ts";
13 import { openIssue } from "../src/actions/issues.ts";
14 import { setPullsCeiling } from "../src/actions/planner_switch.ts";
15 import { openPull } from "../src/actions/pulls.ts";
16 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
17 import { getAgentByName, type Agent } from "../src/core/agents.ts";
18 import { growthPanelFor } from "../src/core/growth_panel.ts";
19 import { getIssueById, type Issue } from "../src/core/issues.ts";
20 import { DEFAULT_PULLS_CEILING, openPullsCeiling, pullsCeilingHold } from "../src/core/pulls_ceiling.ts";
21 import { getRepoById, type Repo } from "../src/core/repos.ts";
22 import { createUser, type User } from "../src/core/users.ts";
23 import { ensureDirectionIssue } from "../src/crew/autonomy.ts";
24 import { queueAgentRun } from "../src/crew/dispatch.ts";
25 import { plannerHeld } from "../src/flow/planner_held.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27 import { seatAs } from "./helpers/seat.ts";
28
29 quietLogs();
30
31 let dataDir: string;
32 let app: App;
33 let alice: User;
34 let repo: Repo;
35 let builder: Agent;
36 let planner: Agent;
37 let reviewer: Agent;
38 let issue: Issue;
39 let pulls: Issue[] = [];
40
41 const fresh = () => getRepoById(app.db, repo.id)!;
42
43 beforeAll(async () => {
44 dataDir = await mkdtemp(join(tmpdir(), "forge-pulls-ceiling-"));
45 app = createApp({ dataDir, port: 0 });
46 const a = await createUser(app.db, {
47 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
48 password: "a-good-passphrase", adminIfFirst: true,
49 });
50 if (!a.ok) throw new Error(a.error);
51 alice = a.value;
52 const made = await createRepo(app, alice, { name: "notes", visibility: "public" });
53 if (!made.ok) throw new Error(String(made.error));
54 repo = made.value;
55 const first = await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "package.json", content: `{"name":"notes"}\n` }] });
56 if (!first.ok) throw new Error(JSON.stringify(first.error));
57 for (const name of ["b1", "p1", "r1"]) {
58 const m = await createAgent(app, alice, { username: name });
59 if (!m.ok) throw new Error(String(m.error));
60 expect(addToCrew(app, alice, repo, name).ok).toBe(true);
61 }
62 builder = getAgentByName(app.db, "b1")!;
63 planner = getAgentByName(app.db, "p1")!;
64 expect(seatAs(app.db, repo.id, planner.user.id, "planner")).toBe(true);
65 reviewer = getAgentByName(app.db, "r1")!;
66 expect(seatAs(app.db, repo.id, reviewer.user.id, "reviewer")).toBe(true);
67 const opened = openIssue(app, alice, fresh(), { title: "Rename a note" });
68 if (!opened.ok) throw new Error(String(opened.error));
69 issue = opened.value;
70 for (let n = 0; n < 3; n++) {
71 const pushed = await commitToBranch(app, alice, fresh(), { branch: `b${n}`, message: `B${n}`, files: [{ path: `f${n}.md`, content: "x\n" }] });
72 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
73 const pull = await openPull(app, alice, fresh(), { title: `Pull ${n}`, baseBranch: "main", headBranch: `b${n}` });
74 if (!pull.ok) throw new Error(JSON.stringify(pull.error));
75 pulls.push(getIssueById(app.db, pull.value.id)!);
76 }
77 });
78
79 afterAll(async () => {
80 await rm(dataDir, { recursive: true, force: true });
81 });
82
83 describe("the open-pull ceiling", () => {
84 test("it defaults to 20, and only the owner sets it", () => {
85 expect(DEFAULT_PULLS_CEILING).toBe(20);
86 expect(openPullsCeiling(app.db, repo.id)).toBe(20);
87 expect(pullsCeilingHold(app.db, repo.id)).toBeNull();
88 expect(setPullsCeiling(app, builder.user, fresh(), "2")).toEqual({ ok: false, error: "forbidden" });
89 for (const bad of ["-1", "x", "1.5", "", "1000000"]) expect(setPullsCeiling(app, alice, fresh(), bad)).toEqual({ ok: false, error: "invalid" });
90 expect(setPullsCeiling(app, alice, fresh(), "2")).toEqual({ ok: true, value: 2 });
91 expect(openPullsCeiling(app.db, repo.id)).toBe(2);
92 });
93
94 test("with the ceiling at 2 and three pulls open, a new issue's run is refused while a review starts", () => {
95 expect(pullsCeilingHold(app.db, repo.id)).toBe("paused: 3 of 2 pulls open");
96 expect(queueAgentRun(app, fresh(), issue, builder, "assigned")).toBeUndefined();
97 expect(queueAgentRun(app, fresh(), pulls[0]!, reviewer, "review")).toBeDefined();
98 });
99
100 test("the panel, /flow and the planner's own run say or keep going", () => {
101 const panel = growthPanelFor(app.db, fresh(), alice, true);
102 expect(panel?.pullsHeld).toBe("paused: 3 of 2 pulls open");
103 expect(plannerHeld(app.db)).toEqual([{ repo: "alice/notes", cause: "paused: 3 of 2 pulls open" }]);
104 // a planning run is exempt: it splits, it never builds
105 const direction = ensureDirectionIssue(app, alice, fresh());
106 expect(direction).toBeDefined();
107 expect(queueAgentRun(app, fresh(), direction!, planner, "assigned")).toBeDefined();
108 });
109
110 test("at 4 the issue starts; 0 turns it off", () => {
111 setPullsCeiling(app, alice, fresh(), "4");
112 expect(pullsCeilingHold(app.db, repo.id)).toBeNull();
113 setPullsCeiling(app, alice, fresh(), "3");
114 expect(pullsCeilingHold(app.db, repo.id)).toBe("paused: 3 of 3 pulls open");
115 setPullsCeiling(app, alice, fresh(), "0");
116 expect(pullsCeilingHold(app.db, repo.id)).toBeNull();
117 expect(queueAgentRun(app, fresh(), issue, builder, "assigned")).toBeDefined();
118 });
119
120 test("the kept panel says the paused line from now, not from when it was kept", () => {
121 setPullsCeiling(app, alice, fresh(), "3");
122 expect(growthPanelFor(app.db, fresh(), alice, true)?.pullsHeld).toBe("paused: 3 of 3 pulls open");
123 // a pull closing is no ceiling setter: the kept panel must still follow the count
124 app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(pulls[0]!.id);
125 expect(growthPanelFor(app.db, fresh(), alice, true)?.pullsHeld).toBeNull();
126 app.db.query("UPDATE issue SET state = 'open' WHERE id = ?1").run(pulls[0]!.id);
127 expect(growthPanelFor(app.db, fresh(), alice, true)?.pullsHeld).toBe("paused: 3 of 3 pulls open");
128 });
129 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs