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

The crew says why it is waiting: the pace's reason on the tick, in flow why, and in the idle words #16722

Merged opened this

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

Merged

flow/pace-reason → main 0 commits 2 threads · 2 unresolved

  • Merged. flow/pace-reason was merged into main as ab7816e.

Review

Sign in to review this change.
7 files changed +188 −37
src/crew/autonomy.ts +13
@@ -432,6 +432,16 @@ export function repoPace(app: App, repo: Repo, now = new Date(), crew = true, pi
432432 return week !== null && week.slots === 0 ? { ...limited, slots: 0, reason: week.sentence } : limited;
433433 }
434434
435 /**
436 * Why the crew's pace allows no run here now, in a sentence ("espo-corp's 5-hour window is full
437 * until …", the week's sentence), or undefined while one may start: the words beside a tick that
438 * did `waiting`, the idle reason and the flow's why. `crew` as `repoPace`'s: a new pick or not.
439 */
440 export function paceHold(app: App, repo: Repo, now = new Date(), crew = true): string | undefined {
441 const paced = repoPace(app, repo, now, crew);
442 return paced.slots > 0 ? undefined : paced.reason || "no run may start at the crew's pace";
443 }
444
435445 /** The builder slots free now: none while paused, else the paced slots less what is slotted. */
436446 function freeSlots(app: App, repo: Repo, now: Date): number {
437447 if (autonomyStatus(app, repo, now).paused !== null) return 0;
@@ -1472,6 +1482,7 @@ export async function autonomyTick(
14721482 const staleToday = closedToday(app, current.id, now);
14731483 // Says when the governor lowers the slots (#6375); one feed item per change.
14741484 const governor = announceGovernor(app, current, now);
1485 const paceWhy = did === "waiting" ? paceHold(app, current, now) : undefined;
14751486 log.info("tick", {
14761487 repo: `${repo.ownerName}/${repo.name}`,
14771488 did,
@@ -1522,6 +1533,8 @@ export async function autonomyTick(
15221533 spent: status.spentTodayUsd.toFixed(2),
15231534 ...(status.week === null ? {} : { week: `${status.week.usedPct}/${status.week.mayUsePct}%` }),
15241535 ...(status.paused === null ? {} : { paused: status.paused }),
1536 // Why the pace started nothing, when it did not (`paceHold`): the account and its reset.
1537 ...(paceWhy === undefined ? {} : { pace: paceWhy }),
15251538 // Starts after the first, and how many followed a crash (#3708).
15261539 restarts: boots.restarts,
15271540 ...(boots.unclean === 0 ? {} : { unclean: boots.unclean }),
src/crew/idle_reason.ts +6 −2
@@ -24,6 +24,9 @@ import { heldNow, HOLDS } from "./held.ts";
2424 import { pace } from "./pacing.ts";
2525 import { redUnattended } from "./red_unattended.ts";
2626
27 /** The idle word when every granted subscription's window is full; the pace's reason follows it. */
28 export const NO_HEADROOM = "no subscription with headroom";
29
2730 export interface IdleReason {
2831 readonly word: string;
2932 readonly href: string;
@@ -45,8 +48,9 @@ export function whatBlocks(app: App, repo: Repo, now: Date): IdleReason | null {
4548 return s === undefined ? [] : [{ name: a.name, standing: s }];
4649 });
4750 // Whether a window has room does not depend on what a run costs.
48 if (pace(accounts, repo.autonomySlots, 1, now).slots === 0)
49 return { word: "no subscription with headroom", href: "/subscriptions" };
51 const paced = pace(accounts, repo.autonomySlots, 1, now);
52 if (paced.slots === 0)
53 return { word: `${NO_HEADROOM}${paced.reason === "" ? "" : `: ${paced.reason}`}`, href: "/subscriptions" };
5054 }
5155 return null;
5256 }
src/flow/why.ts +25 −29
@@ -6,7 +6,6 @@
66 * from it. The first cause that holds is the answer: later ones are behind it.
77 */
88
9 import type { Database } from "bun:sqlite";
109 import type { App } from "../app.ts";
1110 import { listCrewRoles } from "../core/agents.ts";
1211 import { repoGraph } from "../core/dependencies.ts";
@@ -16,8 +15,8 @@ import type { Repo } from "../core/repos.ts";
1615 import { refTip } from "../git/read.ts";
1716 import { resolveOid } from "../git/merge.ts";
1817 import { checkSummary } from "../core/runs.ts";
19 import { standings } from "../core/standing.ts";
2018 import { ceilingHitAt, forgeCeiling } from "./ceiling.ts";
19 import { paceHold } from "../crew/autonomy.ts";
2120 import { heldNow, mapHolds } from "../crew/held.ts";
2221 import { nextOfPull, type Actor } from "./next_actor.ts";
2322 import { wallWords } from "./wall_wait.ts";
@@ -51,7 +50,8 @@ export interface WhyFacts {
5150 readonly blockedBy?: readonly number[];
5251 readonly laterGate?: string;
5352 readonly builders?: number;
54 readonly noHeadroom?: boolean;
53 /** Why this repository's pace starts no run (`paceHold`): the full window and when it resets. */
54 readonly paced?: string;
5555 readonly redCheck?: boolean;
5656 readonly waitingReview?: boolean;
5757 /** What the access wall holds the pull for, in plain words (#7847). */
@@ -114,10 +114,10 @@ const RULES: Readonly<Record<CauseName, (f: WhyFacts) => Omit<Cause, "name"> | n
114114 ? { says: "No builder is on this repository's crew.", clears: "add a builder to the crew." }
115115 : null,
116116 no_headroom: (f) =>
117 f.noHeadroom === true && agentActs(f)
117 f.paced !== undefined && agentActs(f)
118118 ? {
119 says: "Every subscription's window is spent down to the share kept for people.",
120 clears: "wait for the window to reset, lower the headroom, or add a subscription.",
119 says: `The crew is at its pace: ${f.paced}.`,
120 clears: "wait for the window or the week to reset, lower the headroom, or grant another subscription.",
121121 }
122122 : null,
123123 red_check: (f) =>
@@ -147,37 +147,33 @@ export interface Why {
147147 readonly next?: { readonly who: Actor; readonly why: string };
148148 }
149149
150 /** True when every subscription has used what the crew may spend; false with none. */
151 function headroomSpent(db: Database, now: Date): boolean {
152 const ids = db.query<{ id: string }, []>("SELECT id FROM subscription").all().map((r) => r.id);
153 if (ids.length === 0) return false;
154 const read = standings(db, ids, now);
155 return ids.every((id) =>
156 (read.get(id)?.windows ?? []).some((w) => w.crewRemaining !== null && w.crewRemaining.value <= 0),
157 );
158 }
159
160 type Shared = Pick<WhyFacts, "ceilingUsd" | "builders" | "noHeadroom">;
150 type Shared = Pick<WhyFacts, "ceilingUsd" | "builders" | "paced">;
161151
162152 /** The facts that hold for the whole forge, read once for a batch. */
163 function forgeFacts(app: App, now: Date): Pick<Shared, "ceilingUsd" | "noHeadroom"> {
153 function forgeFacts(app: App, now: Date): Pick<Shared, "ceilingUsd"> {
164154 const cap = forgeCeiling(app.config);
165 return {
166 ...(cap !== null && ceilingHitAt(app.db, now, cap) !== null ? { ceilingUsd: cap } : {}),
167 noHeadroom: headroomSpent(app.db, now),
168 };
155 return cap !== null && ceilingHitAt(app.db, now, cap) !== null ? { ceilingUsd: cap } : {};
169156 }
170157
171158 const buildersOf = (app: App, repo: Repo): number =>
172159 listCrewRoles(app.db, repo.id).filter((c) => c.role === "builder").length;
173160
174 function sharedFacts(app: App, repo: Repo, now: Date): Shared {
175 return { ...forgeFacts(app, now), builders: buildersOf(app, repo) };
161 /**
162 * This repository's pace, when it starts nothing: a new build's (`crew`), or work on an open
163 * pull's.
164 */
165 function pacedFact(app: App, repo: Repo, now: Date, crew: boolean): Pick<Shared, "paced"> {
166 const held = paceHold(app, repo, now, crew);
167 return held === undefined ? {} : { paced: held };
168 }
169
170 function sharedFacts(app: App, repo: Repo, now: Date, crew = false): Shared {
171 return { ...forgeFacts(app, now), builders: buildersOf(app, repo), ...pacedFact(app, repo, now, crew) };
176172 }
177173
178174 /** Why the repository's builders are held, whatever the issue. */
179175 export function whyRepo(app: App, repo: Repo, now = new Date()): Why {
180 return { cause: firstCause({ actor: "builder", ...sharedFacts(app, repo, now) }) };
176 return { cause: firstCause({ actor: "builder", ...sharedFacts(app, repo, now, true) }) };
181177 }
182178
183179 /** Why an open issue is not moving. */
@@ -203,7 +199,7 @@ export function whyIssue(app: App, repo: Repo, issue: Issue, now = new Date()):
203199 ...(twin !== undefined ? { twin } : {}),
204200 blockedBy: openBlockers,
205201 ...(later !== undefined ? { laterGate: later } : {}),
206 ...sharedFacts(app, repo, now),
202 ...sharedFacts(app, repo, now, true),
207203 }),
208204 };
209205 }
@@ -250,12 +246,12 @@ export function whyPulls(
250246 now = new Date(),
251247 ): Why[] {
252248 const forge = forgeFacts(app, now);
253 const builders = new Map<string, number>();
249 const perRepo = new Map<string, Pick<Shared, "builders" | "paced">>();
254250 return rows.map(({ repo, pull }) => {
255 if (!builders.has(repo.id)) builders.set(repo.id, buildersOf(app, repo));
251 if (!perRepo.has(repo.id)) perRepo.set(repo.id, { builders: buildersOf(app, repo), ...pacedFact(app, repo, now, false) });
256252 return whyPull(app, repo, pull, { headOid: pull.headOid, conflicts: 0 }, now, {
257253 ...forge,
258 builders: builders.get(repo.id)!,
254 ...perRepo.get(repo.id)!,
259255 });
260256 });
261257 }
test/home-builders-idle.test.ts +3 −3
@@ -128,8 +128,8 @@ test("no subscription with headroom: the granted account's window is full", asyn
128128 // The write stamp is the same at both clocks; only the window's reset moves.
129129 const stampBefore = writeStamp(app.db);
130130 const later = new Date(now + 2 * 3_600_000);
131 expect(idleReason(app, new Date(now))?.word).toBe("no subscription with headroom");
132 expect(idleReason(app, later)?.word).not.toBe("no subscription with headroom");
131 expect(idleReason(app, new Date(now))?.word).toStartWith("no subscription with headroom: espo's 5-hour window is full until ");
132 expect(idleReason(app, later)?.word ?? "").not.toContain("no subscription with headroom");
133133 expect(writeStamp(app.db)).toBe(stampBefore);
134134 expect(tile(page)).toContain("no subscription with headroom");
135135 expect(tile(page)).toContain('href="/subscriptions"');
@@ -141,7 +141,7 @@ test("week spent outranks the others: dollars alone do not, the provider's week
141141 claimRun(app.db, spent.id);
142142 finishRun(app.db, spent.id, { state: "ok", summary: "done", costUsd: 12 });
143143 // $12 today is no ceiling: the reason is still the subscription's.
144 expect(idleReason(app, new Date())?.word).toBe("no subscription with headroom");
144 expect(idleReason(app, new Date())?.word).toStartWith("no subscription with headroom");
145145 const at = Date.now();
146146 for (const a of grantedAccounts(app.db, repo.id, repo.ownerId))
147147 noteMeasure(app.db, a.id, { window: "week", usedPct: 100, resetsAt: new Date(at + 3 * 86_400_000).toISOString(), observedAt: new Date(at).toISOString() });
test/idle-reason.test.ts +2 −1
@@ -119,7 +119,8 @@ describe("idleReason", () => {
119119 observedAt: "2026-10-02T11:00:00.000Z",
120120 said: "You've hit your session limit",
121121 });
122 expect(idleReason(app, NOW)).toEqual({ word: "no subscription with headroom", href: "/subscriptions" });
122 // The pace's own reason follows: which account, which window, until when.
123 expect(idleReason(app, NOW)).toEqual({ word: expect.stringMatching(/^no subscription with headroom: acct\d+'s 5-hour window is full until /), href: "/subscriptions" });
123124 });
124125
125126 test("nothing ready: no open issue, or every one waits on another", () => {
test/mcp-flow-why.test.ts +2 −2
@@ -30,7 +30,7 @@ describe("the list of causes", () => {
3030 ["blocked_by", { actor: "builder", blockedBy: [4, 9] }],
3131 ["later_gate", { actor: "builder", laterGate: "behind the Later gate" }],
3232 ["no_builder", { actor: "builder", builders: 0 }],
33 ["no_headroom", { actor: "builder", noHeadroom: true }],
33 ["no_headroom", { actor: "builder", paced: "espo's 5-hour window is full until 14:00 UTC" }],
3434 ["red_check", { actor: "builder", redCheck: true }],
3535 ["waiting_review", { actor: "reviewer", waitingReview: true }],
3636 ];
@@ -44,7 +44,7 @@ describe("the list of causes", () => {
4444
4545 test("every cause in the list has a case, and the first in order wins", () => {
4646 expect(cases.map(([n]) => n)).toEqual([...CAUSES]);
47 expect(firstCause({ actor: "builder", noHeadroom: true, redCheck: true })?.name).toBe("no_headroom");
47 expect(firstCause({ actor: "builder", paced: "the week is spent", redCheck: true })?.name).toBe("no_headroom");
4848 expect(firstCause({ actor: "queue" })).toBeNull();
4949 // A ceiling does not hold a pull that only waits for the queue.
5050 expect(firstCause({ actor: "queue", ceilingUsd: 5 })).toBeNull();
test/pace-reason.test.ts added +137
@@ -0,0 +1,137 @@
1 /**
2 * A tick that starts nothing because the crew's pace allows no run says why: the tick line carries
3 * the pace's reason beside `did=waiting` (the account and when its window resets), and so do the
4 * flow's why and the idle reason. Before, the line read `did=waiting startable=151 slots=8` and
5 * nothing named the full window.
6 */
7 import { afterAll, beforeAll, describe, expect, spyOn, 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 { addToCrew, createAgent } from "../src/actions/crew.ts";
12 import { openIssue } from "../src/actions/issues.ts";
13 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import type { Issue } from "../src/core/issues.ts";
16 import { getRepoById, listAutonomousRepos, type Repo } from "../src/core/repos.ts";
17 import { noteLimit } from "../src/core/standing.ts";
18 import { addSubscription, setGrants } from "../src/core/subscriptions.ts";
19 import { createUser, getUserByName, type User } from "../src/core/users.ts";
20 import { autonomyTick, driveRepo, paceHold } from "../src/crew/autonomy.ts";
21 import { idleReason } from "../src/crew/idle_reason.ts";
22 import { whyIssue, whyPulls, whyRepo } from "../src/flow/why.ts";
23 import { openPull } from "../src/actions/pulls.ts";
24 import { createRun } from "../src/core/runs.ts";
25 import { seatAs } from "./helpers/seat.ts";
26
27 const FULL = "espo's 5-hour window is full until ";
28
29 let dataDir: string;
30 let app: App;
31 let alice: User;
32 let repo: Repo;
33 let renderer: Issue;
34
35 const fresh = () => getRepoById(app.db, repo.id)!;
36
37 beforeAll(async () => {
38 dataDir = await mkdtemp(join(tmpdir(), "forge-pace-reason-"));
39 app = createApp({ dataDir, port: 0 });
40 const a = await createUser(app.db, {
41 origin: "seed",
42 trusted: true,
43 username: "alice",
44 email: "[email protected]",
45 password: "a-good-passphrase",
46 adminIfFirst: true,
47 });
48 if (!a.ok) throw new Error(a.error);
49 alice = a.value;
50 const made = await createRepo(app, alice, { name: "engine", visibility: "private" });
51 if (!made.ok) throw new Error(String(made.error));
52 await commitToBranch(app, alice, made.value, { message: "Start", files: [{ path: "README.md", content: "# engine\n" }] });
53 for (const name of ["atlas", "bolt"]) {
54 const agent = await createAgent(app, alice, { username: name });
55 if (!agent.ok) throw new Error(String(agent.error));
56 expect(addToCrew(app, alice, made.value, name).ok).toBe(true);
57 }
58 seatAs(app.db, made.value.id, getUserByName(app.db, "atlas")!.id, "planner");
59 const set = await updateRepoSettings(app, alice, made.value, {
60 autonomy: "assisted",
61 autonomyDirection: "Keep the engine small.",
62 autonomySlots: 2,
63 autonomyBy: alice.id,
64 });
65 if (!set.ok) throw new Error(JSON.stringify(set.error));
66 repo = getRepoById(app.db, made.value.id)!;
67 const opened = openIssue(app, alice, repo, { title: "Renderer" });
68 if (!opened.ok) throw new Error(String(opened.error));
69 renderer = opened.value;
70 // The one granted account's 5-hour window is full for another hour.
71 const sub = addSubscription(app.db, dataDir, { name: "espo", token: "sk-ant-oat01-" + "x".repeat(24) });
72 if (!sub.ok) throw new Error(sub.error);
73 setGrants(app.db, repo.id, "", [sub.value.id]);
74 const now = Date.now();
75 noteLimit(app.db, sub.value.id, {
76 window: "5h",
77 resetsAt: new Date(now + 3_600_000).toISOString(),
78 observedAt: new Date(now).toISOString(),
79 said: "limit",
80 });
81 });
82
83 afterAll(async () => {
84 app.close();
85 await rm(dataDir, { recursive: true, force: true });
86 });
87
88 describe("the pace's reason, wherever a still crew is explained", () => {
89 test("the pace allows no run, and says which window until when", async () => {
90 expect(paceHold(app, fresh())).toStartWith(FULL);
91 expect(await driveRepo(app, fresh())).toBe("waiting");
92 });
93
94 test("the tick line carries it beside did=waiting", async () => {
95 for (const other of listAutonomousRepos(app.db))
96 if (other.id !== repo.id) app.db.query("UPDATE repo SET autonomy = 'off' WHERE id = ?1").run(other.id);
97 const lines: string[] = [];
98 const spy = spyOn(console, "info").mockImplementation((line: unknown) => {
99 lines.push(String(line));
100 });
101 try {
102 await autonomyTick(app, new Date(), async () => 0);
103 } finally {
104 spy.mockRestore();
105 }
106 const tick = lines.find((l) => l.includes("[autonomy] tick") && l.includes("repo=alice/engine ") && l.includes("did=")) ?? "";
107 expect(tick).toContain("did=waiting");
108 expect(tick).toContain(`pace="${FULL}`);
109 });
110
111 test("the flow's why names it for the repository and an issue", () => {
112 expect(whyRepo(app, fresh()).cause?.says).toStartWith(`The crew is at its pace: ${FULL}`);
113 const why = whyIssue(app, fresh(), renderer);
114 expect(why.cause?.name).toBe("no_headroom");
115 expect(why.cause?.says).toStartWith(`The crew is at its pace: ${FULL}`);
116 });
117
118 test("the flow's why names it for an open pull, read in a pile", async () => {
119 const pushed = await commitToBranch(app, alice, fresh(), { branch: "renderer", base: "main", message: "Renderer", files: [{ path: "r.txt", content: "r\n" }] });
120 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
121 const opened = await openPull(app, alice, fresh(), { title: "Renderer", baseBranch: "main", headBranch: "renderer" });
122 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
123 // Its check is red: a builder owes it, at the pace for work on an open pull (no governor, no
124 // week), which is still no run here.
125 const red = createRun(app.db, { repoId: repo.id, kind: "check", issueId: opened.value.id, env: `pull-${opened.value.number}`, commitOid: opened.value.headOid, reason: "pull" });
126 app.db.query("UPDATE run SET state = 'failed', finished_at = ?2 WHERE id = ?1").run(red.id, new Date().toISOString());
127 const [why] = whyPulls(app, [{ repo: fresh(), pull: opened.value }]);
128 expect(why?.cause?.name).toBe("no_headroom");
129 expect(why?.cause?.says).toStartWith(`The crew is at its pace: ${FULL}`);
130 });
131
132 test("the idle reason names it", () => {
133 // The idle reason reads the autonomous repositories, the ones the loop drives on its own.
134 app.db.query("UPDATE repo SET autonomy = 'autonomous' WHERE id = ?1").run(repo.id);
135 expect(idleReason(app, new Date())?.word).toBe(`no subscription with headroom: ${paceHold(app, fresh())}`);
136 });
137 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs