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

Plan when planning helps: the planner is held while nothing lands or the plate is full, and the shop says why #1099

Closed opened this in answer to
Closed without merging

scout/forge:scout/1091-plan-when-planning-helps-the-planner-is → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +383 −1
docs/PLANNING.md +29
@@ -528,3 +528,32 @@ not confirm its own plan. Split also moves the parent's blocked-by edges to
528528 the issues named in `into` (a child that would make a loop is skipped), and
529529 the parent waits for nothing. Reopening clears the reason. Closes that
530530 predate reasons count as done.
531
532 ## When the planner is asked, and when it is held
533
534 Planning widens the plan; it cannot make anything land. Each tick the
535 planner is asked (`planIfThin`, `crew/autonomy.ts`) only when the map is
536 thin (fewer than three ready issues) or the crew handed it an issue it
537 parked twice, and none of these hold it:
538
539 - **Nothing has landed.** No pull merged in the last 48 hours *and* at
540 least one was closed unmerged (a red gate, a parked crew). The planner
541 is not asked. Instead, at most once per 6 hours (`crew/idle.ts`), the
542 forge opens, or updates in place and never duplicates, one issue titled
543 "Nothing has landed since <date>: why". It carries the last five
544 closed-unmerged pulls, their check summaries and the gate's last result,
545 and goes to the builder with the fewest runs in flight.
546 - **The plate is full.** More than `slots × 3` open issues are ready and
547 unassigned. A hand-over (an issue parked twice) is still owed its pass.
548 - **Planned recently,** a planner run is in flight, the direction is
549 declined, parked, or unwritten — as before.
550
551 A stalled shop is held whatever else is true; a thin map that is merging
552 plans as it always did. Every tick log line says so, so an idle shop is
553 never a mystery: `planner=held why="nothing landed since 2026-10-06"`,
554 `why="plate full (7 ready)"`, `why="planned recently"`.
555
556 The planner's brief says "at most four issues per run" is a ceiling, not a
557 target: read the open issues under the pillar first, attach to one when the
558 intent exists, and never open an issue whose acceptance is already another
559 open issue's or an umbrella's.
src/crew/autonomy.ts +34
@@ -101,6 +101,7 @@ import {
101101 proposedWork,
102102 speaksForCrew,
103103 } from "./direct.ts";
104 import { diagnose, landing, plateFull, sinceOf, stalled as nothingLanded } from "./idle.ts";
104105 import { crewOffInPreview } from "./preview.ts";
105106 import { reviewersOf, sendToReview, sweepReviews } from "./review.ts";
106107
@@ -326,6 +327,7 @@ export async function driveRepo(
326327 now = new Date(),
327328 ): Promise<Drove> {
328329 if (repo.autonomy === "off") return "off";
330 heldWhy.delete(repo.id);
329331 const status = autonomyStatus(app, repo, now);
330332 if (status.paused !== null) return "paused";
331333 const by = getUserById(app.db, repo.autonomyBy!);
@@ -422,7 +424,11 @@ const THIN_MAP = 3;
422424 * this is something it has not seen. What the pass leaves as it was stays
423425 * on the board and in every later brief (`parks.ts`).
424426 */
427 const heldWhy = new Map<string, string>();
428
425429 function notPlanned(repo: Repo, why: string): false {
430 if (/^(nothing landed|plate full|planned recently)/.test(why))
431 heldWhy.set(repo.id, why);
426432 log.info("planner not asked", {
427433 repo: `${repo.ownerName}/${repo.name}`,
428434 why,
@@ -441,6 +447,25 @@ async function planIfThin(
441447 ): Promise<boolean> {
442448 const handed = parkedTwice(app.db, [repo]);
443449 if (ready >= THIN_MAP && handed.length === 0) return false;
450 // Planning widens the plan; it cannot make anything land. While nothing
451 // has and pulls were thrown back, one issue asks a builder why instead.
452 const lands = landing(app.db, repo.id, now);
453 if (nothingLanded(lands)) {
454 const inFlight = new Map<string, number>();
455 for (const r of active)
456 if (r.actorId !== null)
457 inFlight.set(r.actorId, (inFlight.get(r.actorId) ?? 0) + 1);
458 diagnose(
459 app,
460 repo,
461 by,
462 crew.filter((c) => c.role === "builder").map((c) => c.agent),
463 inFlight,
464 lands,
465 now,
466 );
467 return notPlanned(repo, `nothing landed since ${sinceOf(lands)}`);
468 }
444469 const planner = crew.find((c) => c.role === "planner")?.agent;
445470 if (planner === undefined) return notPlanned(repo, "no planner on the crew");
446471 if (repo.autonomyDirection.trim() === "")
@@ -461,6 +486,12 @@ async function planIfThin(
461486 const seen = lastPlan?.created_at ?? "";
462487 const owed = handed.filter((issue) => issue.at > seen);
463488 if (ready >= THIN_MAP && owed.length === 0) return false;
489 const unassigned = readyNow(repoGraph(app.db, repo.id, { sealed: true })).filter(
490 (r) => r.issue.assigneeId === null && r.issue.id !== repo.directionIssueId,
491 ).length;
492 // A hand-over is owed even to a full plate: it mends what is there.
493 if (owed.length === 0 && plateFull(unassigned, repo.autonomySlots))
494 return notPlanned(repo, `plate full (${unassigned} ready)`);
464495 if (atRunCap(app, repo, direction))
465496 return notPlanned(repo, "parked: the direction is at its run cap");
466497 if (lastPlan !== null && lastPlan !== undefined) {
@@ -909,6 +940,9 @@ export async function autonomyTick(app: App, now = new Date()): Promise<void> {
909940 slots: status.slots,
910941 spent: `${status.spentTodayUsd.toFixed(2)}/${status.ceilingUsd}`,
911942 ...(status.paused === null ? {} : { paused: status.paused }),
943 ...(heldWhy.has(repo.id)
944 ? { planner: "held", why: heldWhy.get(repo.id) }
945 : {}),
912946 });
913947 } catch (error) {
914948 log.error("autonomy tick failed", {
src/crew/brief.ts +1
@@ -95,6 +95,7 @@ export function systemPrompt(input: BriefInput): string {
9595 '- Say what each issue is for. Where the direction names pillars, each has an open umbrella issue titled with its name ("P0 Trust: …"), opened by the owner or a writer of the repository; an issue so titled by anyone else is not a pillar. Link every issue you open under the pillar it serves — POST …/issues/U/dependencies with {"blockedBy": N} makes umbrella U wait for your issue N. Work that serves no pillar is not for now: link it behind the Later gate, the open issue whose title starts "Later gate:", opened by the owner or a writer — POST …/issues/N/dependencies with {"blockedBy": G} — and open its body with one sentence that says why it waits. Never leave an issue you opened with neither link; a deferred issue is not one of the ready issues the map needs.',
9696 "- The direction is never finished. When what it names is built, propose its next increment in the same spirit: what a demanding user would want next, what is fragile, slow, ugly, untested or undocumented, what the pictures and the previews show is off. Leave the map with at least three ready issues, every time.",
9797 '- An issue with a comment that starts "Parked by the crew" was tried and could not be finished as written. Split it into smaller issues, or rewrite what done looks like, or close it with a word if the direction no longer needs it — never leave it as it was. One the crew parked twice is yours: your task lists it, with what you may do with it.',
98 '- "At most four issues per run" is a ceiling, not a target: open fewer, or none, when fewer is all the direction needs. Before filing, read the open issues under the same pillar and attach to one when the intent exists. Never open an issue whose acceptance is already the acceptance of an umbrella or of another open issue.',
9899 "- Assign nobody and push nothing: the map is the result. The direction issue stays open.",
99100 "- The forge's API works; open no issue to try it. Every issue you open is work a builder is given.",
100101 "- Finish with a short message that lists what you opened, in order, and what is ready now.",
src/crew/idle.ts added +153
@@ -0,0 +1,153 @@
1 /**
2 * When planning helps. A planner widens the plan; it cannot make anything
3 * land. So it is held while the shop is idle for a reason it cannot fix —
4 * nothing merged in two days while pulls were closed unmerged, or a plate
5 * already full of ready work — and one diagnosis issue asks a builder why.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import type { App } from "../app.ts";
10 import { assignIssue, editIssue, openIssue } from "../actions/issues.ts";
11 import type { Agent } from "../core/agents.ts";
12 import { getIssueById, MAX_TITLE } from "../core/issues.ts";
13 import { checkSummary } from "../core/runs.ts";
14 import type { Repo } from "../core/repos.ts";
15 import type { User } from "../core/users.ts";
16 import { pickBuilder } from "./route.ts";
17
18 /** How far back "nothing has landed" looks. */
19 export const STALL_WINDOW_MS = 48 * 3_600_000;
20 /** The diagnosis issue is opened or updated at most this often. */
21 export const DIAGNOSE_EVERY_MS = 6 * 3_600_000;
22 const TITLE_PREFIX = "Nothing has landed since ";
23 const SHOWN = 5;
24
25 export interface Landing {
26 /** Pulls merged inside the window. */
27 readonly merged: number;
28 /** The newest merge ever, if any. */
29 readonly lastMergedAt: string | null;
30 /** Pulls closed unmerged inside the window, newest first (all of them). */
31 readonly closedUnmerged: readonly { id: string; number: number; title: string; headOid: string; closedAt: string }[];
32 }
33
34 export function landing(db: Database, repoId: string, now: Date): Landing {
35 const since = new Date(now.getTime() - STALL_WINDOW_MS).toISOString();
36 const merged =
37 db
38 .query<{ n: number }, [string, string]>(
39 `SELECT COUNT(*) AS n FROM pull JOIN issue ON issue.id = pull.issue_id
40 WHERE issue.repo_id = ?1 AND pull.merged_at >= ?2`,
41 )
42 .get(repoId, since)?.n ?? 0;
43 const last = db
44 .query<{ at: string | null }, [string]>(
45 `SELECT MAX(pull.merged_at) AS at FROM pull JOIN issue ON issue.id = pull.issue_id
46 WHERE issue.repo_id = ?1`,
47 )
48 .get(repoId);
49 const closedUnmerged = db
50 .query<
51 { id: string; number: number; title: string; head_oid: string; closed_at: string },
52 [string, string]
53 >(
54 `SELECT issue.id, issue.number, issue.title, pull.head_oid, issue.closed_at
55 FROM pull JOIN issue ON issue.id = pull.issue_id
56 WHERE issue.repo_id = ?1 AND issue.kind = 'pull' AND issue.state = 'closed'
57 AND pull.merged_at IS NULL AND issue.closed_at >= ?2
58 ORDER BY issue.closed_at DESC`,
59 )
60 .all(repoId, since)
61 .map((r) => ({
62 id: r.id,
63 number: r.number,
64 title: r.title,
65 headOid: r.head_oid,
66 closedAt: r.closed_at,
67 }));
68 return { merged, lastMergedAt: last?.at ?? null, closedUnmerged };
69 }
70
71 /** Nothing landed, and something was tried and thrown back. */
72 export function stalled(l: Landing): boolean {
73 return l.merged === 0 && l.closedUnmerged.length > 0;
74 }
75
76 /** More ready, unassigned issues than the builders can take three rounds of. */
77 export function plateFull(readyUnassigned: number, slots: number): boolean {
78 return readyUnassigned > Math.max(slots, 1) * 3;
79 }
80
81 /** The date a stall is dated from: the last merge, else the oldest closed pull in the window. */
82 export function sinceOf(l: Landing): string {
83 const at = l.lastMergedAt ?? l.closedUnmerged.at(-1)?.closedAt ?? "";
84 return at.slice(0, 10);
85 }
86
87 function bodyOf(db: Database, l: Landing, repoId: string, now: Date): string {
88 const lines = [
89 `No pull has merged in the last 48 hours, and ${l.closedUnmerged.length} closed unmerged. The planner is held until something lands; it cannot fix this. Find out why and say it here.`,
90 "",
91 "Last closed unmerged:",
92 ];
93 for (const p of l.closedUnmerged.slice(0, SHOWN)) {
94 const c = checkSummary(db, p.id, p.headOid);
95 lines.push(
96 `- #${p.number} ${p.title} — closed ${p.closedAt.slice(0, 16)}Z; checks: ${c.state}${c.run?.summary ? ` (${c.run.summary})` : ""}`,
97 );
98 }
99 const gate = db
100 .query<{ state: string; summary: string; created_at: string }, [string]>(
101 `SELECT state, summary, created_at FROM run
102 WHERE repo_id = ?1 AND kind IN ('check','deploy') ORDER BY id DESC LIMIT 1`,
103 )
104 .get(repoId);
105 lines.push(
106 "",
107 gate
108 ? `The gate's last result: ${gate.state} at ${gate.created_at.slice(0, 16)}Z${gate.summary ? ` — ${gate.summary}` : ""}.`
109 : "The gate has not run.",
110 "",
111 `Updated ${now.toISOString().slice(0, 16)}Z.`,
112 );
113 return lines.join("\n");
114 }
115
116 /**
117 * Open the one diagnosis issue, or update it; never a second. At most once
118 * per DIAGNOSE_EVERY_MS. Returns whether it wrote.
119 */
120 export function diagnose(
121 app: App,
122 repo: Repo,
123 by: User,
124 builders: readonly Agent[],
125 inFlight: ReadonlyMap<string, number>,
126 l: Landing,
127 now: Date,
128 ): boolean {
129 const title = `${TITLE_PREFIX}${sinceOf(l)}: why`.slice(0, MAX_TITLE);
130 const found = app.db
131 .query<{ id: string }, [string, string]>(
132 `SELECT id FROM issue WHERE repo_id = ?1 AND kind = 'issue' AND title LIKE ?2
133 ORDER BY created_at DESC LIMIT 1`,
134 )
135 .get(repo.id, `${TITLE_PREFIX}%`);
136 const existing = found ? getIssueById(app.db, found.id) : undefined;
137 const body = bodyOf(app.db, l, repo.id, now);
138 if (existing !== undefined) {
139 // An open one is updated in place; a closed one is a person's answer,
140 // and is not reopened inside the window.
141 const at = existing.state === "open" ? existing.updatedAt : existing.createdAt;
142 if (now.getTime() - new Date(at).getTime() < DIAGNOSE_EVERY_MS) return false;
143 if (existing.state === "open") {
144 const edited = editIssue(app, by, repo, existing, { title, body });
145 return edited.ok;
146 }
147 }
148 const opened = openIssue(app, by, repo, { title, body });
149 if (!opened.ok) return false;
150 const builder = pickBuilder(opened.value, builders, inFlight);
151 if (builder !== undefined) assignIssue(app, by, repo, opened.value, builder.user);
152 return true;
153 }
test/capacity.test.ts +1 −1
@@ -292,7 +292,7 @@ describe("capacity: only a forge admin reads or changes it", () => {
292292 await fetch(`${servers.url}/settings/capacity`, { headers: { cookie } })
293293 ).text();
294294 expect(after).toContain("alice");
295 });
295 }, 30_000); // a long walk of requests: the default 5s fails on a loaded runner
296296 });
297297
298298 describe("report mode is loud to admins, and to nobody else", () => {
test/crew-idle.test.ts added +165
@@ -0,0 +1,165 @@
1 /**
2 * When planning helps: the planner is held while nothing lands or the plate
3 * is full, one diagnosis issue asks why, and the tick says so.
4 */
5 import { afterEach, beforeEach, describe, expect, spyOn, 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 { addToCrew, createAgent } from "../src/actions/crew.ts";
11 import { openIssue } from "../src/actions/issues.ts";
12 import { createRepo, updateRepoSettings } from "../src/actions/repos.ts";
13 import { setCrewRole } from "../src/core/agents.ts";
14 import { getIssueById } from "../src/core/issues.ts";
15 import { getRepoById, type Repo } from "../src/core/repos.ts";
16 import { claimRun, createRun } from "../src/core/runs.ts";
17 import { createUser, getUserByName, type User } from "../src/core/users.ts";
18 import { autonomyTick, driveRepo } from "../src/crew/autonomy.ts";
19 import { plateFull, stalled, landing } from "../src/crew/idle.ts";
20
21 let dataDir: string;
22 let app: App;
23 let alice: User;
24 let repo: Repo;
25 let n = 100;
26 const fresh = () => getRepoById(app.db, repo.id)!;
27
28 /** A pull row, closed (merged or not) at `at`, without a git branch behind it. */
29 function pullAt(at: string, merged: boolean): void {
30 const id = `pull-${n}`;
31 app.db
32 .query(
33 `INSERT INTO issue (id, repo_id, number, kind, title, author_id, state, closed_at)
34 VALUES (?1, ?2, ?3, 'pull', ?4, ?5, 'closed', ?6)`,
35 )
36 .run(id, repo.id, n, `Pull ${n}`, alice.id, at);
37 app.db
38 .query(
39 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at)
40 VALUES (?1, 'main', ?2, 'a', 'b', ?3)`,
41 )
42 .run(id, `b${n}`, merged ? at : null);
43 n++;
44 }
45
46 const hoursAgo = (h: number) => new Date(Date.now() - h * 3_600_000).toISOString();
47 const diagnoses = () =>
48 app.db
49 .query<{ id: string }, []>(
50 "SELECT id FROM issue WHERE title LIKE 'Nothing has landed since %'",
51 )
52 .all();
53 const directionHolder = () =>
54 getIssueById(app.db, fresh().directionIssueId!)?.assigneeId ?? null;
55
56 beforeEach(async () => {
57 dataDir = await mkdtemp(join(tmpdir(), "forge-idle-"));
58 app = createApp({ dataDir, port: 0 });
59 const a = await createUser(app.db, {
60 trusted: true,
61 username: "alice",
62 email: "[email protected]",
63 password: "a-good-passphrase",
64 adminIfFirst: true,
65 });
66 if (!a.ok) throw new Error(a.error);
67 alice = a.value;
68 const made = await createRepo(app, alice, { name: "engine", visibility: "private" });
69 if (!made.ok) throw new Error(String(made.error));
70 repo = made.value;
71 for (const name of ["mason", "atlas"]) {
72 await createAgent(app, alice, { username: name });
73 addToCrew(app, alice, repo, name);
74 }
75 setCrewRole(app.db, repo.id, getUserByName(app.db, "atlas")!.id, "planner");
76 await updateRepoSettings(app, alice, repo, {
77 autonomy: "autonomous",
78 autonomyDirection: "Build the engine.",
79 autonomyCeilingUsd: 10,
80 autonomySlots: 1,
81 autonomyBy: alice.id,
82 });
83 });
84
85 afterEach(async () => {
86 app.close();
87 await rm(dataDir, { recursive: true, force: true });
88 });
89
90 describe("a stalled shop", () => {
91 test("closed-unmerged pulls and no merge: one diagnosis issue, no planner run", async () => {
92 pullAt(hoursAgo(5), false);
93 pullAt(hoursAgo(3), false);
94 expect(stalled(landing(app.db, repo.id, new Date()))).toBe(true);
95 expect(await driveRepo(app, fresh())).toBe("idle");
96 expect(directionHolder()).toBeNull();
97 const [one, ...rest] = diagnoses();
98 expect(rest).toEqual([]);
99 const issue = getIssueById(app.db, one!.id)!;
100 expect(issue.title).toMatch(/^Nothing has landed since \d{4}-\d\d-\d\d: why$/);
101 expect(issue.body).toContain("#101");
102 expect(issue.body).toContain("The gate has not run.");
103 expect(issue.assigneeId).toBe(getUserByName(app.db, "mason")!.id);
104 });
105
106 test("asked again within the window it does not duplicate; after it, it updates in place", async () => {
107 pullAt(hoursAgo(5), false);
108 await driveRepo(app, fresh());
109 await driveRepo(app, fresh());
110 expect(diagnoses().length).toBe(1);
111 pullAt(hoursAgo(1), false);
112 const later = new Date(Date.now() + 7 * 3_600_000);
113 await driveRepo(app, fresh(), later);
114 expect(diagnoses().length).toBe(1);
115 expect(getIssueById(app.db, diagnoses()[0]!.id)!.body).toContain(`#${n - 1}`);
116 expect(directionHolder()).toBeNull();
117 });
118
119 test("a merge inside 48 hours is a healthy shop: the planner is asked as before", async () => {
120 pullAt(hoursAgo(5), false);
121 pullAt(hoursAgo(2), true);
122 expect(stalled(landing(app.db, repo.id, new Date()))).toBe(false);
123 expect(await driveRepo(app, fresh())).toBe("planned");
124 expect(directionHolder()).toBe(getUserByName(app.db, "atlas")!.id);
125 expect(diagnoses()).toEqual([]);
126 });
127
128 test("the tick says the planner is held, and why", async () => {
129 pullAt(hoursAgo(5), false);
130 const lines: string[] = [];
131 const spy = spyOn(console, "info").mockImplementation((l: unknown) => {
132 lines.push(String(l));
133 });
134 await autonomyTick(app);
135 spy.mockRestore();
136 const tick = lines.find((l) => l.includes("tick"));
137 expect(tick).toContain("held");
138 expect(tick).toContain("nothing landed since");
139 });
140 });
141
142 describe("a full plate", () => {
143 test("more than slots × 3 ready and unassigned holds the planner", async () => {
144 expect(plateFull(3, 1)).toBe(false);
145 expect(plateFull(4, 1)).toBe(true);
146 expect(plateFull(6, 2)).toBe(false);
147 const mason = getUserByName(app.db, "mason")!;
148 const made = [];
149 for (let i = 0; i < 5; i++) {
150 const o = openIssue(app, alice, repo, { title: `Work ${i}` });
151 if (!o.ok) throw new Error(String(o.error));
152 made.push(o.value);
153 }
154 const run = createRun(app.db, {
155 repoId: repo.id,
156 kind: "agent",
157 issueId: made[0]!.id,
158 actorId: mason.id,
159 reason: "assigned",
160 });
161 claimRun(app.db, run.id);
162 expect(await driveRepo(app, fresh())).toBe("full");
163 expect(directionHolder()).toBeNull();
164 });
165 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs