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

The needs stack recommends four reversible fixes: retry a parked run, dismiss stale notices, wake a stopped app, close a landed pull #12361

Merged opened this

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

Merged

torque/forge:torque/12277-the-needs-stack-recommends-four-reversib → main 12 commits fork 4 threads · 4 unresolved

  • Merged. torque/12277-the-needs-stack-recommends-four-reversib was merged into main as 652cd9c.

Review

Sign in to review this change.
14 files changed +546 −27
docs/features/forge-needs.md +11
@@ -24,3 +24,14 @@ In the terminal, `a` reports the same `done` rows, or the `refused` reason.
2424 `forge {apply: "recommended"}` plans (dry by default); `dryRun: false` does the safe ones through the asks' bulk actions (`asks_bulk.ts`), so the per-row access check and the receipt are theirs. Undo with `asks_act {action: "undo", operation}`. The rest is returned untouched under `left`.
2525
2626 Each forge need is one of `forgeNeedList` (`src/actions/health.ts`): the rollout, each platform incident, the vitals' needs and the week's flakes, the very list `forgeNeeds`, the health answer and the board's forge strip print (#12269). One health read per request, and none for anyone not a site admin.
27
28 ## The four fixes that are safe to take (#12277)
29
30 `apply: "recommended"` takes only fixes that are reversible and have a receipt (`undo` names the `asks_act` call):
31
32 - **Retry** a parked issue whose newest agent run failed or was cancelled: the run is queued again; Undo cancels it. One parked issue to a repository (two share a row, which is the owner's to untangle).
33 - **Dismiss** a notice older than the stale window (`STALE_DAYS`, 30): it asks again when something new happens; Undo takes the dismissal back.
34 - **Wake** a stopped (archived) app you administer when a person filed an issue on it since it was stopped: it is restored; Undo archives it again. Listed after the asks, and not counted in the home's "N things need you" (the home draws only the asks).
35 - **Close** a pull whose head the base already holds (read by the stale-ask sweep: `isLandedPull`), or one the crew advised closing: Undo opens it again.
36
37 A merge is never one: its only undo is a revert pull, so it stays a question for the owner.
src/actions/asks_bulk.ts +22
@@ -39,6 +39,7 @@ export const ASK_ACTIONS: Readonly<Record<string, string>> = {
3939 ship: "ship",
4040 close: "close",
4141 replan: "replan",
42 retry: "retry",
4243 };
4344
4445 /** The most asks one action takes. */
@@ -142,6 +143,27 @@ export async function applyAsksBulk(
142143 return ok({ ...op.value, skipped: r.value.skipped, line: doneWords(op.value.reversible) });
143144 }
144145
146 /**
147 * Wake stopped apps (#12277): restore each archived repository, receipted
148 * under the asks' own prefix so the same undo (`undoAsksBulk`) puts them
149 * away again. A person's own selection, named by repository id.
150 */
151 export async function applyWakeBulk(
152 app: App,
153 actor: User | undefined,
154 repoIds: readonly string[],
155 ): Promise<Result<Operation & { skipped: Skipped[]; line: string }, FleetError>> {
156 if (!actor) return err({ code: "unauthorized", message: SIGN_IN_TO_ACT });
157 if (repoIds.length === 0 || repoIds.length > BULK_MAX)
158 return err({ code: "bad_action", message: `wake takes one to ${BULK_MAX} apps` });
159 const op = await applyFleetIds(app, actor, "repo", repoIds, `${ASKS_QUERY_PREFIX}${repoIds.length} selected`, {
160 verb: "archive",
161 value: false,
162 });
163 if (!op.ok) return op;
164 return ok({ ...op.value, skipped: [], line: doneWords(op.value.reversible) });
165 }
166
145167 /**
146168 * A bulk action on asks, for the one person who took it — never another,
147169 * a site admin included: a person's asks are theirs, and so is undoing
src/actions/asks_words.ts +2
@@ -28,6 +28,8 @@ export const VERB_WORDS: Readonly<Record<string, string>> = {
2828 ship: "Ship",
2929 close: "Close",
3030 replan: "Hand back to the planner",
31 retry: "Retry",
32 archive: "Wake",
3133 };
3234
3335 /**
src/actions/fleet.ts +10 −3
@@ -43,7 +43,7 @@ import {
4343 getReposByIds,
4444 type Repo,
4545 } from "../core/repos.ts";
46 import { latestRunsForIssues } from "../core/runs.ts";
46 import { latestRunsForIssues, newestAgentRun } from "../core/runs.ts";
4747 import { isStalePull } from "../crew/stale_asks.ts";
4848 import { askDismissedBy } from "../web/studio/asks.ts";
4949 import { mutedRepos } from "../core/interactions.ts";
@@ -194,6 +194,9 @@ function loadTargets(
194194 return seats;
195195 };
196196 const peers: ReadonlySet<string> = new Set(ids);
197 const retrying = new Set(
198 ids.filter((id) => newestAgentRun(app.db, id, ["queued", "running"]) !== undefined),
199 );
197200 const muted = viewer === undefined ? new Set<string>() : mutedRepos(app.db, viewer.id);
198201 const pull = (id: string) => {
199202 const p = pulls.get(id);
@@ -225,6 +228,7 @@ function loadTargets(
225228 under: under.get(id) ?? [],
226229 seating: seatingOf(repo),
227230 peers,
231 ...(retrying.has(id) ? { retrying: true } : {}),
228232 ...(viewer === undefined
229233 ? {}
230234 : {
@@ -601,7 +605,7 @@ export async function applyPreviewed(
601605 /** How long a bulk action on asks can be undone: a day. */
602606 export const UNDO_WINDOW_MS = 86_400_000;
603607
604 export const ASK_VERBS: readonly string[] = ["dismiss", "mute", "ship", "close", "replan"];
608 export const ASK_VERBS: readonly string[] = ["dismiss", "mute", "ship", "close", "replan", "retry"];
605609
606610 /** The query a bulk action on asks is receipted under: "asks: n selected". */
607611 export const ASKS_QUERY_PREFIX = "asks: ";
@@ -609,7 +613,10 @@ export const ASKS_QUERY_PREFIX = "asks: ";
609613 /** Whether a receipt is a bulk action on asks: named one by one, "asks: n selected". */
610614 export function isAsksOperation(op: Operation): boolean {
611615 return (
612 op.kind === "issue" && op.query.startsWith(ASKS_QUERY_PREFIX) && ASK_VERBS.includes(op.verb)
616 op.query.startsWith(ASKS_QUERY_PREFIX) &&
617 ((op.kind === "issue" && ASK_VERBS.includes(op.verb)) ||
618 // Waking a stopped app (#12277) is its restore, taken from the needs stack.
619 (op.kind === "repo" && op.verb === "archive"))
613620 );
614621 }
615622
src/actions/needs.ts +107 −13
@@ -7,7 +7,12 @@
77 * so the preview, the per-row access check, the receipt and the undo are theirs.
88 */
99 import type { App } from "../app.ts";
10 import { applyAsksBulk, receiptOf } from "./asks_bulk.ts";
10 import { applyAsksBulk, applyWakeBulk, receiptOf } from "./asks_bulk.ts";
11 import { asleepLine } from "./needs_asleep.ts";
12 import { isLandedPull } from "../crew/stale_asks.ts";
13 import { getPull } from "../core/pulls.ts";
14 import { newestAgentRun } from "../core/runs.ts";
15 import { STALE_DAYS } from "../web/studio/review_set.ts";
1116 import { askStackFor, type askLinesFor } from "../web/studio/asks.ts";
1217 import { weekOld } from "../flow/oldest_approved.ts";
1318 import { drillNow } from "./backups_now.ts";
@@ -36,14 +41,19 @@ export interface Recommended {
3641 /** For an item not safe: the question to put to the owner. */
3742 readonly ask?: string;
3843 /**
39 * What carries it out, for a safe one: a close (it has a receipt), a drill, or a hand back to
40 * the crew.
44 * What carries it out, for a safe one: a close, retry, dismiss or wake (each has a receipt and
45 * an undo, `asks_bulk.ts`), a drill, or a hand back to the crew.
4146 */
42 readonly action?: "close" | "drill" | "give_back";
47 readonly action?: SafeAction | "drill" | "give_back";
48 /** For a close: the reason said on it. */
49 readonly note?: string;
4350 /** For a need with no safe default: the real options the owner picks between. */
4451 readonly options?: readonly string[];
4552 }
4653
54 /** The four fixes safe to take on a recommendation: each is reversible, none merges. */
55 export type SafeAction = "close" | "retry" | "dismiss" | "wake";
56
4757 export interface Need {
4858 readonly id: string;
4959 readonly sentence: string;
@@ -71,14 +81,43 @@ const needsDecision = (question: string, reason: string, options: readonly strin
7181 options,
7282 });
7383
74 /** What to do about one row, from its state: its kind, what it waits for, the crew's advice. */
75 export function recommend(row: Row): Recommended {
84 /** What the stack knows of a row beyond the row itself: git's and the runs' answers,
85 * and the clock. */
86 export interface Facts {
87 readonly now: number;
88 /** The row's one pull is already on its base. */
89 readonly landed: (row: Row) => boolean;
90 /** The row's one issue has a failed or cancelled agent run to try again. */
91 readonly retryable: (row: Row) => boolean;
92 }
93
94 const NOTHING: Facts = { now: Date.now(), landed: () => false, retryable: () => false };
95
96 /** Kinds the asks' dismiss refuses: decided where they live (`askTargetsFor`). */
97 const NOT_DISMISSED_HERE: readonly string[] = ["paused", "proposal", "declined"];
98
99 /**
100 * What to do about one row, from its state: its kind, what it waits for, the crew's advice.
101 * Four fixes are safe (reversible, with a receipt): close a pull already on the base, close
102 * what the crew advised closing, dismiss a notice older than the stale window, retry a
103 * parked run. A merge is never one: its only undo is a revert pull.
104 */
105 export function recommend(row: Row, facts: Facts = NOTHING): Recommended {
76106 const about = row.line;
77107 const options = row.words.options;
78108 if (row.items.length !== 1)
79109 return needsDecision(`Which of these should be taken first: ${about}?`, "several changes share this row; each is its own call", options);
80110 const advice = row.recommendation;
81111 const conflicts = row.waitingFor.word === "conflicts with main";
112 if (row.numberOf === "pull" && facts.landed(row))
113 return {
114 choice: "Close it",
115 reason: "its change is already on the base, so closing it loses nothing",
116 undo: "receipt",
117 safe: true,
118 action: "close",
119 note: "Closed by the recommended choice: its change is already on the base.",
120 };
82121 if (row.numberOf === "pull" && !conflicts) {
83122 // A merge has no undo but a revert pull, so no change is shipped on a recommendation:
outdated

Dismiss shadows the retry below it: an old parked run is never retried. Move the retry branch above this one.

84123 // the owner's word is the approval.
@@ -97,8 +136,26 @@ export function recommend(row: Row): Recommended {
97136 undo: "receipt",
98137 safe: true,
99138 action: "close",
139 note: "Closed by the recommended choice: the crew advised it.",
100140 };
101141 }
142 if (row.kind === "parked" && facts.retryable(row))
143 return {
144 choice: "Retry it",
145 reason: "its newest run failed; trying it again is one run, and Undo cancels it",
146 undo: "receipt",
147 safe: true,
148 action: "retry",
149 };
150 const days = Math.floor((facts.now - Date.parse(row.since)) / 86_400_000);
151 if (days >= STALE_DAYS && !NOT_DISMISSED_HERE.includes(row.kind))
152 return {
153 choice: "Dismiss it",
154 reason: `it has waited ${days} days, past the ${STALE_DAYS}-day stale window; it asks again if anything new happens`,
155 undo: "receipt",
156 safe: true,
157 action: "dismiss",
158 };
102159 if (row.kind === "stopped" && !conflicts && row.numberOf === "pull")
103160 return {
104161 choice: "Start the crew on it again",
@@ -168,7 +225,17 @@ function approvedNeeds(ctx: Home): Need[] {
168225
169226 /** The stack: the forge's own needs first (an admin's), then the asks, most consequential first. */
170227 export function needsStack(ctx: Home, user: User, chips?: Chips): Need[] {
228 const db = ctx.app.db;
171229 const stack = askStackFor(ctx, user, chips);
230 const idOf = (row: Row): string => row.items[0]!.slice(row.items[0]!.indexOf(":") + 1);
231 const facts: Facts = {
232 now: Date.now(),
233 landed: (row) => {
234 const pull = row.number === undefined ? undefined : getPull(db, row.repoId, row.number);
235 return pull !== undefined && pull.state === "open" && isLandedPull(db, pull.id, pull.headOid);
236 },
237 retryable: (row) => newestAgentRun(db, idOf(row), ["failed", "cancelled"]) !== undefined,
238 };
172239 const forge = stack.forge.map(
173240 (d, i): Need => ({
174241 id: `forge:${d.cause || i}`,
@@ -188,12 +255,30 @@ export function needsStack(ctx: Home, user: User, chips?: Chips): Need[] {
188255 why: row.consequence.why,
189256 waits: row.words.ifNothing,
190257 choices: row.words.options,
191 recommended: recommend(row),
258 recommended: recommend(row, facts),
192259 link: row.link,
193260 items: row.items,
194261 }),
195262 );
196 return [...forge, ...(user.isAdmin ? approvedNeeds(ctx) : []), ...rows];
263 const asleep = stack.asleep.map(
264 (a): Need => ({
265 id: `wake:${a.repo.id}`,
266 sentence: asleepLine(a),
267 why: "someone filed an issue on an app that is put away",
268 waits: "nothing starts there until it is woken",
269 choices: ["Wake it", "Leave it stopped"],
270 recommended: {
271 choice: "Wake it",
272 reason: "waking restores it as it was; Undo puts it away again",
273 undo: "receipt",
274 safe: true,
275 action: "wake",
276 },
277 link: `/${a.repo.ownerName}/${a.repo.name}`,
278 items: [a.repo.id],
279 }),
280 );
281 return [...forge, ...(user.isAdmin ? approvedNeeds(ctx) : []), ...rows, ...asleep];
197282 }
198283
199284 /** One or two sentences: serving or not, the crew, what is unusual. */
@@ -265,6 +350,15 @@ export async function applyRecommended(ctx: Home, user: User, dryRun: boolean, o
265350 refused: [],
266351 };
267352 if (dryRun) return out;
353 const groups = new Map<string, { action: SafeAction; note: string; items: string[] }>();
354 for (const n of safe) {
355 const action = n.recommended.action!;
356 if (action === "drill" || action === "give_back") continue;
357 const note = action === "close" ? (n.recommended.note ?? "Closed by the recommended choice.") : "";
358 const g = groups.get(`${action}|${note}`) ?? { action, note, items: [] };
359 g.items.push(...n.items);
360 groups.set(`${action}|${note}`, g);
361 }
268362 for (const n of safe.filter((n) => n.recommended.action === "drill")) {
269363 const drilled = await drillNow(ctx.app, user);
270364 out.done.push({ id: n.id, choice: n.recommended.choice, result: drilled.ok ? drilled.value.says : drilled.error.says });
@@ -276,11 +370,9 @@ export async function applyRecommended(ctx: Home, user: User, dryRun: boolean, o
276370 else out.refused.push({ item, reason: back.reason });
277371 }
278372 }
279 for (const action of ["close"] as const) {
280 const items = safe.filter((n) => n.recommended.action === action).flatMap((n) => [...n.items]);
281 if (items.length === 0) continue;
282 const reason = "Closed by the recommended choice: the crew advised it.";
283 const done = await applyAsksBulk(ctx.app, user, action, items, reason);
373 for (const { action, note, items } of groups.values()) {
374 const done =
375 action === "wake" ? await applyWakeBulk(ctx.app, user, items) : await applyAsksBulk(ctx.app, user, action, items, action === "close" ? note : undefined);
284376 if (!done.ok) {
285377 out.refused.push(...items.map((item) => ({ item, reason: done.error.message })));
286378 continue;
@@ -290,6 +382,8 @@ export async function applyRecommended(ctx: Home, user: User, dryRun: boolean, o
290382 for (const item of n.items)
291383 if (!skipped.has(item)) out.done.push({ id: n.id, choice: n.recommended.choice, result: "closed, with a receipt" });
292384 out.refused.push(...done.value.skipped);
385 for (const row of done.value.rows)
386 if (row.outcome !== "ok" && row.outcome !== "unchanged") out.refused.push({ item: row.targetId, reason: row.reason ?? row.outcome });
293387 out.receipts.push({
294388 operation: done.value.id,
295389 receipt: receiptOf(done.value),
src/actions/needs_asleep.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * Stopped apps that someone asked for (#12277). An archived repository is a
3 * stopped app: nothing of it runs. If a person has filed an issue on it since
4 * it was stopped, someone wants it back, and waking it (restoring it) is the
5 * reversible fix the needs stack recommends. Only for those who administer it.
6 */
7 import type { Database } from "bun:sqlite";
8 import { canAdmin, listReposWritableTo, type Repo } from "../core/repos.ts";
9 import type { User } from "../core/users.ts";
10
11 /** The most stopped apps one stack reads. */
12 export const ASLEEP_MAX = 50;
13
14 export interface Asleep {
15 readonly repo: Repo;
16 /** The open issues people filed since it was stopped. */
17 readonly asked: number;
18 readonly since: string;
19 }
20
21 /** Walks `issue_repo_kind_number` (repo_id, kind): one seek per stopped app. */
22 export const ASKED_SINCE = `SELECT COUNT(*) AS n, MIN(i.created_at) AS since
23 FROM issue i JOIN user u ON u.id = i.author_id
24 WHERE i.repo_id = ?1 AND i.kind = 'issue' AND i.state = 'open'
25 AND i.created_at > ?2 AND u.is_agent = 0`;
26
27 /** One stopped app's need, in a sentence: what the asks page and the stack both say. */
28 export const asleepLine = (a: Asleep): string =>
29 `${a.repo.ownerName}/${a.repo.name} is stopped and ${a.asked} ${a.asked === 1 ? "person has" : "people have"} asked for it`;
30
31 /** The user's stopped apps that a person asked for, newest ask first. */
32 export function askedAsleep(db: Database, user: User): Asleep[] {
33 const out: Asleep[] = [];
34 for (const repo of listReposWritableTo(db, user, { limit: 200, onlyArchived: true })) {
35 if (repo.archivedAt === null) continue;
36 const row = db.query<{ n: number; since: string | null }, [string, string]>(ASKED_SINCE).get(repo.id, repo.archivedAt);
37 // Ask the cheap question first: admin rights only for an app someone asked for.
38 if (row !== null && row.n > 0 && row.since !== null && canAdmin(db, repo, user)) out.push({ repo, asked: row.n, since: row.since });
39 if (out.length >= ASLEEP_MAX) break;
40 }
41 return out.sort((a, b) => (a.since < b.since ? 1 : -1));
42 }
src/core/repos.ts +6
@@ -856,6 +856,11 @@ export interface ListReposOptions {
856856 appsFirst?: boolean;
857857 /** Leave archived repositories out. @default false */
858858 withoutArchived?: boolean;
859 /**
860 * Only the archived (stopped) ones: the filter is in the query,
861 * so a viewer with none costs one statement.
862 */
863 onlyArchived?: boolean;
859864 /** Only archived repositories. @default false */
860865 archivedOnly?: boolean;
861866 /** Only this owner's repositories (a username, any case). */
@@ -1016,6 +1021,7 @@ export function listReposWritableTo(
10161021 where += ` AND repo.id < ?${params.length}`;
10171022 }
10181023 if (options.withoutArchived === true) where += " AND repo.archived_at IS NULL";
1024 if (options.onlyArchived === true) where += " AND repo.archived_at IS NOT NULL";
10191025 params.push(pageLimit(options.limit));
10201026 const rows = db
10211027 .query<RepoRow, (string | number)[]>(
src/core/runs.ts +14
@@ -1132,6 +1132,20 @@ export function checkSummary(
11321132 : { state: "none", run: null };
11331133 }
11341134
1135 /**
1136 * An issue's newest agent run in one of these states (#12277): one seek on
1137 * `run_issue` (issue_id, id DESC). `ids` are time-ordered, so the newest id is the latest.
1138 */
1139 export function newestAgentRun(db: Database, issueId: string, states: readonly RunState[]): Run | undefined {
1140 const row = db
1141 .query<RunRow, string[]>(
1142 `SELECT * FROM run INDEXED BY run_issue WHERE issue_id = ?1 AND kind = 'agent'
1143 AND state IN (${states.map((_, n) => `?${n + 2}`).join(",")}) ORDER BY id DESC LIMIT 1`,
1144 )
1145 .get(issueId, ...states);
1146 return row ? toRun(row) : undefined;
1147 }
1148
11351149 /**
11361150 * The latest run per issue for a set of issues — one query, for a list that
11371151 * shows a check mark beside every pull without asking per row.
src/crew/stale_asks.ts +32 −3
@@ -20,6 +20,7 @@ import { getRepoById } from "../core/repos.ts";
2020 import { latestRunsForIssues } from "../core/runs.ts";
2121 import { checkStale } from "../checks/stale.ts";
2222 import { resolveOid } from "../git/merge.ts";
23 import { isAncestor } from "../git/local.ts";
2324 import { repoDir } from "../git/repos.ts";
2425
2526 interface Known {
@@ -28,6 +29,8 @@ interface Known {
2829 /** The pull's head the answer was taken at, as the database names it. */
2930 readonly head: string;
3031 readonly stale: boolean;
32 /** The base already holds the head: everything the pull adds is there (#12277). */
33 readonly landed?: boolean;
3134 /** The base's tip when it was last read; empty when it could not be. */
3235 readonly base: string;
3336 /** The files that stop it merging; 0 when it merges or is simply already in. */
@@ -54,6 +57,13 @@ export function isStalePull(
5457 return known !== undefined && known.stale && known.head === headOid;
5558 }
5659
60 /** Whether this pull, at this head, was last found already on its base:
61 * closing it loses nothing. */
62 export function isLandedPull(db: Database, pullId: string, headOid: string): boolean {
63 const known = knownByDb.get(db)?.get(pullId);
64 return known !== undefined && known.landed === true && known.head === headOid;
65 }
66
5767 /**
5868 * Whether this pull's green was checked against an older tip of its base, as
5969 * the last sweep read that tip (#1179's `checkStale`). A tip not yet read is
@@ -102,6 +112,13 @@ export function mergesAgainSince(
102112 /** The most pulls one sweep looks at: enough for a busy forge, bounded for a strange one. */
103113 export const SWEEP_LIMIT = 300;
104114
115 /**
116 * The most `merge-base --is-ancestor` spawns one sweep makes for pulls that are not
117 * green (a green pull's answer comes from `pullStatus`). A pull whose head and base
118 * are unchanged is skipped before this (`between`); the rest wait for the next sweep.
119 */
120 export const ANCESTOR_PER_SWEEP = 40;
121
105122 /**
106123 * Look again at every open pull with a green check in a repository that
107124 * asks a person (anything not `autonomous`: those settle their own). Never
@@ -119,10 +136,11 @@ export async function sweepStaleAsks(app: App): Promise<void> {
119136 .all(SWEEP_LIMIT)
120137 .map((r) => r.id);
121138 const checks = latestRunsForIssues(db, ids);
122 const green = ids.filter((id) => checks.get(id)?.state === "ok");
123 const pulls = joinMany(db, [...getIssuesByIds(db, green).values()]);
139 const green = new Set(ids.filter((id) => checks.get(id)?.state === "ok"));
140 const pulls = joinMany(db, [...getIssuesByIds(db, ids).values()]);
124141 const open = new Set(pulls.map((p) => p.id));
125142 for (const id of known.keys()) if (!open.has(id)) known.delete(id);
143 let spawns = 0;
126144 for (const pull of pulls) {
127145 const repo = getRepoById(db, pull.repoId);
128146 if (!repo) continue;
@@ -134,8 +152,18 @@ export async function sweepStaleAsks(app: App): Promise<void> {
134152 if (known.get(pull.id)?.between === between) continue;
outdated

An ancestor check now runs for every open pull on each sweep; bound it or cache by head and base.

135153 // An autonomous repository settles its own mergeability; only the
136154 // base tip is read there, for the stale green.
155 // Only a green pull is asked whether it merges; any open pull is asked
156 // (one `merge-base --is-ancestor`) whether the base already holds it.
157 const needsGit = !(repo.autonomy !== "autonomous" && green.has(pull.id)) && base !== "" && !pull.crossRepo;
158 // Over budget: leave this pull unrecorded, so the next sweep takes it first.
159 if (needsGit && spawns >= ANCESTOR_PER_SWEEP) continue;
160 if (needsGit) spawns++;
137161 const status =
138 repo.autonomy === "autonomous" ? undefined : await pullStatus(dir, pull);
162 repo.autonomy === "autonomous" || !green.has(pull.id) ? undefined : await pullStatus(dir, pull);
163 const landed =
164 status !== undefined
165 ? status.ahead === 0
166 : base !== "" && !pull.crossRepo && (await isAncestor(dir, pull.headOid, base));
139167 const stale =
140168 status !== undefined &&
141169 (status.ahead === 0 ||
@@ -151,6 +179,7 @@ export async function sweepStaleAsks(app: App): Promise<void> {
151179 between,
152180 head: pull.headOid,
153181 stale,
182 landed,
154183 base,
155184 conflicts:
156185 status === undefined || status.mergeable ? 0 : status.conflicts.length,
src/fleet/verbs.ts +24
@@ -29,6 +29,7 @@ import { moveLimb, parseSeat, type Seating } from "../core/limb_seats.ts";
2929 import { getHold } from "../core/holds.ts";
3030 import { recordInteraction, removeDismissals, removeMutes } from "../core/interactions.ts";
3131 import { getPull } from "../core/pulls.ts";
32 import { newestAgentRun } from "../core/runs.ts";
3233 import { teamHoldRefusal } from "../core/teams_words.ts";
3334 import { askItemsOf } from "../web/studio/asks.ts";
3435 import type { FleetValue } from "../core/fleet_ops.ts";
@@ -64,6 +65,8 @@ export interface Target {
6465 readonly viewerId?: string;
6566 /** For an issue: whether the viewer's dismissal of its ask still holds. */
6667 readonly askDismissed?: boolean;
68 /** For an issue: an agent run on it is waiting or going. */
69 readonly retrying?: boolean;
6770 /** Whether the viewer muted this repository. */
6871 readonly muted?: boolean;
6972 /** For a pull: merged, its latest check green, and whether it merges as it stands. */
@@ -472,6 +475,27 @@ export const VERBS: Record<string, Verb> = {
472475 },
473476 },
474477
478 // Retry: a parked issue's newest failed run is queued again, in the actor's
479 // name (a person's word starts the crew on it again). Undo cancels that run.
480 retry: {
481 kind: "issue",
482 reversible: true,
483 parse: noValue,
484 read: (t) => (t.retrying === true ? "retrying" : "parked"),
485 next: () => "retrying",
486 refuse: (_app, t) => (t.issue?.state === "open" ? undefined : "it is closed"),
487 async write(app, actor, t, after) {
488 if (!t.issue) return words("not_found");
489 if (after === "retrying") {
490 const run = newestAgentRun(app.db, t.id, ["failed", "cancelled"]);
491 if (run === undefined) return "no failed run to try again";
492 return done(requeueRepoRun(app, actor, t.repo, run.id));
493 }
494 const queued = newestAgentRun(app.db, t.id, ["queued", "running"]);
495 return queued === undefined ? undefined : done(cancelRepoRun(app, actor, t.repo, queued.id));
496 },
497 },
498
475499 // Hand back to the planner: the issue is assigned to the repository's
476500 // planner, which re-plans it. Never on a public repository, where a crew
477501 // assignment would let any reader's comment steer the run (#619).
src/web/studio/asks.ts +8 −6
@@ -7,6 +7,7 @@
77 * forms and buttons are `decisions.ts`.
88 */
99
10 import { askedAsleep, asleepLine } from "../../actions/needs_asleep.ts";
1011 import type { Database } from "bun:sqlite";
1112 import { crewHandsFor } from "../../actions/give_back.ts";
1213 import { forgeNeedList, type ForgeNeed } from "../../actions/health.ts";
@@ -58,7 +59,7 @@ import {
5859 } from "../../crew/autonomy.ts";
5960 import { breakerParked, WAITING_NOTES } from "../../crew/breaker.ts";
6061 import { handoversOf, passReasonOf, type Handover } from "../../crew/guard.ts";
61 import { conflictsOf, isStalePull, mergesAgainSince, staleGreen } from "../../crew/stale_asks.ts";
62 import { conflictsOf, isLandedPull, isStalePull, mergesAgainSince, staleGreen } from "../../crew/stale_asks.ts";
6263 import { reviewSays } from "../../crew/review_says.ts";
6364 import { reviewerPaused } from "../../crew/reviewer_paused.ts";
6465 import { reviewWaitsFor, type ReviewWait } from "../../crew/review.ts";
@@ -376,7 +377,7 @@ function askCandidatesFor(
376377 settled.flatMap((p) => {
377378 const pull = joined.get(p.id)!;
378379 const check = checks.get(p.id);
379 return check?.state === "ok" && !isStalePull(db, pull.id, pull.headOid) && !staleGreen(db, pull, check)
380 return check?.state === "ok" && (!isStalePull(db, pull.id, pull.headOid) || isLandedPull(db, pull.id, pull.headOid)) && !staleGreen(db, pull, check)
380381 ? [{ repo: byId.get(p.repoId)!, pull }]
381382 : [];
382383 }),
@@ -451,7 +452,7 @@ function askCandidatesFor(
451452 repo.autonomy !== "autonomous" &&
452453 // A green pull that no longer merges as it stands cannot be shipped:
453454 // bringing it up to date is work, not a person's decision.
454 !isStalePull(db, pull.id, pull.headOid) &&
455 (!isStalePull(db, pull.id, pull.headOid) || isLandedPull(db, pull.id, pull.headOid)) &&
455456 // A green checked against an older base is a check still to come.
456457 !staleGreen(db, pull, check)
457458 ) {
@@ -477,7 +478,7 @@ function askCandidatesFor(
477478 } else if (
478479 check?.state === "ok" &&
479480 repo.autonomy === "autonomous" &&
480 !isStalePull(db, pull.id, pull.headOid) &&
481 (!isStalePull(db, pull.id, pull.headOid) || isLandedPull(db, pull.id, pull.headOid)) &&
481482 !staleGreen(db, pull, check)
482483 ) {
483484 // An autonomous repository lands its own green pulls once reviewed;
@@ -1200,14 +1201,14 @@ export function askStackFor(
12001201 chips?: Chips,
12011202 onHidden?: (rows: number) => void,
12021203 ) {
1203 return { forge: forgeNeedsFor(ctx, user), rows: askLinesFor(ctx.app.db, user, chips, onHidden) };
1204 return { forge: forgeNeedsFor(ctx, user), rows: askLinesFor(ctx.app.db, user, chips, onHidden), asleep: askedAsleep(ctx.app.db, user) };
12041205 }
12051206
12061207 /** How many things ask the viewer: the stack's length, the number the header and asks page show. */
12071208 export function askCountFor(ctx: Pick<Ctx, "app">, user: User | undefined): number {
12081209 if (!user) return 0;
12091210 const stack = askStackFor(ctx, user);
1210 return stack.forge.length + stack.rows.length;
1211 return stack.forge.length + stack.rows.length + stack.asleep.length;
12111212 }
12121213
12131214 /** The single sentence the asks page leads with, and the dashboard links with. */
@@ -1234,6 +1235,7 @@ export function asksAnswer(ctx: Ctx, user: User, chips?: Chips) {
12341235 waiting: { count: set.count, stale: set.stale.length },
12351236 rows,
12361237 forge: stack.forge.map((n) => n.line),
1238 asleep: stack.asleep.map((a) => ({ repo: `${a.repo.ownerName}/${a.repo.name}`, sentence: asleepLine(a) })),
12371239 measure: { days: ASKS_WINDOW_DAYS, ...askMeasureWeek(ctx.app.db, user.id) },
12381240 ...(hasAskFilters(askFiltersOf(ctx.app.db, user.id)) ? { filters: { hidden, line: hiddenLine(hidden) } } : {}),
12391241 };
src/web/studio/asks_page.ts +15 −2
@@ -7,6 +7,7 @@
77 * (`actions/asks_bulk.ts`). `/asks` was its own screen; it lands here now.
88 */
99
10 import { askedAsleep, asleepLine, type Asleep } from "../../actions/needs_asleep.ts";
1011 import { UNDO_LABEL, VERB_WORDS } from "../../actions/asks_words.ts";
1112 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1213 import type { WaitingFor } from "../../core/waiting_for.ts";
@@ -413,6 +414,17 @@ export const forgeCard = (d: ForgeNeed): Html =>
413414 <div class="bar">${btn("Health", { href: "/api/v1/health", size: "sm" })}</div>
414415 </section>`;
415416
417 /**
418 * A stopped app someone asked for: said where the person looks; the wake itself is the
419 * repository's (and the stack's recommended choice, with a receipt and an undo).
420 */
421 export const asleepCard = (a: Asleep): Html =>
422 html`<section class="stack">
423 <h2>A stopped app</h2>
424 <p><span class="dot" data-tone="warn" aria-hidden="true"></span> <a href="/${a.repo.ownerName}/${a.repo.name}">${asleepLine(a)}</a></p>
425 <div class="bar">${btn("Open it", { href: `/${a.repo.ownerName}/${a.repo.name}`, size: "sm" })}</div>
426 </section>`;
427
416428 /** What sits above the asks after a bulk step: a preview to confirm, a receipt, or why nothing was done. */
417429 export interface AsksTop {
418430 readonly banner: Html;
@@ -545,7 +557,8 @@ export function needsYouSection(
545557 )}
546558 </details>`;
547559 const undo = undoSlot(ctx, user);
548 const count = rows.length + needs.length;
560 const asleep = askedAsleep(ctx.app.db, user);
561 const count = rows.length + needs.length + asleep.length;
549562 if (count === 0 && top === undefined)
550563 return {
551564 body: html`<h2 id="asks-sentence" class="sr-only">${askSentence(0)}</h2>${filtered}${silencedNote}${asideNote}${undo}`,
@@ -574,7 +587,7 @@ export function needsYouSection(
574587 const body = html`<section id="needs-you" class="stack">
575588 <h2 id="asks-sentence">${askSentence(count)}</h2>
576589 ${top?.banner ?? null}
577 ${needs.map(forgeCard)} ${first.map((r) => mutableRow(ctx, r, picked))}
590 ${needs.map(forgeCard)} ${asleep.map(asleepCard)} ${first.map((r) => mutableRow(ctx, r, picked))}
578591 ${middle.length === 0
579592 ? null
580593 : more(
test/needs-fixes.test.ts added +252
@@ -0,0 +1,252 @@
1 /**
2 * The four reversible fixes the needs stack recommends (#12277): retry a
3 * parked run, dismiss a notice past the stale window, wake a stopped app
4 * someone asked for, close a pull already on the base. Each is offered when
5 * its condition holds, not when it does not, and its undo restores what was
6 * there. A merge is never one.
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { addToCrew, createAgent } from "../src/actions/crew.ts";
14 import { addComment, openIssue } from "../src/actions/issues.ts";
15 import { openPull } from "../src/actions/pulls.ts";
16 import { commitToBranch, createRepo, setArchived } from "../src/actions/repos.ts";
17 import { applyRecommended, needsStack, recommend, type Need } from "../src/actions/needs.ts";
18 import { undoAsksBulk } from "../src/actions/asks_bulk.ts";
19 import { ASKED_SINCE } from "../src/actions/needs_asleep.ts";
20 import { sweepStaleAsks } from "../src/crew/stale_asks.ts";
21 import { addComment as commentAs, getIssueById } from "../src/core/issues.ts";
22 import { getPull } from "../src/core/pulls.ts";
23 import { getRepoById, type Repo } from "../src/core/repos.ts";
24 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
25 import { createUser, getUserByName, type User } from "../src/core/users.ts";
26 import { BREAKER_NOTE } from "../src/crew/breaker.ts";
27 import { repoDir } from "../src/git/repos.ts";
28 import type { Ctx } from "../src/http/context.ts";
29 import { id as newId } from "../src/kernel/id.ts";
30 import { askCountFor, askLinesFor } from "../src/web/studio/asks.ts";
31 import { gitClientEnv } from "./helpers/git-client.ts";
32 import { quietLogs } from "./helpers/globals.ts";
33
34 quietLogs();
35
36 let dataDir = "";
37 let app: App;
38 let alice: User;
39 let repo: Repo;
40 let botId = "";
41
42 const ctx = (): Ctx => ({
43 app,
44 request: new Request("http://x/"),
45 url: new URL("http://x/"),
46 params: {},
47 auth: { user: alice, scope: "rw", via: "session" },
48 theme: undefined,
49 });
50 const stack = (): Need[] => needsStack(ctx(), alice);
51 const found = (needle: (n: Need) => boolean): Need | undefined => stack().find(needle);
52 const day = 86_400_000;
53
54 /** A bot's open pull, last touched `days` ago, with an optional crew word on it. */
55 const botPull = (title: string, days: number, advice?: string): { id: string; number: number } => {
56 const issueId = newId();
57 const number = app.db.query<{ issue_seq: number }, [string]>("UPDATE repo SET issue_seq = issue_seq + 1 WHERE id = ?1 RETURNING issue_seq").get(repo.id)!.issue_seq;
58 const ago = new Date(Date.now() - days * day).toISOString();
59 app.db
60 .query(`INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at, updated_at) VALUES (?1, ?2, ?3, 'pull', ?4, '', ?5, 'open', ?6, ?6)`)
61 .run(issueId, repo.id, number, title, botId, ago);
62 app.db
63 .query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id) VALUES (?1, 'main', ?2, ?3, ?3, ?4)`)
64 .run(issueId, `x/${number}`, "0".repeat(40), repo.id);
65 if (advice !== undefined) commentAs(app.db, { issueId, authorId: botId, body: advice });
66 return { id: issueId, number };
67 };
68 const pullNeed = (number: number) => found((n) => n.link.endsWith(`/pulls/${number}`));
69 const issueNeed = (p: { id: string }) => found((n) => n.id === `parked:${p.id}`);
70
71 const parkedIssue = async (name: string, withFailedRun: boolean): Promise<{ id: string; number: number; repo: Repo }> => {
72 // One parked issue to a repository: two in one are a single row, which the owner must untangle.
73 const made = await createRepo(app, alice, { name, visibility: "public" });
74 if (!made.ok) throw new Error(String(made.error));
75 const home = made.value;
76 addToCrew(app, alice, home, "bot");
77 const opened = openIssue(app, alice, home, { title: `Parked in ${name}` });
78 if (!opened.ok) throw new Error(String(opened.error));
79 const issue = opened.value;
80 if (withFailedRun) {
81 const run = createRun(app.db, { repoId: home.id, kind: "agent", issueId: issue.id, actorId: botId, reason: "assigned" });
82 claimRun(app.db, run.id);
83 finishRun(app.db, run.id, { state: "failed", summary: "tests stayed red" });
84 }
85 addComment(app, alice, home, issue, BREAKER_NOTE);
86 return { id: issue.id, number: issue.number, repo: home };
87 };
88 const agentRuns = (issueId: string) =>
89 app.db.query<{ id: string; state: string }, [string]>("SELECT id, state FROM run WHERE issue_id = ?1 AND kind = 'agent' ORDER BY id").all(issueId);
90
91 beforeAll(async () => {
92 dataDir = await mkdtemp(join(tmpdir(), "forge-needs-fixes-"));
93 app = createApp({ dataDir, port: 0 });
94 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-fixes-passphrase", adminIfFirst: true });
95 if (!a.ok) throw new Error(a.error);
96 alice = a.value;
97 await createAgent(app, alice, { username: "bot" });
98 botId = getUserByName(app.db, "bot")!.id;
99 const made = await createRepo(app, alice, { name: "open", visibility: "public" });
100 if (!made.ok) throw new Error(String(made.error));
101 repo = made.value;
102 await commitToBranch(app, alice, repo, { message: "seed", files: [{ path: "README.md", content: "# open\n" }] });
103 addToCrew(app, alice, repo, "bot");
104 }, 30_000);
105
106 afterAll(async () => {
107 await rm(dataDir, { recursive: true, force: true });
108 });
109
110 test("a parked run is retried when it has a failed run to try; not when it has none; undo cancels the new run", async () => {
111 const none = await parkedIssue("norun", false);
112 const parked = await parkedIssue("failed", true);
113 expect(issueNeed(none)!.recommended.safe).toBe(false);
114 const need = issueNeed(parked)!;
115 expect(need.recommended).toMatchObject({ choice: "Retry it", safe: true, action: "retry", undo: "receipt" });
116
117 const dry = await applyRecommended({ app }, alice, true, need.id);
118 expect(dry.plan.map((p) => p.id)).toEqual([need.id]);
119 expect(agentRuns(parked.id).map((r) => r.state)).toEqual(["failed"]);
120
121 const done = await applyRecommended({ app }, alice, false, need.id);
122 expect(done.refused).toEqual([]);
123 expect(done.receipts).toHaveLength(1);
124 expect(done.receipts[0]!.receipt).toContain("Retry");
125 expect(agentRuns(parked.id).map((r) => r.state)).toEqual(["failed", "queued"]);
126
127 const undone = await undoAsksBulk(app, alice, done.receipts[0]!.operation);
128 expect(undone.ok).toBe(true);
129 expect(agentRuns(parked.id).map((r) => r.state)).toEqual(["failed", "cancelled"]);
130 expect(getIssueById(app.db, parked.id)!.state).toBe("open");
131 });
132
133 test("a notice older than the stale window is dismissed; a fresh one is not; undo brings it back", async () => {
134 const old = botPull("Old notice", 40);
135 const fresh = botPull("Fresh notice", 2);
136 const need = pullNeed(old.number)!;
137 expect(need.recommended).toMatchObject({ choice: "Dismiss it", safe: true, action: "dismiss", undo: "receipt" });
138 expect(pullNeed(fresh.number)!.recommended.safe).toBe(false);
139
140 const done = await applyRecommended({ app }, alice, false, need.id);
141 expect(done.refused).toEqual([]);
142 expect(pullNeed(old.number)).toBeUndefined();
143 expect(pullNeed(fresh.number)).toBeDefined();
144 expect(getPull(app.db, repo.id, old.number)!.state).toBe("open");
145
146 expect((await undoAsksBulk(app, alice, done.receipts[0]!.operation)).ok).toBe(true);
147 expect(pullNeed(old.number)).toBeDefined();
148 expect(getPull(app.db, repo.id, old.number)!.state).toBe("open");
149 });
150
151 test("a stopped app someone asked for is woken; one nobody asked for, or still running, is not; undo puts it away", async () => {
152 const quiet = await createRepo(app, alice, { name: "quiet", visibility: "public" });
153 const asked = await createRepo(app, alice, { name: "wanted", visibility: "public" });
154 if (!quiet.ok || !asked.ok) throw new Error("repos");
155 expect((await setArchived(app, alice, quiet.value, true, false)).ok).toBe(true);
156 expect((await setArchived(app, alice, asked.value, true, false)).ok).toBe(true);
157 await new Promise((r) => setTimeout(r, 5)); // real-timer: archive time must precede the issue by a tick
158 const filed = openIssue(app, alice, getRepoById(app.db, asked.value.id)!, { title: "Please bring this back" });
159 expect(filed.ok).toBe(true);
160
161 expect(found((n) => n.id === `wake:${quiet.value.id}`)).toBeUndefined();
162 expect(found((n) => n.id === `wake:${repo.id}`)).toBeUndefined();
163 const need = found((n) => n.id === `wake:${asked.value.id}`)!;
164 expect(need.recommended).toMatchObject({ choice: "Wake it", safe: true, action: "wake", undo: "receipt" });
165 // The wake is one of the asks: the home's count and /asks hold it,
166 // as the terminal and MCP list do.
167 expect(askCountFor({ app }, alice)).toBe(stack().length);
168
169 const done = await applyRecommended({ app }, alice, false, need.id);
170 expect(done.refused).toEqual([]);
171 expect(getRepoById(app.db, asked.value.id)!.archivedAt).toBeNull();
172 expect(getRepoById(app.db, quiet.value.id)!.archivedAt).not.toBeNull();
173 expect(found((n) => n.id === need.id)).toBeUndefined();
174
175 expect((await undoAsksBulk(app, alice, done.receipts[0]!.operation)).ok).toBe(true);
176 expect(getRepoById(app.db, asked.value.id)!.archivedAt).not.toBeNull();
177 // Put away again: an ask is raised by what was filed after it was stopped, so the undo is quiet.
178 expect(found((n) => n.id === need.id)).toBeUndefined();
179 });
180
181 test("the stopped-app read walks an index, never the issue table", () => {
182 const plan = app.db.query<{ detail: string }, []>(`EXPLAIN QUERY PLAN ${ASKED_SINCE.replace("?1", "'r'").replace("?2", "'t'")}`).all().map((r) => r.detail).join("\n");
183 expect(plan).not.toMatch(/SCAN i\b|SCAN issue|TEMP B-TREE/);
184 expect(plan).toContain("issue_");
185 });
186
187 test("a pull already on the base is closed; one that adds something is not; undo opens it again", async () => {
188 await commitToBranch(app, alice, repo, { branch: "bot/landed", base: "main", message: "Landed work", files: [{ path: "L.md", content: "l\n" }] });
189 await commitToBranch(app, alice, repo, { branch: "bot/ahead", base: "main", message: "New work", files: [{ path: "N.md", content: "n\n" }] });
190 const bot = getUserByName(app.db, "bot")!;
191 const landed = await openPull(app, bot, repo, { title: "Landed work", body: "", baseBranch: "main", headBranch: "bot/landed" });
192 const ahead = await openPull(app, bot, repo, { title: "New work", body: "", baseBranch: "main", headBranch: "bot/ahead" });
193 if (!landed.ok || !ahead.ok) throw new Error("pulls");
194 for (const n of [landed.value.number, ahead.value.number])
195 app.db.query("UPDATE issue SET created_at = ?2, updated_at = ?2 WHERE repo_id = ?1 AND number = ?3").run(repo.id, new Date(Date.now() - 3 * day).toISOString(), n);
196 // The change reaches the base some other way: main moves to the pull's head.
197 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
198 const moved = Bun.spawnSync(["git", "update-ref", "refs/heads/main", landed.value.headOid], { env: gitClientEnv({ GIT_DIR: dir }) });
199 expect(moved.exitCode).toBe(0);
200 await sweepStaleAsks(app);
201
202 const need = pullNeed(landed.value.number)!;
203 expect(need.recommended).toMatchObject({ choice: "Close it", safe: true, action: "close", undo: "receipt" });
204 expect(need.recommended.reason).toContain("already on the base");
205 const other = pullNeed(ahead.value.number);
206 expect(other === undefined || other.recommended.safe === false).toBe(true);
207
208 const done = await applyRecommended({ app }, alice, false, need.id);
209 expect(done.refused).toEqual([]);
210 expect(getPull(app.db, repo.id, landed.value.number)!.state).toBe("closed");
211 expect(getPull(app.db, repo.id, landed.value.number)!.mergedAt).toBeNull();
212 expect(getPull(app.db, repo.id, ahead.value.number)!.state).toBe("open");
213
214 expect((await undoAsksBulk(app, alice, done.receipts[0]!.operation)).ok).toBe(true);
215 expect(getPull(app.db, repo.id, landed.value.number)!.state).toBe("open");
216 });
217
218 test("a merge is never recommended, whatever the pull says", async () => {
219 const merge = botPull("Advised to merge", 2, "Recommendation: merge — green and small.");
220 const rows = askLinesFor(app.db, alice);
221 const row = rows.find((r) => r.number === merge.number)!;
222 const pick = recommend(row);
223 expect(pick.safe).toBe(false);
224 expect(pick.action).toBeUndefined();
225 expect(pick.undo).toBe("none");
226 expect(pick.choice).toBe("Needs your decision");
227 // Of every need on the stack, only the four reversible fixes are ever safe.
228 for (const n of stack())
229 if (n.recommended.safe) expect(["close", "retry", "dismiss", "wake"]).toContain(n.recommended.action!);
230 const done = await applyRecommended({ app }, alice, false);
231 expect(done.plan.every((p) => !/ship|merge/i.test(p.choice))).toBe(true);
232 expect(getPull(app.db, repo.id, merge.number)!.state).toBe("open");
233 expect(getPull(app.db, repo.id, merge.number)!.mergedAt).toBeNull();
234 });
235
236 test("a parked run with a failed run is retried even when it is older than the stale window", async () => {
237 const parked = await parkedIssue("oldfailed", true);
238 const row = askLinesFor(app.db, alice).find((r) => r.id === `parked:${parked.id}`)!;
239 const old = { ...row, since: new Date(Date.now() - 40 * day).toISOString() };
240 expect(recommend(old, { now: Date.now(), landed: () => false, retryable: () => true })).toMatchObject({ choice: "Retry it", action: "retry" });
241 expect(recommend(old, { now: Date.now(), landed: () => false, retryable: () => false })).toMatchObject({ choice: "Dismiss it", action: "dismiss" });
242 });
243
244 test("an old paused, proposal or declined row is never dismissed", () => {
245 const row = askLinesFor(app.db, alice)[0]!;
246 const old = new Date(Date.now() - 90 * day).toISOString();
247 for (const kind of ["paused", "proposal", "declined"] as const) {
248 const pick = recommend({ ...row, kind, since: old }, { now: Date.now(), landed: () => false, retryable: () => false });
249 expect(pick.action).toBeUndefined();
250 expect(pick.safe).toBe(false);
251 }
252 });
test/pages-budget.test.ts +1
@@ -39,6 +39,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = {
3939 "/:owner/:name/issues/:number": { statements: 70 },
4040 "/:owner/:name/next": { statements: 65 }, // +1: the growth line, one read for the week and the planner pause (#12290)
4141 "/:owner/:name/pulls/:number": { statements: 113 }, // +1: whether a repository is the forge's own copy, one read of the source setting for the tell box (#12037); +1: the paused sentence, one read of a queued paused run on the pull (#12010); +1: the header Talk count (#10327); +1: the landing line (#10860); +1: whether a reviewer is seated, read only when Require review is off and the pull would otherwise wait on one; the page loads no crew besides (#11666)
42 "/api/v1/asks": { statements: 61 }, // +1: the stopped apps someone asked for, one read of the viewer's archived repositories (#12277)
4243 "/board": { statements: 72 }, // +1: the forge-copy read for the tell box (#12037); +1: the vitals read the database's growth (#12025); +6: the money line (#510) — one settings read, then the month's and the 30 days' meter, storage and ledger reads; constant in the number of apps
4344 "/settings/capacity": { statements: 71 },
4445 };

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs