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

Parked pulls do not sit: offered to the crew again after crew.parkedHours, then closed with Reopen #17382

opened this

Merged 27h 16m ago, live in production

crew/parked-pulls → main 0 commits 6 threads · 6 unresolved

  • Merged. crew/parked-pulls was merged into main as a405edf.

Review

Sign in to review this change.
9 files changed +627 −2
docs/features/parked-pulls.md added +24
@@ -0,0 +1,24 @@
1 ---
2 topic: Ship and undo
3 row: A pull nobody moves is offered to the crew again after six hours, then closed with Reopen
4 ---
5 # Parked pulls do not sit
6
7 A pull is **parked** when it is open, not approved on its head, has nothing queued or running on
8 it, and has had no push or reopen for six hours (`PARKED_HOURS`, `src/flow/parked_read.ts`). The
9 crew's pass (`src/crew/parked.ts`, every five minutes per autonomous repository) moves it:
10
11 - **Offered once.** When the last verdict asked for changes, a feedback run goes to its builder;
12 with no verdict, or an approval of an older head, a review run goes to the least busy reviewer.
13 One note on the pull quotes that verdict and says what comes next.
14 - **Closed six hours after the offer.** Still parked, a crew pull is closed with the reason. Its
15 branch is kept: **Reopen** restores the pull, and the reopen starts the clock again.
16 - **A person's pull is never closed.** The owner's own, or anyone's from a branch of the
17 repository, is offered and nothing more: no builder can push its branch, so with changes asked
18 for, the offer is the note alone.
19 - **Left to their own flows:** a held pull, one approved on its head (landing), one whose head's
20 check failed (the red flow), a draft, and one with a run in flight.
21 - **On the Bridge, both doors.** The home lists each parked pull of a repository the viewer can
22 read, at every width: the pull and one fact (no push yet answered, when it closes, or that it was
23 offered). One closed in the last day has Reopen beside it; the terminal home says the same, with
24 `o` on its pull to reopen it.
src/crew/autonomy_tick.ts +9
@@ -29,6 +29,7 @@ import { pruneLine, startSweep, sweepGreen } from "./green_sweep.ts";
2929 import { heldBy, heldWords } from "./held.ts";
3030 import { hotFiles, hotWords } from "./hot_files.ts";
3131 import { liveTriage, none as noTriage, tickFields } from "./livetriage.ts";
32 import { moveParked, parkedDue } from "./parked.ts";
3233 import { passedWords, pickFilter } from "./pick_filter.ts";
3334 import { crewOffInPreview } from "./preview.ts";
3435 import { recheckRedApproved } from "./red_approved.ts";
@@ -154,6 +155,14 @@ export async function autonomyTick(
154155 // work takes the slots it needs (#2172).
155156 const requested = await moveRequested(app, current, freeSlots(app, current, now), now);
156157 await breathe();
158 // A pull nobody moves is offered to the crew again, then closed (`parked.ts`).
159 if (parkedDue(app, current.id, now)) {
160 try {
161 moveParked(app, current, now);
162 } catch (error) {
163 log.error("parked pulls pass failed", { repo: `${repo.ownerName}/${repo.name}`, error: String(error) });
164 }
165 }
157166 const unstuck = unstickNow(app, current, now);
158167 const did = await driveOrBeat(app, current, now, picked, driveRepo);
159168 await breathe();
src/crew/parked.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * The parked-pulls pass (docs/features/parked-pulls.md): a pull with no push for `PARKED_HOURS` is
3 * offered to the crew once, with one note quoting its last verdict; a crew pull still parked as long
4 * again is closed, its branch kept. A person's pull is offered, never closed. What counts as parked
5 * is read in `flow/parked_read.ts`; state lives on the pull (the engine's notes, the push and reopen
6 * events).
7 */
8
9 import type { Database } from "bun:sqlite";
10 import type { App } from "../app.ts";
11 import { addComment, assignIssue, setIssueState } from "../actions/issues.ts";
12 import { listCrewRoles, type Agent } from "../core/agents.ts";
13 import { engineActor } from "../core/engine.ts";
14 import { getIssueById, type Issue } from "../core/issues.ts";
15 import type { Repo } from "../core/repos.ts";
16 import { getUserById } from "../core/users.ts";
17 import { HOUR_MS, PARKED_CLOSE_NOTE, PARKED_HOURS, parkedPulls, REOFFER_NOTE, type Parked } from "../flow/parked_read.ts";
18 import { createLog } from "../kernel/log.ts";
19 import { queueAgentRun } from "./dispatch.ts";
20 import { leastBusy, reviewersOf } from "./review.ts";
21
22 const log = createLog("crew");
23
24 /** The engine says it posts these; nobody wrote them by hand. */
25 const POSTED = "(The forge posts this; nobody wrote it by hand.)";
26
27 /** The newest verdict on the pull, for the offer's brief: whose, which, and its words. */
28 function lastVerdict(db: Database, pullId: string): { authorId: string; state: string; body: string } | undefined {
29 return (
30 db
31 .query<{ authorId: string; state: string; body: string }, [string]>(
32 "SELECT author_id AS authorId, state, body FROM review WHERE issue_id = ?1 ORDER BY created_at DESC, id DESC LIMIT 1",
33 )
34 .get(pullId) ?? undefined
35 );
36 }
37
38 /** What one pass did with one parked pull. */
39 export type ParkedMove =
40 | { readonly pull: number; readonly did: "offered"; readonly to: string }
41 | { readonly pull: number; readonly did: "noted" }
42 | { readonly pull: number; readonly did: "closed" }
43 | { readonly pull: number; readonly did: "waits"; readonly why: string };
44
45 /** The verdict's words as the note quotes them: the first lines, short. */
46 const quoted = (body: string): string => {
47 const words = body.replace(/\s+/g, " ").trim();
48 return words === "" ? "(no words with it)" : words.length > 300 ? `${words.slice(0, 299)}…` : words;
49 };
50
51 /** Who the offer goes to, and for what: a builder to answer changes asked for, else a reviewer. */
52 interface Recipient {
53 readonly to: Agent | undefined;
54 readonly reason: "feedback" | "review";
55 }
56
57 /**
58 * The recipient of one parked pull's offer: when the last verdict asked for changes and a builder
59 * may push its branch, its builder (assigned to it if it was not); with changes asked of a person's
60 * branch, nobody; otherwise the least busy reviewer.
61 */
62 function recipient(app: App, repo: Repo, parked: Parked, issue: Issue, changes: boolean): Recipient {
63 if (!changes) return { to: leastBusy(app.db, reviewersOf(app.db, repo.id)), reason: "review" };
64 if (parked.persons) return { to: undefined, reason: "feedback" };
65 const builders = listCrewRoles(app.db, repo.id)
66 .filter((c) => c.role === "builder")
67 .map((c) => c.agent);
68 const to = builders.find((b) => b.user.id === issue.assigneeId) ?? builders.find((b) => b.user.id === issue.authorId) ?? builders[0];
69 const by = repo.autonomyBy === null ? undefined : getUserById(app.db, repo.autonomyBy);
70 if (to !== undefined && issue.assigneeId !== to.user.id && by !== undefined) assignIssue(app, by, repo, issue, to.user);
71 return { to, reason: "feedback" };
72 }
73
74 /** The offer's note: who has it now (or that nobody can take it), the last verdict, and what comes next. */
75 function offerNote(parked: Parked, who: Agent | undefined, reason: Recipient["reason"], verdict: { state: string; body: string } | undefined): string {
76 const brief =
77 verdict === undefined ? "No verdict yet." : `The last verdict (${verdict.state === "changes_requested" ? "changes requested" : verdict.state}): ${quoted(verdict.body)}`;
78 if (who === undefined)
79 return `${REOFFER_NOTE} it sat ${PARKED_HOURS} h with no push, and nobody on the crew can take it from here${parked.persons ? " (a person's branch: no builder can push it)" : ""}, so it waits for its author. ${brief} ${POSTED}`;
80 const next = parked.persons ? "" : ` Still parked ${PARKED_HOURS} h from now, it is closed; the branch stays and Reopen restores it.`;
81 return `${REOFFER_NOTE} it sat ${PARKED_HOURS} h with no push, so ${who.user.username} has it now (${reason === "feedback" ? "to answer the last verdict" : "to review it"}). ${brief}${next} ${POSTED}`;
82 }
83
84 /** Offer one parked pull to the crew: its run queued to its recipient, and its note. */
85 function offer(app: App, repo: Repo, parked: Parked): ParkedMove {
86 const { pull } = parked;
87 const issue = getIssueById(app.db, pull.id);
88 if (issue === undefined) return { pull: pull.number, did: "waits", why: "no pull row" };
89 const verdict = lastVerdict(app.db, pull.id);
90 const { to, reason } = recipient(app, repo, parked, issue, verdict?.state === "changes_requested");
91 const current = getIssueById(app.db, issue.id) ?? issue;
92 const who = to !== undefined && queueAgentRun(app, repo, current, to, reason) !== undefined ? to : undefined;
93 addComment(app, engineActor(app.db), repo, current, offerNote(parked, who, reason, verdict));
94 log.info("parked pull offered to the crew again", { repo: `${repo.ownerName}/${repo.name}`, pull: pull.number, to: who?.user.username ?? "nobody" });
95 return who === undefined ? { pull: pull.number, did: "noted" } : { pull: pull.number, did: "offered", to: who.user.username };
96 }
97
98 /** Close a crew pull still parked a second period after its offer: the reason, and how to undo it. */
99 function close(app: App, repo: Repo, parked: Parked): ParkedMove {
100 const issue = getIssueById(app.db, parked.pull.id);
101 if (issue === undefined || issue.state !== "open") return { pull: parked.pull.number, did: "waits", why: "not open" };
102 const engine = engineActor(app.db);
103 if (!setIssueState(app, engine, repo, issue, "closed", { reason: "parked" }).ok)
104 return { pull: parked.pull.number, did: "waits", why: "the close was refused" };
105 addComment(
106 app,
107 engine,
108 repo,
109 issue,
110 `${PARKED_CLOSE_NOTE} it sat ${PARKED_HOURS} h with no push, was offered to the crew again, and sat ${PARKED_HOURS} h more. The branch is kept: Reopen restores the pull as it was, and the crew picks it up again. ${POSTED}`,
111 );
112 log.info("parked pull closed", { repo: `${repo.ownerName}/${repo.name}`, pull: parked.pull.number });
113 return { pull: parked.pull.number, did: "closed" };
114 }
115
116 /**
117 * One pass over `repo`'s parked pulls: each not yet offered since it last moved is offered; each
outdated

Stray double blank line; also remove the to! assertions in offer() by narrowing.

118 * offered a period ago and still parked is closed, a person's excepted.
119 */
120 export function moveParked(app: App, repo: Repo, now: Date = new Date()): ParkedMove[] {
121 return parkedPulls(app.db, repo, now).map((parked) => {
122 if (parked.offered === undefined) return offer(app, repo, parked);
123 if (parked.persons) return { pull: parked.pull.number, did: "waits", why: "a person's pull is offered, never closed" };
124 if (now.getTime() - Date.parse(parked.offered) < PARKED_HOURS * HOUR_MS)
125 return { pull: parked.pull.number, did: "waits", why: "offered; closes a period after" };
126 return close(app, repo, parked);
127 });
128 }
129
130 /** How often one repository's pulls are read for this: hours are its unit, a tick is seconds. */
131 export const PARKED_EVERY_MS = 5 * 60_000;
132 const lastPass = new WeakMap<App, Map<string, number>>();
133
134 /** Whether the pass is due in `repoId` now, and if so, noted as made. */
135 export function parkedDue(app: App, repoId: string, now: Date): boolean {
136 const seen = lastPass.get(app) ?? new Map<string, number>();
137 lastPass.set(app, seen);
138 const last = seen.get(repoId);
139 if (last !== undefined && now.getTime() - last < PARKED_EVERY_MS) return false;
140 seen.set(repoId, now.getTime());
141 return true;
142 }
src/flow/lanes_read.ts +4
@@ -37,6 +37,7 @@ import { readTypicals, type Typicals } from "./lane_times.ts";
3737 import { shortTitle } from "./moving.ts";
3838 import { getUserById } from "../core/users.ts";
3939 import { reviewSetOf } from "../web/studio/review_set.ts";
40 import { parkedLines, type ParkedLine } from "./parked_read.ts";
4041
4142 export const LANES = [
4243 "asked",
@@ -121,6 +122,8 @@ export interface StripPart {
121122 readonly weekSpendUsd: number;
122123 readonly ceilingUsd: number | null;
123124 readonly needs: readonly { readonly says: string; readonly href: string }[];
125 /** Pulls that sat with no push, and those closed for it in the last day (`parked_read.ts`). */
126 readonly parked?: readonly ParkedLine[];
124127 }
125128
126129 export interface LanePicture {
@@ -706,6 +709,7 @@ export function readSlow(
706709 weekSpendUsd: spend?.usd ?? 0,
707710 ceilingUsd: forge.ceilingUsd,
708711 needs,
712 parked: parkedLines(db, now),
709713 },
710714 figures: readFigures(db, now, kpis),
711715 asks: asksOf(db, viewers, now),
src/flow/parked_read.ts added +153
@@ -0,0 +1,153 @@
1 /**
2 * What the parked-pulls pass reads (`crew/parked.ts` acts on it): the open pulls of a repository
3 * that have sat, and the Bridge's one line for each, and for each one it closed in the last day.
4 * Plain rows: the push and reopen events by their (repo, kind, number) index, the engine's notes by
5 * their first words. What the pass does is in docs/features/parked-pulls.md.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { getHold } from "../core/holds.ts";
10 import { getPull, type Pull } from "../core/pulls.ts";
11 import { canRead, getRepoById, getReposByIds, type Repo } from "../core/repos.ts";
12 import { reviewSummary } from "../core/reviews.ts";
13 import type { User } from "../core/users.ts";
14 import { authorsInRepoPull } from "../crew/authors_pull.ts";
15
16 /** The first words of the offer note: how the pass finds that it made one. */
17 export const REOFFER_NOTE = "Parked, offered to the crew again:";
18 /** The first words of the close note. */
19 export const PARKED_CLOSE_NOTE = "Closed by the forge, parked:";
20
21 export const HOUR_MS = 3_600_000;
22 /** How long a pull sits with no push before it is offered again, and again before it closes. */
23 export const PARKED_HOURS = 6;
24
25 /** One open pull that has sat: since when, and the offer made since then, if one was. */
26 export interface Parked {
27 readonly pull: Pull;
28 readonly title: string;
29 /** The newest push or reopen, else when it was opened. */
30 readonly moved: string;
31 /** When the offer note was posted for this stretch, if it was. */
32 readonly offered: string | undefined;
33 /** A person's pull: offered, never closed. */
34 readonly persons: boolean;
35 }
36
37 /**
38 * The open pulls of one repository (?1) with no push or reopen since ?2, newest first by when
39 * they last moved, nothing queued or running on them, and the offer note (?3, its first words)
40 * posted since then.
41 */
42 const SAT_SQL = `SELECT i.id, i.number, i.title, m.moved,
43 (SELECT MAX(c.created_at) FROM comment c WHERE c.issue_id = i.id AND c.body LIKE ?3 AND c.created_at >= m.moved) AS offered
44 FROM (SELECT q.id, MAX(q.created_at,
45 COALESCE((SELECT MAX(e.created_at) FROM event e WHERE e.repo_id = q.repo_id AND e.kind = 'pull.pushed'
46 AND json_extract(e.payload, '$.number') = q.number + 0), ''),
47 COALESCE((SELECT MAX(e.created_at) FROM event e WHERE e.repo_id = q.repo_id AND e.kind = 'pull.reopened'
48 AND json_extract(e.payload, '$.number') = q.number + 0), '')) AS moved
49 FROM issue q WHERE q.repo_id = ?1 AND q.kind = 'pull' AND q.state = 'open') m
50 JOIN issue i ON i.id = m.id
51 JOIN pull p ON p.issue_id = i.id
52 WHERE p.merged_at IS NULL AND p.draft_run IS NULL AND m.moved <= ?2
53 AND NOT EXISTS (SELECT 1 FROM run r WHERE r.issue_id = i.id AND r.state IN ('queued', 'running'))
54 ORDER BY m.moved DESC`;
55
56 /** The repositories the pass runs in: the autonomous ones, with the person the forge acts as. */
57 const AUTONOMOUS = "r.autonomy = 'autonomous' AND r.autonomy_by IS NOT NULL";
58
59 /** The pulls the pass closed (?1, the close note's first words) since ?2 that are still closed. */
60 const CLOSED_SQL = `SELECT r.id AS repoId, u.username AS owner, r.name, i.number, i.title, c.created_at AS at
61 FROM comment c JOIN issue i ON i.id = c.issue_id JOIN repo r ON r.id = i.repo_id JOIN user u ON u.id = r.owner_id
62 WHERE c.body LIKE ?1 AND c.created_at >= ?2 AND i.state = 'closed' AND ${AUTONOMOUS}
63 ORDER BY c.created_at DESC LIMIT 20`;
64
65 /** The head's newest check failed: the red flow has it (`stale_reds.ts`). */
66 const headRed = (db: Database, pull: Pull): boolean =>
67 db
68 .query<
69 { state: string },
70 [string, string]
71 >("SELECT state FROM run WHERE issue_id = ?1 AND kind = 'check' AND commit_oid = ?2 ORDER BY id DESC LIMIT 1")
72 .get(pull.id, pull.headOid)?.state === "failed";
73
74 /** The pulls of `repo` that are parked now: sat `hours`, and none of the other flows has them. */
75 export function parkedPulls(db: Database, repo: Repo, now: Date, hours: number = PARKED_HOURS): Parked[] {
76 const rows = db
77 .query<{ id: string; number: number; title: string; moved: string; offered: string | null }, [string, string, string]>(SAT_SQL)
78 .all(repo.id, new Date(now.getTime() - hours * HOUR_MS).toISOString(), `${REOFFER_NOTE}%`);
79 const out: Parked[] = [];
80 for (const row of rows) {
81 const pull = getPull(db, repo.id, row.number);
82 if (pull === undefined || getHold(db, pull.id) !== undefined) continue;
83 if (reviewSummary(db, pull.id, pull.headOid).approvals > 0 || headRed(db, pull)) continue;
84 out.push({ pull, title: row.title, moved: row.moved, offered: row.offered ?? undefined, persons: authorsInRepoPull(pull) });
85 }
86 return out;
87 }
88
89 /** One line on the Bridge: the pull, and one fact about it. */
90 export interface ParkedLine {
91 readonly repoId: string;
92 readonly ref: string;
93 readonly says: string;
94 readonly href: string;
95 /** Where Reopen posts, for a closed one. */
96 readonly reopen?: string;
97 }
98
99 /** When an offered crew pull closes, from its offer. */
100 const closesIn = (offered: string, hours: number, now: Date): string => {
101 const left = Date.parse(offered) + hours * HOUR_MS - now.getTime();
102 return left <= 0 ? "closes on the next pass" : `closes in ${Math.max(1, Math.round(left / HOUR_MS))} h`;
103 };
104
105 /** Its one fact: not offered yet, offered (a person's), or when it closes. */
106 const factOf = (p: Parked, now: Date): string =>
107 p.offered === undefined ? `no push for ${PARKED_HOURS} h` : p.persons ? "offered to the crew" : closesIn(p.offered, PARKED_HOURS, now);
108
109 /**
110 * Every parked pull of an autonomous repository, then each one the pass closed there in the last
111 * day that is still closed, with Reopen. Read once for the forge; a viewer sees them through
112 * {@link parkedFor}.
113 */
114 export function parkedLines(db: Database, now: Date = new Date()): ParkedLine[] {
115 const repos = db.query<{ id: string }, []>(`SELECT r.id FROM repo r WHERE ${AUTONOMOUS}`).all();
116 const out: ParkedLine[] = [];
117 for (const { id } of repos) {
118 const repo = getRepoById(db, id);
119 if (repo === undefined) continue;
120 for (const p of parkedPulls(db, repo, now)) {
outdated

Unscoped: any repo, any visibility, any autonomy. Scope to the repos this view may show (finding 1).

121 const ref = `${repo.ownerName}/${repo.name}#${p.pull.number}`;
122 out.push({
123 repoId: repo.id,
124 ref,
125 says: `${ref} ${p.title}: ${factOf(p, now)}.`,
126 href: `/${repo.ownerName}/${repo.name}/pulls/${p.pull.number}`,
127 });
128 }
129 }
130 const closed = db
131 .query<{ repoId: string; owner: string; name: string; number: number; title: string }, [string, string]>(CLOSED_SQL)
132 .all(`${PARKED_CLOSE_NOTE}%`, new Date(now.getTime() - 24 * HOUR_MS).toISOString());
133 for (const c of closed) {
134 const thread = `/${c.owner}/${c.name}/pulls/${c.number}`;
135 const ref = `${c.owner}/${c.name}#${c.number}`;
136 out.push({ repoId: c.repoId, ref, says: `${ref} ${c.title}: closed; Reopen restores it.`, href: thread, reopen: `${thread}/state` });
137 }
138 return out;
139 }
140
141 /** The lines `viewer` may read: those of repositories they can read, never a private one they cannot. */
142 export function parkedFor(db: Database, viewer: User, lines: readonly ParkedLine[] | undefined): ParkedLine[] {
143 if (lines === undefined || lines.length === 0) return [];
144 const repos = getReposByIds(db, [...new Set(lines.map((l) => l.repoId))]);
145 return lines.filter((l) => {
146 const repo = repos.get(l.repoId);
147 return repo !== undefined && canRead(db, repo, viewer);
148 });
149 }
150
151 /** The terminal home's lines: the same, a closed one saying where Reopen is there (`o` on its pull). */
152 export const terminalLines = (lines: readonly ParkedLine[], most = 5): string[] =>
153 lines.slice(0, most).map((l) => (l.reopen === undefined ? l.says : l.says.replace(/Reopen restores it\.$/, "o on its pull reopens it.")));
src/tui/screens/dashboard.ts +14 −2
@@ -57,6 +57,7 @@ import { quietFor, quietText } from "../../web/studio/home_empty.ts";
5757 import { firstWeekText } from "../../web/first_week.ts";
5858 import { firstWrong, firstWrongText, readFacts } from "../../web/first_wrong.ts";
5959 import { lanePicture } from "../../flow/lanes.ts";
60 import { parkedFor, terminalLines } from "../../flow/parked_read.ts";
6061 import { startedFromText } from "../../web/started_from.ts";
6162 import { publicOrigin } from "../../core/public_origin.ts";
6263 import { FEED_MORE, sinceDigest } from "../../web/studio/since.ts";
@@ -332,6 +333,8 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
332333 * One line per fired flow alarm; an admin reads every repository, anyone else public ones alone.
333334 */
334335 let alarms: string[] = [];
336 /** The Bridge's parked pulls, one line each (`flow/parked_read.ts`), as the web home lists them. */
337 let parked: string[] = [];
335338 /** The panels this admin pinned to the web home, by title and board, in their order. */
336339 let panelLines: string[] = [];
337340 const filter = new Filter();
@@ -492,9 +495,11 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
492495 };
493496
494497 const loadWrong = async (): Promise<void> => {
495 if (f.user?.isAdmin === true) {
498 if (f.user !== undefined) {
496499 const picture = await lanePicture(f.db, { dataDir: f.app.config.dataDir, ceilingUsd: forgeCeiling(f.app.config), viewer: f.user.id }, "lane");
497 crewWeek = picture?.strip?.week ?? null;
500 if (f.user.isAdmin) crewWeek = picture?.strip?.week ?? null;
501 // Every viewer reads the parked pulls of the repositories they can read, as on the web home.
502 parked = terminalLines(parkedFor(f.db, f.user, picture?.strip?.parked));
498503 }
499504 readWrong();
500505 ctx.invalidate();
@@ -1338,6 +1343,13 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
13381343 );
13391344 body = rest!;
13401345 }
1346 if (parked.length > 0) {
1347 const [strip, rest] = split(body, "v", [len(parked.length), fill(1)]);
1348 parked.forEach((line, i) =>
1349 s.text(strip!.x, strip!.y + i, truncate(line, strip!.w), style(c.mutedFg, c.bg), strip!.x + strip!.w),
1350 );
1351 body = rest!;
1352 }
13411353 if (clientLines.length > 0) {
13421354 // The next steps are the last line and always stay.
13431355 const lines = clientLines.length > 5 ? [...clientLines.slice(0, 4), clientLines.at(-1)!] : clientLines;
src/web/pages/home_flow.ts +3
@@ -78,6 +78,8 @@ import { untoldAnswer, markTold } from "../../core/requests.ts";
7878 import { YOURE_IN_MESSAGE } from "../../actions/users.ts";
7979 import { spawnedForge } from "../../spawn/claim.ts";
8080 import { startedFromLine } from "../started_from.ts";
81 import { parkedSection } from "../parked_lines.ts";
82 import { parkedFor } from "../../flow/parked_read.ts";
8183 import { firstWeekBlock } from "../first_week.ts";
8284
8385
@@ -590,6 +592,7 @@ export async function homeFlowPage(ctx: Ctx, known?: { readonly spawned: Awaited
590592 </header>
591593 ${mine ? askedSection(ctx, user) : null}
592594 ${main}
595 ${parkedSection(parkedFor(ctx.app.db, user, picture?.strip?.parked))}
593596 ${slots}
594597 ${before}
595598 ${strip}
src/web/parked_lines.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * The Bridge's parked pulls (`flow/parked_read.ts`), at every width and for every viewer, each line
3 * the pull and one fact, a closed one with Reopen in place (the pull page's own form). Nothing at
4 * all when there is none. What the crew does with them is in docs/features/parked-pulls.md.
5 */
6
7 import type { ParkedLine } from "../flow/parked_read.ts";
8 import { html, type Html } from "./html.ts";
9 import { btn, row, rowList } from "./ui.ts";
10
11 export function parkedSection(lines: readonly ParkedLine[] | undefined): Html | null {
12 if (lines === undefined || lines.length === 0) return null;
13 return html`<section id="parked" aria-labelledby="parked-title">
14 <h2 id="parked-title" class="small">Parked pulls</h2>
outdated

Principle 1/8: hf-parked is a new class not documented under docs/design/areas/; use a named component or document it.

outdated

Principle 6/7: fine as rows, but the section is rendered only when wide (home_flow.ts), so phone width gets no Reopen. Render it at all widths.

15 <p class="small muted">Pulls nobody has pushed to in six hours.</p>
16 ${rowList(
outdated

Principle 1 and 8: this sentence restates what the lines below say. Say the one thing plainly, for example 'Pulls nobody has touched for hours.', and let each row carry one fact.

17 lines.map((l) =>
18 row({
19 href: l.href,
20 title: l.says,
21 ...(l.reopen === undefined
22 ? {}
23 : {
24 trail: html`<form method="post" action="${l.reopen}"><input type="hidden" name="state" value="open" />${btn("Reopen", { size: "sm", label: `Reopen ${l.ref}` })}</form>`,
25 }),
26 }),
27 ),
28 { label: "Parked pulls" },
29 )}
30 </section>`;
31 }
test/parked-pulls.test.ts added +247
@@ -0,0 +1,247 @@
1 /**
2 * A parked pull does not sit (`crew/parked.ts`, `flow/parked_read.ts`): a crew pull with changes
3 * requested and no push for six hours is offered to its builder once, with the verdict
4 * quoted; still parked a period later it is closed with the reason, its branch kept; reopened, it
5 * starts again. A person's pull is offered, never closed. Each viewer's Bridge, on both doors, says each in one line.
6 */
7 import { afterEach, beforeEach, 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 { setIssueState } from "../src/actions/issues.ts";
14 import { openPull } from "../src/actions/pulls.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { getIssueById, listComments } from "../src/core/issues.ts";
17 import { getPull, type Pull } from "../src/core/pulls.ts";
18 import { getRepoById, type Repo } from "../src/core/repos.ts";
19 import { submitReview } from "../src/core/reviews.ts";
20 import { createUser, type User } from "../src/core/users.ts";
21 import { moveParked, parkedDue, PARKED_EVERY_MS } from "../src/crew/parked.ts";
22 import { PARKED_CLOSE_NOTE, parkedFor, parkedLines, REOFFER_NOTE, terminalLines } from "../src/flow/parked_read.ts";
23 import { createForgeApp } from "../src/tui/forge.ts";
24 import { headlessTerminal } from "../src/tui/term/terminal.ts";
25 import { settleApp } from "./helpers/tui.ts";
26 import { setHold } from "../src/core/holds.ts";
27 import { resolveOid } from "../src/git/merge.ts";
28 import { repoDir } from "../src/git/repos.ts";
29 import { parkedSection } from "../src/web/parked_lines.ts";
30
31 const HOUR = 3_600_000;
32 let dataDir: string, app: App, alice: User, builder: User, reviewer: User, repo: Repo;
33
34 /**
35 * A pull of `branch`, said to be `author`'s, opened `hoursAgo`: asked for changes by the reviewer,
36 * or with `verdict` an approval of an older head, or no verdict at all.
37 */
38 async function sitting(branch: string, author: User, hoursAgo: number, verdict: "changes" | "old approval" | "none" = "changes"): Promise<Pull> {
39 await commitToBranch(app, alice, repo, { branch, base: "main", message: branch, files: [{ path: `${branch}.txt`, content: "x\n" }] });
40 const opened = await openPull(app, alice, repo, { title: `Change ${branch}`, baseBranch: "main", headBranch: branch });
41 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
42 const at = new Date(Date.now() - hoursAgo * HOUR).toISOString();
43 app.db.query("UPDATE issue SET author_id = ?2, created_at = ?3 WHERE id = ?1").run(opened.value.id, author.id, at);
44 // Nothing is running on it: what the open queued, if anything, is over.
45 app.db
46 .query("UPDATE run SET state = 'ok', finished_at = ?2 WHERE issue_id = ?1 AND state IN ('queued', 'running')")
47 .run(opened.value.id, at);
48 const pull = getPull(app.db, repo.id, opened.value.number)!;
49 if (verdict === "none") return pull;
50 expect(
51 submitReview(app.db, {
52 issueId: pull.id,
53 authorId: reviewer.id,
54 state: verdict === "changes" ? "changes_requested" : "approved",
55 commitOid: verdict === "changes" ? pull.headOid : pull.baseOid,
56 body: "Name the button for what it does.",
57 }).ok,
58 ).toBe(true);
59 return pull;
60 }
61
62 /** The runs the pass queued are over, as a run that pushed nothing ends. */
63 const runsEnd = (pullId: string) =>
64 app.db
65 .query("UPDATE run SET state = 'failed', finished_at = ?2 WHERE issue_id = ?1 AND state IN ('queued', 'running')")
66 .run(pullId, new Date().toISOString());
67
68 const notes = (pullId: string, first: string) => listComments(app.db, pullId).filter((c) => c.body.startsWith(first));
69 const later = (hours: number) => new Date(Date.now() + hours * HOUR);
70
71 beforeEach(async () => {
72 dataDir = await mkdtemp(join(tmpdir(), "forge-parked-"));
73 app = createApp({ dataDir, port: 0 });
74 const made = await createUser(app.db, {
75 origin: "seed",
76 trusted: true,
77 username: "alice",
78 email: "[email protected]",
79 password: "a-good-passphrase",
80 adminIfFirst: true,
81 });
82 if (!made.ok) throw new Error(made.error);
83 alice = made.value;
84 const r = await createRepo(app, alice, { name: "garden", visibility: "public" });
85 if (!r.ok) throw new Error(String(r.error));
86 await commitToBranch(app, alice, r.value, { branch: "main", message: "base", files: [{ path: "README.md", content: "# garden\n" }] });
87 app.db.query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1").run(r.value.id, alice.id);
88 repo = getRepoById(app.db, r.value.id)!;
89 const b = await createAgent(app, alice, { username: "builderbot", roles: ["builder"] });
90 const v = await createAgent(app, alice, { username: "reviewbot", roles: ["reviewer"] });
91 if (!b.ok || !v.ok) throw new Error("agents");
92 builder = b.value.user;
93 reviewer = v.value.user;
94 expect(addToCrew(app, alice, repo, "builderbot", "builder").ok).toBe(true);
95 expect(addToCrew(app, alice, repo, "reviewbot", "reviewer").ok).toBe(true);
96 });
97
98 afterEach(async () => {
99 app.close();
100 await rm(dataDir, { recursive: true, force: true });
101 });
102
103 test("a crew pull parked past six hours is offered to its builder once, the verdict quoted; under it, nothing", async () => {
104 const young = await sitting("young", builder, 2);
105 const pull = await sitting("old", builder, 7);
106 const moves = moveParked(app, repo, new Date());
107 expect(moves).toEqual([{ pull: pull.number, did: "offered", to: "builderbot" }]);
108 const run = app.db
109 .query<{ reason: string; agent: string }, [string]>("SELECT reason, actor_id AS agent FROM run WHERE issue_id = ?1 AND kind = 'agent'")
110 .get(pull.id);
111 expect(run).toEqual({ reason: "feedback", agent: builder.id });
112 const said = notes(pull.id, REOFFER_NOTE);
113 expect(said).toHaveLength(1);
114 expect(said[0]!.body).toContain("Name the button for what it does.");
115 expect(notes(young.id, REOFFER_NOTE)).toHaveLength(0);
116 // Its run in flight, the next pass leaves it; ended without a push, it waits out the second period.
117 expect(moveParked(app, repo, new Date())).toEqual([]);
118 runsEnd(pull.id);
119 expect(moveParked(app, repo, later(1))).toEqual([{ pull: pull.number, did: "waits", why: "offered; closes a period after" }]);
120 expect(notes(pull.id, REOFFER_NOTE)).toHaveLength(1);
121 });
122
123 test("still parked a period after the offer, a crew pull is closed with its reason, the branch kept; reopened, it starts again", async () => {
124 const pull = await sitting("stale", builder, 7);
125 moveParked(app, repo, new Date());
126 runsEnd(pull.id);
127 expect(moveParked(app, repo, later(7))).toEqual([{ pull: pull.number, did: "closed" }]);
128 expect(getIssueById(app.db, pull.id)?.state).toBe("closed");
129 expect(notes(pull.id, PARKED_CLOSE_NOTE)[0]!.body).toContain("The branch is kept: Reopen restores the pull");
130 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
131 expect(await resolveOid(dir, `refs/heads/${pull.headBranch}`)).toBe(pull.headOid);
132 // The Bridge has it, with Reopen.
133 const closed = parkedLines(app.db, later(7)).find((l) => l.ref === `alice/garden#${pull.number}`);
134 expect(closed?.says).toBe(`alice/garden#${pull.number} Change stale: closed; Reopen restores it.`);
135 // The terminal home says the same, with its own way to reopen.
136 expect(terminalLines([closed!])[0]).toContain("o on its pull reopens it.");
137 expect(closed?.reopen).toBe(`/alice/garden/pulls/${pull.number}/state`);
138 expect(String(parkedSection([closed!]))).toContain(`action="/alice/garden/pulls/${pull.number}/state"`);
139 // Reopened, the clock starts again from the reopen: the old offer no longer counts.
140 app.db.query("UPDATE comment SET created_at = ?2 WHERE issue_id = ?1").run(pull.id, new Date(Date.now() - HOUR).toISOString());
141 expect(setIssueState(app, alice, repo, getIssueById(app.db, pull.id)!, "open").ok).toBe(true);
142 expect(moveParked(app, repo, later(1))).toEqual([]);
143 expect(moveParked(app, repo, later(7))).toEqual([{ pull: pull.number, did: "offered", to: "builderbot" }]);
144 });
145
146 test("the owner's own pull is offered and never closed", async () => {
147 const own = await sitting("mine", alice, 7);
148 // No builder can push a person's branch: with changes asked for, the offer is the note alone.
149 expect(moveParked(app, repo, new Date())).toEqual([{ pull: own.number, did: "noted" }]);
150 expect(notes(own.id, REOFFER_NOTE)[0]!.body).toContain("a person's branch: no builder can push it");
151 expect(moveParked(app, repo, later(13))).toEqual([{ pull: own.number, did: "waits", why: "a person's pull is offered, never closed" }]);
152 expect(getIssueById(app.db, own.id)?.state).toBe("open");
153 const line = parkedLines(app.db, later(13)).find((l) => l.ref === `alice/garden#${own.number}`);
154 expect(line?.says).toBe(`alice/garden#${own.number} Change mine: offered to the crew.`);
155 expect(line?.reopen).toBeUndefined();
156 });
157
158 test("one approved on its head, and one with a run in flight, are left alone", async () => {
159 const approved = await sitting("approved", builder, 7);
160 expect(submitReview(app.db, { issueId: approved.id, authorId: reviewer.id, state: "approved", commitOid: approved.headOid, body: "" }).ok).toBe(true);
161 const busy = await sitting("busy", builder, 7);
162 app.db
163 .query("INSERT INTO run (id, repo_id, kind, env, issue_id, commit_oid, state, created_at) VALUES ('busy1', ?1, 'check', 'pull', ?2, ?3, 'running', ?4)")
164 .run(repo.id, busy.id, busy.headOid, new Date().toISOString());
165 expect(moveParked(app, repo, new Date())).toEqual([]);
166 expect(parkedLines(app.db, new Date())).toEqual([]);
167 });
168
169 test("the Bridge's lines are each viewer's: a private repository's parked and closed pulls only for those who read it", async () => {
170 const made = await createRepo(app, alice, { name: "vault", visibility: "private" });
171 if (!made.ok) throw new Error(String(made.error));
172 await commitToBranch(app, alice, made.value, { branch: "main", message: "base", files: [{ path: "README.md", content: "# vault\n" }] });
173 app.db.query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1").run(made.value.id, alice.id);
174 const vault = getRepoById(app.db, made.value.id)!;
175 const keep = repo;
176 repo = vault;
177 try {
178 await sitting("secret", builder, 7);
179 const shut = await sitting("shut", builder, 7);
180 moveParked(app, vault, new Date());
181 runsEnd(shut.id);
182 app.db.query("UPDATE run SET state = 'failed' WHERE issue_id IN (SELECT id FROM issue WHERE repo_id = ?1) AND state IN ('queued','running')").run(vault.id);
183 expect(setIssueState(app, alice, vault, getIssueById(app.db, shut.id)!, "closed").ok).toBe(true);
184 app.db.query("INSERT INTO comment (id, issue_id, author_id, body, created_at) VALUES ('cn1', ?1, ?2, ?3, ?4)").run(shut.id, alice.id, `${PARKED_CLOSE_NOTE} test`, new Date().toISOString());
185 } finally {
186 repo = keep;
187 }
188 const lines = parkedLines(app.db, new Date());
189 const inVault = lines.filter((l) => l.ref.startsWith("alice/vault#"));
190 expect(inVault.length).toBeGreaterThanOrEqual(2);
191 expect(inVault.some((l) => l.reopen !== undefined)).toBe(true);
192 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
193 if (!bob.ok) throw new Error(bob.error);
194 expect(parkedFor(app.db, bob.value, lines).filter((l) => l.ref.startsWith("alice/vault#"))).toEqual([]);
195 expect(parkedFor(app.db, alice, lines).filter((l) => l.ref.startsWith("alice/vault#"))).toHaveLength(inVault.length);
196 });
197
198 test("the terminal home shows the lines, a closed one with o on its pull to reopen it", async () => {
199 const pull = await sitting("term", builder, 7);
200 moveParked(app, repo, new Date());
201 runsEnd(pull.id);
202 moveParked(app, repo, later(7));
203 const terminal = headlessTerminal(220, 40);
204 const { app: tui } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: alice }, { terminal, exitHooks: false });
205 tui.start();
206 await settleApp(tui);
207 const text = tui.screen.toText();
208 tui.stop();
209 expect(text).toContain(`alice/garden#${pull.number} Change term: closed; o on its pull reopens it.`);
210 });
211
212 test("with no verdict, or an approval of an older head, the offer is a review run to the reviewer", async () => {
213 const none = await sitting("unread", builder, 7, "none");
214 const old = await sitting("moved-on", builder, 7, "old approval");
215 const moves = moveParked(app, repo, new Date());
216 expect(moves).toEqual([
217 { pull: old.number, did: "offered", to: "reviewbot" },
218 { pull: none.number, did: "offered", to: "reviewbot" },
219 ]);
220 const reasons = app.db
221 .query<{ reason: string }, [string, string]>("SELECT reason FROM run WHERE kind = 'agent' AND issue_id IN (?1, ?2)")
222 .all(none.id, old.id)
223 .map((r) => r.reason);
224 expect(reasons).toEqual(["review", "review"]);
225 expect(notes(none.id, REOFFER_NOTE)[0]!.body).toContain("No verdict yet.");
226 });
227
228 test("a held pull, a draft and one whose head's check failed are left to their own flows", async () => {
229 const held = await sitting("held", builder, 7);
230 const draft = await sitting("draft", builder, 7);
231 const red = await sitting("red", builder, 7);
232 setHold(app.db, held.id, alice.id, "mine to finish");
233 app.db.query("UPDATE pull SET draft_run = 'r1' WHERE issue_id = ?1").run(draft.id);
234 app.db
235 .query("INSERT INTO run (id, repo_id, kind, env, issue_id, commit_oid, state, created_at) VALUES ('red1', ?1, 'check', 'pull', ?2, ?3, 'failed', ?4)")
236 .run(repo.id, red.id, red.headOid, new Date(Date.now() - 7 * HOUR).toISOString());
237 expect(moveParked(app, repo, new Date())).toEqual([]);
238 expect(parkedLines(app.db, new Date())).toEqual([]);
239 });
240
241 test("the pass runs at most once per repository in each five minutes", () => {
242 const at = new Date();
243 expect(parkedDue(app, repo.id, at)).toBe(true);
244 expect(parkedDue(app, repo.id, new Date(at.getTime() + 60_000))).toBe(false);
245 expect(parkedDue(app, "another", new Date(at.getTime() + 60_000))).toBe(true);
246 expect(parkedDue(app, repo.id, new Date(at.getTime() + PARKED_EVERY_MS))).toBe(true);
247 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs