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
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/12277-the-needs-stack-recommends-four-reversib → main 12 commits fork 4 threads · 4 unresolved
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. | ||
| 24 | 24 | `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`. |
| 25 | 25 | |
| 26 | 26 | 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>> = { | ||
| 39 | 39 | ship: "ship", |
| 40 | 40 | close: "close", |
| 41 | 41 | replan: "replan", |
| 42 | retry: "retry", | |
| 42 | 43 | }; |
| 43 | 44 | |
| 44 | 45 | /** The most asks one action takes. */ |
| @@ -142,6 +143,27 @@ export async function applyAsksBulk( | ||
| 142 | 143 | return ok({ ...op.value, skipped: r.value.skipped, line: doneWords(op.value.reversible) }); |
| 143 | 144 | } |
| 144 | 145 | |
| 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 | ||
| 145 | 167 | /** |
| 146 | 168 | * A bulk action on asks, for the one person who took it — never another, |
| 147 | 169 | * 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>> = { | ||
| 28 | 28 | ship: "Ship", |
| 29 | 29 | close: "Close", |
| 30 | 30 | replan: "Hand back to the planner", |
| 31 | retry: "Retry", | |
| 32 | archive: "Wake", | |
| 31 | 33 | }; |
| 32 | 34 | |
| 33 | 35 | /** |
src/actions/fleet.ts +10 −3
| @@ -43,7 +43,7 @@ import { | ||
| 43 | 43 | getReposByIds, |
| 44 | 44 | type Repo, |
| 45 | 45 | } from "../core/repos.ts"; |
| 46 | import { latestRunsForIssues } from "../core/runs.ts"; | |
| 46 | import { latestRunsForIssues, newestAgentRun } from "../core/runs.ts"; | |
| 47 | 47 | import { isStalePull } from "../crew/stale_asks.ts"; |
| 48 | 48 | import { askDismissedBy } from "../web/studio/asks.ts"; |
| 49 | 49 | import { mutedRepos } from "../core/interactions.ts"; |
| @@ -194,6 +194,9 @@ function loadTargets( | ||
| 194 | 194 | return seats; |
| 195 | 195 | }; |
| 196 | 196 | const peers: ReadonlySet<string> = new Set(ids); |
| 197 | const retrying = new Set( | |
| 198 | ids.filter((id) => newestAgentRun(app.db, id, ["queued", "running"]) !== undefined), | |
| 199 | ); | |
| 197 | 200 | const muted = viewer === undefined ? new Set<string>() : mutedRepos(app.db, viewer.id); |
| 198 | 201 | const pull = (id: string) => { |
| 199 | 202 | const p = pulls.get(id); |
| @@ -225,6 +228,7 @@ function loadTargets( | ||
| 225 | 228 | under: under.get(id) ?? [], |
| 226 | 229 | seating: seatingOf(repo), |
| 227 | 230 | peers, |
| 231 | ...(retrying.has(id) ? { retrying: true } : {}), | |
| 228 | 232 | ...(viewer === undefined |
| 229 | 233 | ? {} |
| 230 | 234 | : { |
| @@ -601,7 +605,7 @@ export async function applyPreviewed( | ||
| 601 | 605 | /** How long a bulk action on asks can be undone: a day. */ |
| 602 | 606 | export const UNDO_WINDOW_MS = 86_400_000; |
| 603 | 607 | |
| 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"]; | |
| 605 | 609 | |
| 606 | 610 | /** The query a bulk action on asks is receipted under: "asks: n selected". */ |
| 607 | 611 | export const ASKS_QUERY_PREFIX = "asks: "; |
| @@ -609,7 +613,10 @@ export const ASKS_QUERY_PREFIX = "asks: "; | ||
| 609 | 613 | /** Whether a receipt is a bulk action on asks: named one by one, "asks: n selected". */ |
| 610 | 614 | export function isAsksOperation(op: Operation): boolean { |
| 611 | 615 | 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")) | |
| 613 | 620 | ); |
| 614 | 621 | } |
| 615 | 622 |
src/actions/needs.ts +107 −13
| @@ -7,7 +7,12 @@ | ||
| 7 | 7 | * so the preview, the per-row access check, the receipt and the undo are theirs. |
| 8 | 8 | */ |
| 9 | 9 | 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"; | |
| 11 | 16 | import { askStackFor, type askLinesFor } from "../web/studio/asks.ts"; |
| 12 | 17 | import { weekOld } from "../flow/oldest_approved.ts"; |
| 13 | 18 | import { drillNow } from "./backups_now.ts"; |
| @@ -36,14 +41,19 @@ export interface Recommended { | ||
| 36 | 41 | /** For an item not safe: the question to put to the owner. */ |
| 37 | 42 | readonly ask?: string; |
| 38 | 43 | /** |
| 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. | |
| 41 | 46 | */ |
| 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; | |
| 43 | 50 | /** For a need with no safe default: the real options the owner picks between. */ |
| 44 | 51 | readonly options?: readonly string[]; |
| 45 | 52 | } |
| 46 | 53 | |
| 54 | /** The four fixes safe to take on a recommendation: each is reversible, none merges. */ | |
| 55 | export type SafeAction = "close" | "retry" | "dismiss" | "wake"; | |
| 56 | ||
| 47 | 57 | export interface Need { |
| 48 | 58 | readonly id: string; |
| 49 | 59 | readonly sentence: string; |
| @@ -71,14 +81,43 @@ const needsDecision = (question: string, reason: string, options: readonly strin | ||
| 71 | 81 | options, |
| 72 | 82 | }); |
| 73 | 83 | |
| 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 { | |
| 76 | 106 | const about = row.line; |
| 77 | 107 | const options = row.words.options; |
| 78 | 108 | if (row.items.length !== 1) |
| 79 | 109 | return needsDecision(`Which of these should be taken first: ${about}?`, "several changes share this row; each is its own call", options); |
| 80 | 110 | const advice = row.recommendation; |
| 81 | 111 | 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 | }; | |
| 82 | 121 | if (row.numberOf === "pull" && !conflicts) { |
| 83 | 122 | // A merge has no undo but a revert pull, so no change is shipped on a recommendation: |
| 84 | 123 | // the owner's word is the approval. |
| @@ -97,8 +136,26 @@ export function recommend(row: Row): Recommended { | ||
| 97 | 136 | undo: "receipt", |
| 98 | 137 | safe: true, |
| 99 | 138 | action: "close", |
| 139 | note: "Closed by the recommended choice: the crew advised it.", | |
| 100 | 140 | }; |
| 101 | 141 | } |
| 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 | }; | |
| 102 | 159 | if (row.kind === "stopped" && !conflicts && row.numberOf === "pull") |
| 103 | 160 | return { |
| 104 | 161 | choice: "Start the crew on it again", |
| @@ -168,7 +225,17 @@ function approvedNeeds(ctx: Home): Need[] { | ||
| 168 | 225 | |
| 169 | 226 | /** The stack: the forge's own needs first (an admin's), then the asks, most consequential first. */ |
| 170 | 227 | export function needsStack(ctx: Home, user: User, chips?: Chips): Need[] { |
| 228 | const db = ctx.app.db; | |
| 171 | 229 | 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 | }; | |
| 172 | 239 | const forge = stack.forge.map( |
| 173 | 240 | (d, i): Need => ({ |
| 174 | 241 | id: `forge:${d.cause || i}`, |
| @@ -188,12 +255,30 @@ export function needsStack(ctx: Home, user: User, chips?: Chips): Need[] { | ||
| 188 | 255 | why: row.consequence.why, |
| 189 | 256 | waits: row.words.ifNothing, |
| 190 | 257 | choices: row.words.options, |
| 191 | recommended: recommend(row), | |
| 258 | recommended: recommend(row, facts), | |
| 192 | 259 | link: row.link, |
| 193 | 260 | items: row.items, |
| 194 | 261 | }), |
| 195 | 262 | ); |
| 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]; | |
| 197 | 282 | } |
| 198 | 283 | |
| 199 | 284 | /** 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 | ||
| 265 | 350 | refused: [], |
| 266 | 351 | }; |
| 267 | 352 | 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 | } | |
| 268 | 362 | for (const n of safe.filter((n) => n.recommended.action === "drill")) { |
| 269 | 363 | const drilled = await drillNow(ctx.app, user); |
| 270 | 364 | 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 | ||
| 276 | 370 | else out.refused.push({ item, reason: back.reason }); |
| 277 | 371 | } |
| 278 | 372 | } |
| 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); | |
| 284 | 376 | if (!done.ok) { |
| 285 | 377 | out.refused.push(...items.map((item) => ({ item, reason: done.error.message }))); |
| 286 | 378 | continue; |
| @@ -290,6 +382,8 @@ export async function applyRecommended(ctx: Home, user: User, dryRun: boolean, o | ||
| 290 | 382 | for (const item of n.items) |
| 291 | 383 | if (!skipped.has(item)) out.done.push({ id: n.id, choice: n.recommended.choice, result: "closed, with a receipt" }); |
| 292 | 384 | 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 }); | |
| 293 | 387 | out.receipts.push({ |
| 294 | 388 | operation: done.value.id, |
| 295 | 389 | 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 { | ||
| 856 | 856 | appsFirst?: boolean; |
| 857 | 857 | /** Leave archived repositories out. @default false */ |
| 858 | 858 | 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; | |
| 859 | 864 | /** Only archived repositories. @default false */ |
| 860 | 865 | archivedOnly?: boolean; |
| 861 | 866 | /** Only this owner's repositories (a username, any case). */ |
| @@ -1016,6 +1021,7 @@ export function listReposWritableTo( | ||
| 1016 | 1021 | where += ` AND repo.id < ?${params.length}`; |
| 1017 | 1022 | } |
| 1018 | 1023 | if (options.withoutArchived === true) where += " AND repo.archived_at IS NULL"; |
| 1024 | if (options.onlyArchived === true) where += " AND repo.archived_at IS NOT NULL"; | |
| 1019 | 1025 | params.push(pageLimit(options.limit)); |
| 1020 | 1026 | const rows = db |
| 1021 | 1027 | .query<RepoRow, (string | number)[]>( |
src/core/runs.ts +14
| @@ -1132,6 +1132,20 @@ export function checkSummary( | ||
| 1132 | 1132 | : { state: "none", run: null }; |
| 1133 | 1133 | } |
| 1134 | 1134 | |
| 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 | ||
| 1135 | 1149 | /** |
| 1136 | 1150 | * The latest run per issue for a set of issues — one query, for a list that |
| 1137 | 1151 | * 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"; | ||
| 20 | 20 | import { latestRunsForIssues } from "../core/runs.ts"; |
| 21 | 21 | import { checkStale } from "../checks/stale.ts"; |
| 22 | 22 | import { resolveOid } from "../git/merge.ts"; |
| 23 | import { isAncestor } from "../git/local.ts"; | |
| 23 | 24 | import { repoDir } from "../git/repos.ts"; |
| 24 | 25 | |
| 25 | 26 | interface Known { |
| @@ -28,6 +29,8 @@ interface Known { | ||
| 28 | 29 | /** The pull's head the answer was taken at, as the database names it. */ |
| 29 | 30 | readonly head: string; |
| 30 | 31 | readonly stale: boolean; |
| 32 | /** The base already holds the head: everything the pull adds is there (#12277). */ | |
| 33 | readonly landed?: boolean; | |
| 31 | 34 | /** The base's tip when it was last read; empty when it could not be. */ |
| 32 | 35 | readonly base: string; |
| 33 | 36 | /** The files that stop it merging; 0 when it merges or is simply already in. */ |
| @@ -54,6 +57,13 @@ export function isStalePull( | ||
| 54 | 57 | return known !== undefined && known.stale && known.head === headOid; |
| 55 | 58 | } |
| 56 | 59 | |
| 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 | ||
| 57 | 67 | /** |
| 58 | 68 | * Whether this pull's green was checked against an older tip of its base, as |
| 59 | 69 | * the last sweep read that tip (#1179's `checkStale`). A tip not yet read is |
| @@ -102,6 +112,13 @@ export function mergesAgainSince( | ||
| 102 | 112 | /** The most pulls one sweep looks at: enough for a busy forge, bounded for a strange one. */ |
| 103 | 113 | export const SWEEP_LIMIT = 300; |
| 104 | 114 | |
| 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 | ||
| 105 | 122 | /** |
| 106 | 123 | * Look again at every open pull with a green check in a repository that |
| 107 | 124 | * asks a person (anything not `autonomous`: those settle their own). Never |
| @@ -119,10 +136,11 @@ export async function sweepStaleAsks(app: App): Promise<void> { | ||
| 119 | 136 | .all(SWEEP_LIMIT) |
| 120 | 137 | .map((r) => r.id); |
| 121 | 138 | 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()]); | |
| 124 | 141 | const open = new Set(pulls.map((p) => p.id)); |
| 125 | 142 | for (const id of known.keys()) if (!open.has(id)) known.delete(id); |
| 143 | let spawns = 0; | |
| 126 | 144 | for (const pull of pulls) { |
| 127 | 145 | const repo = getRepoById(db, pull.repoId); |
| 128 | 146 | if (!repo) continue; |
| @@ -134,8 +152,18 @@ export async function sweepStaleAsks(app: App): Promise<void> { | ||
| 134 | 152 | 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. |
||
| 135 | 153 | // An autonomous repository settles its own mergeability; only the |
| 136 | 154 | // 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++; | |
| 137 | 161 | 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)); | |
| 139 | 167 | const stale = |
| 140 | 168 | status !== undefined && |
| 141 | 169 | (status.ahead === 0 || |
| @@ -151,6 +179,7 @@ export async function sweepStaleAsks(app: App): Promise<void> { | ||
| 151 | 179 | between, |
| 152 | 180 | head: pull.headOid, |
| 153 | 181 | stale, |
| 182 | landed, | |
| 154 | 183 | base, |
| 155 | 184 | conflicts: |
| 156 | 185 | 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"; | ||
| 29 | 29 | import { getHold } from "../core/holds.ts"; |
| 30 | 30 | import { recordInteraction, removeDismissals, removeMutes } from "../core/interactions.ts"; |
| 31 | 31 | import { getPull } from "../core/pulls.ts"; |
| 32 | import { newestAgentRun } from "../core/runs.ts"; | |
| 32 | 33 | import { teamHoldRefusal } from "../core/teams_words.ts"; |
| 33 | 34 | import { askItemsOf } from "../web/studio/asks.ts"; |
| 34 | 35 | import type { FleetValue } from "../core/fleet_ops.ts"; |
| @@ -64,6 +65,8 @@ export interface Target { | ||
| 64 | 65 | readonly viewerId?: string; |
| 65 | 66 | /** For an issue: whether the viewer's dismissal of its ask still holds. */ |
| 66 | 67 | readonly askDismissed?: boolean; |
| 68 | /** For an issue: an agent run on it is waiting or going. */ | |
| 69 | readonly retrying?: boolean; | |
| 67 | 70 | /** Whether the viewer muted this repository. */ |
| 68 | 71 | readonly muted?: boolean; |
| 69 | 72 | /** 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> = { | ||
| 472 | 475 | }, |
| 473 | 476 | }, |
| 474 | 477 | |
| 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 | ||
| 475 | 499 | // Hand back to the planner: the issue is assigned to the repository's |
| 476 | 500 | // planner, which re-plans it. Never on a public repository, where a crew |
| 477 | 501 | // assignment would let any reader's comment steer the run (#619). |
src/web/studio/asks.ts +8 −6
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | * forms and buttons are `decisions.ts`. |
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | import { askedAsleep, asleepLine } from "../../actions/needs_asleep.ts"; | |
| 10 | 11 | import type { Database } from "bun:sqlite"; |
| 11 | 12 | import { crewHandsFor } from "../../actions/give_back.ts"; |
| 12 | 13 | import { forgeNeedList, type ForgeNeed } from "../../actions/health.ts"; |
| @@ -58,7 +59,7 @@ import { | ||
| 58 | 59 | } from "../../crew/autonomy.ts"; |
| 59 | 60 | import { breakerParked, WAITING_NOTES } from "../../crew/breaker.ts"; |
| 60 | 61 | 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"; | |
| 62 | 63 | import { reviewSays } from "../../crew/review_says.ts"; |
| 63 | 64 | import { reviewerPaused } from "../../crew/reviewer_paused.ts"; |
| 64 | 65 | import { reviewWaitsFor, type ReviewWait } from "../../crew/review.ts"; |
| @@ -376,7 +377,7 @@ function askCandidatesFor( | ||
| 376 | 377 | settled.flatMap((p) => { |
| 377 | 378 | const pull = joined.get(p.id)!; |
| 378 | 379 | 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) | |
| 380 | 381 | ? [{ repo: byId.get(p.repoId)!, pull }] |
| 381 | 382 | : []; |
| 382 | 383 | }), |
| @@ -451,7 +452,7 @@ function askCandidatesFor( | ||
| 451 | 452 | repo.autonomy !== "autonomous" && |
| 452 | 453 | // A green pull that no longer merges as it stands cannot be shipped: |
| 453 | 454 | // 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)) && | |
| 455 | 456 | // A green checked against an older base is a check still to come. |
| 456 | 457 | !staleGreen(db, pull, check) |
| 457 | 458 | ) { |
| @@ -477,7 +478,7 @@ function askCandidatesFor( | ||
| 477 | 478 | } else if ( |
| 478 | 479 | check?.state === "ok" && |
| 479 | 480 | repo.autonomy === "autonomous" && |
| 480 | !isStalePull(db, pull.id, pull.headOid) && | |
| 481 | (!isStalePull(db, pull.id, pull.headOid) || isLandedPull(db, pull.id, pull.headOid)) && | |
| 481 | 482 | !staleGreen(db, pull, check) |
| 482 | 483 | ) { |
| 483 | 484 | // An autonomous repository lands its own green pulls once reviewed; |
| @@ -1200,14 +1201,14 @@ export function askStackFor( | ||
| 1200 | 1201 | chips?: Chips, |
| 1201 | 1202 | onHidden?: (rows: number) => void, |
| 1202 | 1203 | ) { |
| 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) }; | |
| 1204 | 1205 | } |
| 1205 | 1206 | |
| 1206 | 1207 | /** How many things ask the viewer: the stack's length, the number the header and asks page show. */ |
| 1207 | 1208 | export function askCountFor(ctx: Pick<Ctx, "app">, user: User | undefined): number { |
| 1208 | 1209 | if (!user) return 0; |
| 1209 | 1210 | const stack = askStackFor(ctx, user); |
| 1210 | return stack.forge.length + stack.rows.length; | |
| 1211 | return stack.forge.length + stack.rows.length + stack.asleep.length; | |
| 1211 | 1212 | } |
| 1212 | 1213 | |
| 1213 | 1214 | /** 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) { | ||
| 1234 | 1235 | waiting: { count: set.count, stale: set.stale.length }, |
| 1235 | 1236 | rows, |
| 1236 | 1237 | forge: stack.forge.map((n) => n.line), |
| 1238 | asleep: stack.asleep.map((a) => ({ repo: `${a.repo.ownerName}/${a.repo.name}`, sentence: asleepLine(a) })), | |
| 1237 | 1239 | measure: { days: ASKS_WINDOW_DAYS, ...askMeasureWeek(ctx.app.db, user.id) }, |
| 1238 | 1240 | ...(hasAskFilters(askFiltersOf(ctx.app.db, user.id)) ? { filters: { hidden, line: hiddenLine(hidden) } } : {}), |
| 1239 | 1241 | }; |
src/web/studio/asks_page.ts +15 −2
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | * (`actions/asks_bulk.ts`). `/asks` was its own screen; it lands here now. |
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | import { askedAsleep, asleepLine, type Asleep } from "../../actions/needs_asleep.ts"; | |
| 10 | 11 | import { UNDO_LABEL, VERB_WORDS } from "../../actions/asks_words.ts"; |
| 11 | 12 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 12 | 13 | import type { WaitingFor } from "../../core/waiting_for.ts"; |
| @@ -413,6 +414,17 @@ export const forgeCard = (d: ForgeNeed): Html => | ||
| 413 | 414 | <div class="bar">${btn("Health", { href: "/api/v1/health", size: "sm" })}</div> |
| 414 | 415 | </section>`; |
| 415 | 416 | |
| 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 | ||
| 416 | 428 | /** What sits above the asks after a bulk step: a preview to confirm, a receipt, or why nothing was done. */ |
| 417 | 429 | export interface AsksTop { |
| 418 | 430 | readonly banner: Html; |
| @@ -545,7 +557,8 @@ export function needsYouSection( | ||
| 545 | 557 | )} |
| 546 | 558 | </details>`; |
| 547 | 559 | 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; | |
| 549 | 562 | if (count === 0 && top === undefined) |
| 550 | 563 | return { |
| 551 | 564 | body: html`<h2 id="asks-sentence" class="sr-only">${askSentence(0)}</h2>${filtered}${silencedNote}${asideNote}${undo}`, |
| @@ -574,7 +587,7 @@ export function needsYouSection( | ||
| 574 | 587 | const body = html`<section id="needs-you" class="stack"> |
| 575 | 588 | <h2 id="asks-sentence">${askSentence(count)}</h2> |
| 576 | 589 | ${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))} | |
| 578 | 591 | ${middle.length === 0 |
| 579 | 592 | ? null |
| 580 | 593 | : 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 }> = { | ||
| 39 | 39 | "/:owner/:name/issues/:number": { statements: 70 }, |
| 40 | 40 | "/:owner/:name/next": { statements: 65 }, // +1: the growth line, one read for the week and the planner pause (#12290) |
| 41 | 41 | "/: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) | |
| 42 | 43 | "/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 |
| 43 | 44 | "/settings/capacity": { statements: 71 }, |
| 44 | 45 | }; |
new above
offline
Dismiss shadows the retry below it: an old parked run is never retried. Move the retry branch above this one.