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

The crew starts a chapter's issues in the order the owner set #15809

Merged opened this

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

Merged

scout/forge:scout/15762-the-crew-starts-a-chapter-s-issues-in-th → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/15762-the-crew-starts-a-chapter-s-issues-in-th was merged into main as 2611fe6.

Review

Sign in to review this change.
7 files changed +218 −10
docs/features/chapters.md +8
@@ -46,3 +46,11 @@ Try it: file a sealed issue, add it to the open chapter, then open `/<owner>/<na
4646 ## How fast the book fills
4747
4848 The chapter line on `/next`, the open chapter's page, the terminal's Queue screen and the MCP `repo` tool (`view: chapters` with `chapter`, field `flow`) carry one sentence: `opened 12 this week, landed 9: the book is growing by 3` (or `draining by N`, or `flat`). Opened is items put in the chapter in the last seven days, landed is items done (live and proven) in them; a sealed item the viewer may not see counts in neither. Read by `flowOf` in `src/core/chapters.ts`; the terminal door is `queueLines` in `src/tui/screens/queuegrowth.ts`. It is the signal for pausing the planner.
49
50 ## The crew follows the order (#15762)
51
52 While a chapter is open, the crew starts its ready issues in the order the owner set on the chapter's list (ties by issue number), ahead of every other ready issue; those keep their own Next up order after them (`inSlotOrder` in `src/crew/autonomy.ts`, reading `openOrder` in `src/core/chapters.ts`). Move an item **Up** and it is the next one a builder takes.
53
54 The position shows only where an issue really waits. When the free builder slots (the slots set in the repository's settings, less the builder runs in flight) run out before a startable chapter item, `/next` (and the API, the MCP `next_up` tool and the terminal's Next up screen, which share `notStartable` in `src/crew/not_startable.ts`) gives that row `position 3 in v1, after #12`: its place in the list, and the first chapter item that will start. A held item is skipped over, so `#12` is always one that can start. With a slot free for each, no row carries the words: they all start on the same tick.
55
56 Try it: open a chapter with three ready issues, set the crew's slots to 1, and open `/<owner>/<name>/next`: the second and third rows say their position after the first. Move the last one **Up** twice on the chapter's page and it becomes the one the others wait after.
src/core/chapters.ts +33
@@ -215,6 +215,39 @@ function orderOf(db: Database, chapterId: string): string[] {
215215 .map((r) => r.issue_id);
216216 }
217217
218 /** The open chapter and each of its items' position in it, 1 at the top. */
219 export interface OpenOrder {
220 readonly chapter: Chapter;
221 readonly places: ReadonlyMap<string, number>;
222 }
223
224 /** The order of a chapter's list as `itemsOf` gives it (place, then number): no read. */
225 export const orderFrom = (chapter: Chapter, items: readonly { readonly issueId: string }[]): OpenOrder => ({
226 chapter,
227 places: new Map(items.map((it, k) => [it.issueId, k + 1] as const)),
228 });
229
230 /**
231 * The open chapter's order: the one the owner set (the place, then the issue number). Undefined
232 * when no chapter is open. Pinned to one chapter, so two open could never interleave their
233 * positions.
234 */
235 export function openOrder(db: Database, repoId: string): OpenOrder | undefined {
236 // One statement: the chapter's columns ride on each item's row; an open chapter with no items has
237 // one row of none.
238 const rows = db
239 .query<Row & { item_id: string | null }, [string]>(
240 `SELECT ch.*, c.issue_id AS item_id FROM chapter ch
241 LEFT JOIN chapter_item c ON c.chapter_id = ch.id
242 LEFT JOIN issue i ON i.id = c.issue_id
243 WHERE ch.id = (SELECT id FROM chapter WHERE repo_id = ?1 AND state = 'open' ORDER BY created_at LIMIT 1)
244 ORDER BY c.place, i.number`,
245 )
246 .all(repoId);
247 if (rows.length === 0) return undefined;
248 return orderFrom(toChapter(rows[0]!), rows.flatMap((r) => (r.item_id === null ? [] : [{ issueId: r.item_id }])));
249 }
250
218251 /**
219252 * Move an item one place up or down its chapter's list: the places are rewritten 1..n so a list
220253 * that never moved (all zero, so by number) takes its first order from what it showed. The first
src/crew/autonomy.ts +11 −1
@@ -35,6 +35,7 @@ import { addLearned } from "../checks/learned.ts";
3535 import { batchWords, dropFromLine, enqueue, type GateCandidate, type Queued, type QueueOptions, queueClashes, queueWords, waitingPulls } from "../checks/queue.ts";
3636 import { checksFor } from "../checks/service.ts";
3737 import { queueBatch, queueDepth } from "../core/capacity.ts";
38 import { openOrder } from "../core/chapters.ts";
3839 import { crewFor as crewForIssue, passedWords, pickFilter, routable } from "./pick_filter.ts";
3940 import { readConflictLane, readConflictRoom } from "./conflict_room.ts";
4041 import { mergeable, resolveOid, treeOf } from "../git/merge.ts";
@@ -441,7 +442,16 @@ export function inSlotOrder(app: App, repo: Repo, ready: readonly Ranked[], now:
441442 const ranked = ranksInRepo(app.db, repo.id).places;
442443 const { allowed } = pickFilter(app, repo, ready, now);
443444 // The order is the one Next up shows (#8826): ranked by place, then the ready order.
444 return pickOrder(allowed, ranked, (r) => r.issue.id, [], fromAppIssues(app.db, allowed.map((r) => r.issue.id)));
445 const order = pickOrder(allowed, ranked, (r) => r.issue.id, [], fromAppIssues(app.db, allowed.map((r) => r.issue.id)));
446 // An open chapter (#15762): its issues come first, by the position the owner set, ties by number;
447 // every other issue keeps the order above, untouched.
448 const open = openOrder(app.db, repo.id);
449 if (open === undefined) return order;
450 const place = (r: Ranked): number | undefined => open.places.get(r.issue.id);
451 const inChapter = order
outdated

Issues outside the chapter all have at()=Infinity, so this falls to the number tiebreak and re-sorts them by number. That breaks the ranked order pickOrder produced. Return 0 when both are outside the chapter, or partition first and concatenate. Add a test for it.

452 .filter((r) => place(r) !== undefined)
453 .sort((a, b) => place(a)! - place(b)! || a.issue.number - b.issue.number);
454 return [...inChapter, ...order.filter((r) => place(r) === undefined)];
445455 }
446456
447457 /**
src/crew/not_startable.ts +18
@@ -11,6 +11,8 @@ import type { Ranked } from "../core/dependencies.ts";
1111 import type { Repo } from "../core/repos.ts";
1212 import { listActive } from "../core/runs.ts";
1313 import { listCrewRoles } from "../core/agents.ts";
14 import { openOrder, type OpenOrder } from "../core/chapters.ts";
15 import { slottedRuns } from "./autonomy.ts";
1416 import { PASSED_WORDS, pickFilter, routable } from "./pick_filter.ts";
1517 import { admits, heldBy, mapHolds } from "./held.ts";
1618
@@ -20,6 +22,10 @@ export function notStartable(
2022 repo: Repo,
2123 ready: readonly Ranked[],
2224 scope: { sealed?: true; sealedBy?: string },
25 /**
26 * The open chapter's order when the caller has read it (null: none open); read here when absent.
27 */
28 open: OpenOrder | null = openOrder(app.db, repo.id) ?? null,
2329 ): Map<string, string> {
2430 const active = listActive(app.db, "agent").filter((r) => r.repoId === repo.id);
2531 const admit = admits(app, repo, scope);
@@ -36,5 +42,17 @@ export function notStartable(
3642 const routed = routable(app, repo, held.startable, crew, now);
3743 const { passed } = pickFilter(app, repo, routed.kept, now);
3844 for (const [id, why] of [...routed.passed, ...passed]) out.set(id, PASSED_WORDS[why]);
45 // The open chapter's startable issues are picked first, by the owner's position (#15762). One
46 // waits behind an earlier one only when the free builder slots run out before it: the slots the
47 // operator set, less the runs in flight that spend one. Pacing can only lower that, so a row
48 // never reads as waiting when it would start this tick.
49 if (open !== null) {
50 const line = held.startable
51 .filter((r) => !out.has(r.issue.id) && open.places.has(r.issue.id))
52 .sort((a, b) => open.places.get(a.issue.id)! - open.places.get(b.issue.id)! || a.issue.number - b.issue.number);
53 const free = Math.max(0, repo.autonomySlots - slottedRuns(active, crew).length);
54 for (const r of line.slice(Math.max(1, free)))
55 out.set(r.issue.id, `position ${open.places.get(r.issue.id)} in ${open.chapter.name}, after #${line[0]!.issue.number}`);
56 }
3957 return out;

Non-blocking: the words read as order, which is good. Once pacing is counted, a waiting row will keep them too.

4058 }
src/web/pages/next.ts +11 −5
@@ -30,7 +30,7 @@ import { html, raw, type Html } from "../html.ts";
3030 import { flashOrJson, page } from "../layout.ts";
3131 import { btn, kbd, listCard, row, time } from "../ui.ts";
3232 import { GROWTH_DAYS, growthLine } from "./next_growth.ts";
33 import { listChapters } from "../../core/chapters.ts";
33 import { itemsOf, listChapters, orderFrom, type Chapter, type Item } from "../../core/chapters.ts";
3434 import { chapterLine, chaptersSection } from "./next_chapters.ts";
3535 import { batchButtons, undoButton, batchForms, tick, undoLive } from "./next_batch.ts";
3636 import { countWords, filterPath, markBefore, filtered, matches, readFilter } from "./next_filter.ts";
@@ -263,7 +263,14 @@ export function nextPage(ctx: Ctx): Response {
263263 const base = repoBase(repo);
264264 const writer = ctx.auth.user !== undefined && ctx.auth.user.kind !== "agent" && canWrite(ctx.app.db, repo, ctx.auth.user);
265265 const scope = sealedScope(ctx.app.db, repo, ctx.auth.user);
266 const next = nextUp(ctx.app.db, repo, scope, (ready) => notStartable(ctx.app, repo, ready, scope));
266 // The chapters are read once: the open one's list, as this viewer sees it, serves the
267 // not-startable words, the chapter line and the chapters section alike (#15762).
268 const chapters = listChapters(ctx.app.db, repo.id);
269 const listed = new Map<string, readonly Item[]>();
270 const itemsFor = (c: Chapter): readonly Item[] => listed.get(c.id) ?? listed.set(c.id, itemsOf(ctx.app.db, c, scope)).get(c.id)!;
271 const openChapter = chapters.find((c) => c.state === "open");
272 const order = openChapter === undefined ? null : orderFrom(openChapter, itemsFor(openChapter));
273 const next = nextUp(ctx.app.db, repo, scope, (ready) => notStartable(ctx.app, repo, ready, scope, order));
267274 const rows = next.rows;
268275 const filter = readFilter(ctx.url.searchParams);
269276 const isFiltered = filtered(filter);
@@ -314,11 +321,10 @@ export function nextPage(ctx: Ctx): Response {
314321 ${isFiltered ? html`<a href="${base}/next">Clear</a>` : null}
315322 ${writer ? batchButtons(live) : null}
316323 </form>`;
317 const chapters = listChapters(ctx.app.db, repo.id);
318324 const body = html`${repoHeader(ctx, repo, "issues")}
319325 <div data-next>
320326 ${pageHead("Next up", { sub: "The crew builds strictly from the top." })}
321 ${chapterLine(ctx, repo, chapters)}
327 ${chapterLine(ctx, repo, chapters, itemsFor)}
322328 ${growthLine(week7, pauseAt(week7, new Date()), writer && canAdmin(ctx.app.db, repo, ctx.auth.user!), base, back)}
323329 <p class="error" id="next-flash" role="alert" hidden></p>
324330 ${outsiderSection(ctx, repo, base, back, writer)}
@@ -327,7 +333,7 @@ export function nextPage(ctx: Ctx): Response {
327333 ? html`<p class="muted">Nothing is ready: everything open waits for something. <a href="${base}/map">See the map</a>. ${undoButton(live)}</p>`
328334 : html`${bar}${isFiltered ? html`<p class="muted" id="next-count">${countWords(ats.length, rows.length)} shown${ats.length + parked.length === 0 ? html`. ${nothingWords}` : null}. Numbers and the cut line are the whole list's; the week's capacity bar is left out while filtered.</p>` : null}
329335 ${first.length > 0 ? section(isFiltered ? "Matching" : "Up next", first, true, "next-list") : null}${rest.length > 0 ? section("After", rest, false) : null}`}
330 ${chaptersSection(ctx, repo, back, chapters)}
336 ${chaptersSection(ctx, repo, back, chapters, itemsFor)}
331337 <p class="muted small mt" id="next-week">${sentence} <a href="${base}/week">The week</a>${writer
332338 ? " · Drag a row. Keys: t top · l Later · Shift+J/K or Alt+↓/↑ down/up · j/k choose a row."
333339 : null}</p>
src/web/pages/next_chapters.ts +7 −4
@@ -22,7 +22,10 @@ function act(base: string, c: Chapter, verb: "close" | "undo", back: string, lab
2222 </form>`;
2323 }
2424
25 export function chaptersSection(ctx: Ctx, repo: Repo, back: string, all: readonly Chapter[]): Html | null {
25 /** A chapter's list as this viewer sees it; a page that read one already passes it. */
26 type ItemsFor = (c: Chapter) => readonly Item[];
27
28 export function chaptersSection(ctx: Ctx, repo: Repo, back: string, all: readonly Chapter[], itemsFor?: ItemsFor): Html | null {
2629 const app = ctx.app;
2730 if (all.length === 0) return null;
2831 const base = repoBase(repo);
@@ -30,7 +33,7 @@ export function chaptersSection(ctx: Ctx, repo: Repo, back: string, all: readonl
3033 const now = Date.now();
3134 const view = sealedScope(app.db, repo, ctx.auth.user);
3235 const rows = all.slice(0, SHOWN).map((c) => {
33 const items = itemsOf(app.db, c, view);
36 const items = itemsFor?.(c) ?? itemsOf(app.db, c, view);
3437 const p = progressOf(c, items, new Date(now));
3538 const link = html`<a href="${base}/chapters/${encodeURIComponent(c.name)}">${c.name}</a>`;
3639 const stop = c.state === "open" ? stopsClose(app, c, view) : null;
@@ -66,12 +69,12 @@ export function chaptersSection(ctx: Ctx, repo: Repo, back: string, all: readonl
6669 * The line under the /next heading: the open chapter and where it stands, or that none is open once
6770 * chapters exist.
6871 */
69 export function chapterLine(ctx: Ctx, repo: Repo, all: readonly Chapter[]): Html | null {
72 export function chapterLine(ctx: Ctx, repo: Repo, all: readonly Chapter[], itemsFor?: ItemsFor): Html | null {
7073 const base = repoBase(repo);
7174 const view = sealedScope(ctx.app.db, repo, ctx.auth.user);
7275 const now = new Date();
7376 let listed: readonly Item[] = [];
74 const p = chapterLineParts(all, (c) => (listed = itemsOf(ctx.app.db, c, view)), now);
77 const p = chapterLineParts(all, (c) => (listed = itemsFor?.(c) ?? itemsOf(ctx.app.db, c, view)), now);
7578 if (p === null) return null;
7679 if (p.chapter === null) return html`<p class="muted" data-chapter-line>${p.lead}<a href="${base}/chapters">${p.name}</a>${p.tail}</p>`;
7780 const flow = flowSentence(flowOf(ctx.app.db, p.chapter, listed, now));
test/chapters-pick-order.test.ts added +130
@@ -0,0 +1,130 @@
1 /** The crew takes an open chapter's issues in the order the owner set (#15762). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { draft, fill, move, open } from "../src/actions/chapters.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { inSlotOrder } from "../src/crew/autonomy.ts";
10 import { rankIssue } from "../src/actions/next.ts";
11 import { notStartable } from "../src/crew/not_startable.ts";
12 import { readyNow, repoGraph } from "../src/core/dependencies.ts";
13 import { createIssue } from "../src/core/issues.ts";
14 import { getRepo } from "../src/core/repos.ts";
15 import { addToCrew, createAgent } from "../src/actions/crew.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { updateRepoSettings } from "../src/core/repos.ts";
18 import { cancelRun, createRun } from "../src/core/runs.ts";
19 import { openOrder } from "../src/core/chapters.ts";
20
21 let dataDir: string;
22 let app: App;
23 let alice: User;
24 const nums: number[] = [];
25 const repo = () => getRepo(app.db, "alice", "pub")!;
26 const ready = () => readyNow(repoGraph(app.db, repo().id, { sealed: true }));
27 const picked = () => inSlotOrder(app, repo(), ready()).map((r) => r.issue.number).filter((n) => nums.includes(n));
28
29 beforeAll(async () => {
30 dataDir = await mkdtemp(join(tmpdir(), "forge-chapters-pick-"));
31 app = createApp({ dataDir, port: 0 });
32 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
33 if (!u.ok) throw new Error(u.error);
34 alice = u.value;
35 const bot = await createAgent(app, alice, { username: "mason", roles: ["builder"] });
36 if (!bot.ok) throw new Error(String(bot.error));
37 const made = await createRepo(app, alice, { name: "pub", visibility: "public" });
38 if (!made.ok) throw new Error(String(made.error));
39 const added = addToCrew(app, alice, repo(), "mason", "builder");
40 if (!added.ok) throw new Error(String(added.error));
41 for (const t of ["one", "two", "three"]) {
42 const i = createIssue(app.db, { repoId: repo().id, authorId: alice.id, title: t, body: "" });
43 if (!i.ok) throw new Error("issue");
44 nums.push(i.value.number);
45 }
46 expect(draft(app, alice, repo(), { name: "v1" }).ok).toBe(true);
47 for (const k of [0, 1, 2]) expect(fill(app, alice, repo(), "v1", nums[k]!, true).ok).toBe(true);
48 expect(open(app, alice, repo(), "v1").ok).toBe(true);
49 }, 30_000);
50
51 afterAll(async () => {
52 app.close();
53 await rm(dataDir, { recursive: true, force: true });
54 });
55
56 test("three ready issues in an open chapter are picked by position, and a reorder changes the pick", () => {
57 const [a, b, c] = nums as [number, number, number];
58 expect(picked()).toEqual([a, b, c]);
59 // Move the last to the top: c, a, b.
60 expect(move(app, alice, repo(), "v1", c, "up").ok).toBe(true);
61 expect(move(app, alice, repo(), "v1", c, "up").ok).toBe(true);
62 expect(picked()).toEqual([c, a, b]);
63 expect(move(app, alice, repo(), "v1", b, "up").ok).toBe(true);
64 expect(picked()).toEqual([c, b, a]);
65 });
66
67 const whyOf = () => {
68 const why = notStartable(app, repo(), ready(), { sealed: true });
69 return (n: number) => why.get(ready().find((r) => r.issue.number === n)!.issue.id);
70 };
71 const slots = (n: number) => updateRepoSettings(app.db, repo(), { autonomySlots: n });
72
73 test("with one builder slot, the issues behind the first name their position and the first", () => {
74 const [a, b, c] = nums as [number, number, number];
75 slots(1);
76 const by = whyOf();
77 expect(by(c)).toBeUndefined();
78 expect(by(b)).toBe(`position 2 in v1, after #${c}`);
79 expect(by(a)).toBe(`position 3 in v1, after #${c}`);
80 });
81
82 test("with a slot free for each, none of them reads as waiting: they all start this tick", () => {
83 const [a, b, c] = nums as [number, number, number];
84 slots(3);
85 const by = whyOf();
86 for (const n of [a, b, c]) expect(by(n)).toBeUndefined();
87 slots(2);
88 const two = whyOf();
89 expect(two(b)).toBeUndefined();
90 expect(two(a)).toBe(`position 3 in v1, after #${c}`);
91 });
92
93 test("a held first item is passed over: the others wait after the first startable one", () => {
94 const [a, b, c] = nums as [number, number, number];
95 slots(1);
96 // A review run on the top item holds it and spends no builder slot.
97 const run = createRun(app.db, { repoId: repo().id, kind: "agent", issueId: ready().find((r) => r.issue.number === c)!.issue.id, reason: "review" });
98 try {
99 const by = whyOf();
100 expect(by(c)).toBeDefined();
101 expect(by(c)).not.toContain("position");
102 expect(by(b)).toBeUndefined();
103 expect(by(a)).toBe(`position 3 in v1, after #${b}`);
104 } finally {
105 cancelRun(app.db, run.id);
106 }
107 });
108
109 test("only one chapter is open at a time, and the order is that chapter's alone", () => {
110 expect(draft(app, alice, repo(), { name: "v2" }).ok).toBe(true);
111 expect(open(app, alice, repo(), "v2").ok).toBe(false);
112 const o = openOrder(app.db, repo().id)!;
113 expect(o.chapter.name).toBe("v1");
114 expect([...o.places.values()]).toEqual([1, 2, 3]);
115 });
116
117 test("issues outside the chapter keep their Next up order, after the chapter's", () => {
118 const mk = (t: string) => {
119 const i = createIssue(app.db, { repoId: repo().id, authorId: alice.id, title: t, body: "" });
120 if (!i.ok) throw new Error("issue");
121 return i.value.number;
122 };
123 const low = mk("outside low"); // lower number, unranked
124 const high = mk("outside high"); // higher number, ranked on top
125 expect(rankIssue(app, alice, repo(), high, { to: "top" }).ok).toBe(true);
126 const all = inSlotOrder(app, repo(), ready()).map((r) => r.issue.number);
127 const outside = all.filter((n) => n === low || n === high);
128 expect(outside).toEqual([high, low]);
129 expect(all.slice(0, 3).sort((x, y) => x - y)).toEqual([...nums].sort((x, y) => x - y));
130 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs