Public: anyone can read this; the crew can change it.
A maintenance duty lists merged pull branches older than seven days and offers to delete them in one tap #13347
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/13321-a-maintenance-duty-lists-merged-pull-bra → main 8 commits fork 3 threads · 3 unresolved
10 files
changed +493
−2
docs/features/maintenance-duties.md +9
| @@ -12,3 +12,12 @@ All doors are for a forge admin and call one function, `switchDuty` in `src/main | ||
| 12 | 12 | An unknown duty name is 404 (a flash on the page); a `paused` that is not a boolean is 422. |
| 13 | 13 | |
| 14 | 14 | Tests: `test/maintain-parked-issue.test.ts` (one issue for three failures and a fourth tick), `test/maintain-pause.test.ts` (the three errors, resume from the API, the page and the terminal, the gates). |
| 15 | ||
| 16 | ## Merged branches (#13321) | |
| 17 | ||
| 18 | The `merged-branches` duty finds branches of pulls that merged over seven days ago and whose tip is still the head they merged with. Never listed: the default branch, a branch an open pull uses, a branch that moved since, a fork's branch. It reads refs from the repository's files in one pass (no git process per branch) and lists at most 100 (`MERGED_CAP`), oldest first. | |
| 19 | ||
| 20 | - **On the web.** `/maintenance` folds the list (name, short head, merge day) with a required confirm box and **Delete all** (`POST /maintenance/branches/delete`, same-origin, a forge admin who is a person). A branch not on the list any more is left alone; the flash receipt names each deleted branch with its full head. | |
| 21 | - **In the terminal.** Ctrl-K, **Branches of pulls merged over 7 days ago**: the same rows; `d` deletes them all after a confirm, with the same receipt. | |
| 22 | ||
| 23 | Tests: `test/maintain-merged-branches.test.ts`, `test/maintain-merged-web.test.ts`. |
src/http/server.ts +2 −1
| @@ -41,7 +41,7 @@ import { contributePage } from "../web/pages/contribute.ts"; | ||
| 41 | 41 | import { pipelinePage } from "../web/pages/pipeline.ts"; |
| 42 | 42 | import { adminDataPage, appDataCsv, appDataPage, dataPage } from "../web/pages/data.ts"; |
| 43 | 43 | import { fleetAct, fleetReceipt, fleetUndo } from "../web/pages/fleet-ops.ts"; |
| 44 | import { maintenanceDuty, maintenancePage, maintenancePrepare, maintenanceResume, staleAction } from "../web/pages/maintenance.ts"; | |
| 44 | import { maintenanceDuty, maintenancePage, maintenancePrepare, maintenanceResume, staleAction, mergedAction } from "../web/pages/maintenance.ts"; | |
| 45 | 45 | import { maintenanceBudget } from "../web/pages/maintenance_budgets.ts"; |
| 46 | 46 | import { nightlyOutputPage, resiliencePage } from "../web/pages/resilience.ts"; |
| 47 | 47 | import { agentStartSet, billingLinksSet, limitsPage, limitsSet, quotasSet, signupSet, inviteMint, inviteRevoke } from "../web/pages/admin-limits.ts"; |
| @@ -1128,6 +1128,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1128 | 1128 | router.add("POST", "/maintenance/budget", maintenanceBudget); |
| 1129 | 1129 | router.add("POST", "/maintenance/duties/:name", maintenanceDuty); |
| 1130 | 1130 | router.add("POST", "/maintenance/stale/:id/:what", staleAction); |
| 1131 | router.add("POST", "/maintenance/branches/delete", mergedAction); | |
| 1131 | 1132 | router.add("GET", "/resilience/nightly/:job", nightlyOutputPage); |
| 1132 | 1133 | // A selection's spend and runs over time; literal, above /:owner. |
| 1133 | 1134 | router.add("GET", "/fleet", fleetPage); |
src/maintain/duties/merged_branches.ts added +125
| @@ -0,0 +1,125 @@ | ||
| 1 | /** | |
| 2 | * Merged branches (#13321): branches whose pull merged more than seven days ago, listed on one | |
| 3 | * card with one "Delete all". The duty only reads; the deletion is `deleteMerged`, pressed by a | |
| 4 | * forge admin, receipted with every name and head so it can be undone by hand. | |
| 5 | * Never listed: the default branch, any branch an open pull still uses, a branch that has moved | |
| 6 | * since the pull merged, a branch of a fork. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../../app.ts"; | |
| 10 | import { deleteBranch } from "../../actions/branches.ts"; | |
| 11 | import { getRepoById } from "../../core/repos.ts"; | |
| 12 | import type { User } from "../../core/users.ts"; | |
| 13 | import { isBranchName } from "../../git/branches.ts"; | |
| 14 | import { repoDir } from "../../git/repos.ts"; | |
| 15 | import { readTips } from "../../git/tips.ts"; | |
| 16 | import { err, ok, type Result } from "../../kernel/result.ts"; | |
| 17 | import type { Duty } from "../duty.ts"; | |
| 18 | import { record } from "../runs.ts"; | |
| 19 | ||
| 20 | export const MERGED_DAYS = 7; | |
| 21 | const DAY_MS = 86_400_000; | |
| 22 | ||
| 23 | export interface MergedBranch { | |
| 24 | readonly repoId: string; | |
| 25 | readonly repo: string; | |
| 26 | readonly branch: string; | |
| 27 | /** The branch's tip, which is the pull's head at merge. */ | |
| 28 | readonly head: string; | |
| 29 | readonly mergedAt: string; | |
| 30 | } | |
| 31 | ||
| 32 | export const MERGED_SQL = `SELECT r.id AS repo_id, o.username || '/' || r.name AS repo, r.default_branch AS def, | |
| 33 | pull.head_branch AS branch, pull.head_oid AS head, MAX(pull.merged_at) AS merged_at | |
| 34 | FROM pull JOIN issue ON issue.id = pull.issue_id | |
| 35 | JOIN repo r ON r.id = issue.repo_id JOIN user o ON o.id = r.owner_id | |
| 36 | WHERE pull.merged_at IS NOT NULL AND pull.merged_at < ?1 | |
| 37 | AND (pull.head_repo_id IS NULL OR pull.head_repo_id = issue.repo_id) | |
| 38 | AND pull.head_branch <> r.default_branch | |
| 39 | AND NOT EXISTS (SELECT 1 FROM issue i2 JOIN pull p2 ON p2.issue_id = i2.id | |
| 40 | WHERE i2.state = 'open' AND i2.kind = 'pull' AND p2.head_branch = pull.head_branch | |
| 41 | AND COALESCE(p2.head_repo_id, i2.repo_id) = issue.repo_id) | |
| 42 | GROUP BY r.id, pull.head_branch | |
| 43 | ORDER BY merged_at, repo, branch`; | |
| 44 | ||
| 45 | interface Row { repo_id: string; repo: string; def: string; branch: string; head: string; merged_at: string } | |
| 46 | ||
| 47 | /** The most branches one card lists; the rest wait for the next press, once these are gone. */ | |
| 48 | export const MERGED_CAP = 100; | |
| 49 | ||
| 50 | /** | |
| 51 | * Merged branches still standing at the head they merged with, oldest merge first, at most `cap`. | |
| 52 | * Reads only, and spawns no git: one pass over the rows, the refs of each repository read from its | |
| 53 | * files together (`readTips`), so a branch already deleted costs a missed file, not a process. | |
| 54 | */ | |
| 55 | export async function mergedBranches(app: App, now: Date, days = MERGED_DAYS, cap = MERGED_CAP): Promise<MergedBranch[]> { | |
| 56 | const cutoff = new Date(now.getTime() - days * DAY_MS).toISOString(); | |
| 57 | const byRepo = new Map<string, Row[]>(); | |
| 58 | for (const row of app.db.query<Row, [string]>(MERGED_SQL).all(cutoff)) { | |
| 59 | if (!isBranchName(row.branch) || row.branch === row.def) continue; | |
| 60 | byRepo.set(row.repo_id, [...(byRepo.get(row.repo_id) ?? []), row]); | |
| 61 | } | |
| 62 | const out: MergedBranch[] = []; | |
| 63 | for (const [repoId, rows] of byRepo) { | |
| 64 | const repo = getRepoById(app.db, repoId); | |
| 65 | if (repo === undefined) continue; | |
| 66 | const tips = await readTips(repoDir(app.reposRoot, repo.ownerName, repo.name), rows.map((r) => `refs/heads/${r.branch}`)); | |
| 67 | for (const row of rows) { | |
| 68 | const tip = tips.get(`refs/heads/${row.branch}`); | |
| 69 | if (tip !== undefined && tip === row.head) out.push({ repoId, repo: row.repo, branch: row.branch, head: tip, mergedAt: row.merged_at }); | |
| 70 | } | |
| 71 | } | |
| 72 | return out.sort((a, b) => a.mergedAt.localeCompare(b.mergedAt) || a.repo.localeCompare(b.repo) || a.branch.localeCompare(b.branch)).slice(0, cap); | |
| 73 | } | |
| 74 | ||
| 75 | /** One line per branch: what the receipt and the form carry. */ | |
| 76 | export const lineOf = (b: Pick<MergedBranch, "repo" | "branch" | "head">): string => `${b.repo}:${b.branch}@${b.head}`; | |
| 77 | ||
| 78 | export type MergedError = "forbidden" | "nothing" | "failed"; | |
| 79 | export const MERGED_WORDS: Record<MergedError, string> = { | |
| 80 | forbidden: "Only a forge admin may do this.", | |
| 81 | nothing: "None of those branches is still listed; the card was out of date.", | |
| 82 | failed: "The forge refused the deletion.", | |
| 83 | }; | |
| 84 | ||
| 85 | /** | |
| 86 | * Delete the listed branches the card showed (`shown`: lines from `lineOf`), each only if it is | |
| 87 | * still on the list now. The receipt names every deleted branch with its head. | |
| 88 | */ | |
| 89 | export async function deleteMerged(app: App, admin: User | undefined, shown: readonly string[], now = new Date()): Promise<Result<{ says: string }, MergedError>> { | |
| 90 | if (admin === undefined || !admin.isAdmin) return err("forbidden"); | |
| 91 | const want = new Set(shown); | |
| 92 | const gone: string[] = []; | |
| 93 | let refused = 0; | |
| 94 | for (const b of await mergedBranches(app, now)) { | |
| 95 | if (!want.has(lineOf(b))) continue; | |
| 96 | const repo = getRepoById(app.db, b.repoId); | |
| 97 | const done = repo && (await deleteBranch(app, admin, repo, b.branch)); | |
| 98 | if (done && done.ok) gone.push(lineOf(b)); | |
| 99 | else refused++; | |
| 100 | } | |
| 101 | if (gone.length === 0) return err(refused > 0 ? "failed" : "nothing"); | |
| 102 | const says = `deleted ${gone.length} merged branch${gone.length === 1 ? "" : "es"} (pressed by ${admin.username}): ${gone.join(", ")}`; | |
| 103 | record(app.db, { duty: "merged-branches", started: now, finished: now, findings: [], actions: [says], outcome: "ok" }); | |
| 104 | return ok({ says }); | |
| 105 | } | |
| 106 | ||
| 107 | export const duty: Duty = { | |
| 108 | name: "merged-branches", | |
| 109 | intervalMs: 6 * 3_600_000, | |
| 110 | budget: { runsPerDay: 8, dollarsPerDay: 1, reason: "every six hours is four a day; the rest is room for a catch-up, and it spends no money" }, | |
| 111 | async run({ now, app }) { | |
| 112 | if (app === undefined) return { findings: [], actions: [] }; | |
| 113 | const found = await mergedBranches(app, now); | |
| 114 | if (found.length === 0) return { findings: [], actions: [] }; | |
| 115 | return { | |
| 116 | findings: [ | |
| 117 | { | |
| 118 | summary: `${found.length} branch${found.length === 1 ? "" : "es"} of pulls merged over ${MERGED_DAYS} days ago: ${found.slice(0, 5).map((b) => `${b.repo}:${b.branch}`).join(", ")}${found.length > 5 ? ", …" : ""}`, | |
| 119 | probe: { kind: "measurement", what: "branches whose pull merged over seven days ago and whose head has not moved", number: found.length, at: now.toISOString() }, | |
| 120 | }, | |
| 121 | ], | |
| 122 | actions: [], | |
| 123 | }; | |
| 124 | }, | |
| 125 | }; |
src/maintain/registry.ts +2 −1
| @@ -8,6 +8,7 @@ import { duty as flowKeeper } from "./duties/flow_keeper.ts"; | ||
| 8 | 8 | import { duty as visitorRetention } from "./duties/visitor_retention.ts"; |
| 9 | 9 | import { duty as backupGrowth } from "./duties/backup_growth.ts"; |
| 10 | 10 | import { duty as v1Proven } from "./duties/v1_proven.ts"; |
| 11 | import { duty as mergedBranches } from "./duties/merged_branches.ts"; | |
| 11 | 12 | import { duty as diskFree } from "./duties/disk_free.ts"; |
| 12 | 13 | |
| 13 | export const duties: readonly Duty[] = [pullsWaiting, ruleWatcher, efficiencyWatcher, flowKeeper, visitorRetention, backupGrowth, v1Proven, diskFree]; | |
| 14 | export const duties: readonly Duty[] = [pullsWaiting, ruleWatcher, efficiencyWatcher, flowKeeper, visitorRetention, backupGrowth, v1Proven, diskFree, mergedBranches]; |
src/tui/screens/entries.ts +2
| @@ -76,6 +76,7 @@ import { entry as maintenance } from "./maintenance.ts"; | ||
| 76 | 76 | import { entry as maintainRuns } from "./maintainruns.ts"; |
| 77 | 77 | import { entry as dutyBudgets } from "./dutybudgets.ts"; |
| 78 | 78 | import { entry as stalePulls } from "./stalepulls.ts"; |
| 79 | import { entry as mergedBranches } from "./mergedbranches.ts"; | |
| 79 | 80 | import { entry as dutySwitch } from "./dutyswitch.ts"; |
| 80 | 81 | import { entry as mirrorPacksEntry } from "./mirrorpacks.ts"; |
| 81 | 82 | import { entry as packReposEntry } from "./packrepos.ts"; |
| @@ -149,6 +150,7 @@ export const ENTRIES: readonly PaletteEntry[] = [ | ||
| 149 | 150 | resilience, |
| 150 | 151 | maintenance, |
| 151 | 152 | stalePulls, |
| 153 | mergedBranches, | |
| 152 | 154 | maintainRuns, |
| 153 | 155 | dutySwitch, |
| 154 | 156 | dutyBudgets, |
src/tui/screens/mergedbranches.ts added +82
| @@ -0,0 +1,82 @@ | ||
| 1 | /** | |
| 2 | * Merged branches in the terminal (#13321): the /maintenance card through the same finder | |
| 3 | * (`mergedBranches`) and the same action (`deleteMerged`), behind the same gate, a forge admin who | |
| 4 | * is a person. `d` deletes every listed branch, after a confirm; the receipt is the one the page | |
| 5 | * flashes. Esc or q closes it. | |
| 6 | */ | |
| 7 | ||
| 8 | import { MERGED_DAYS, MERGED_WORDS, deleteMerged, lineOf, mergedBranches, type MergedBranch } from "../../maintain/duties/merged_branches.ts"; | |
| 9 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 10 | import { binding } from "../app/keys.ts"; | |
| 11 | import type { Session } from "../session.ts"; | |
| 12 | import { style } from "../term/style.ts"; | |
| 13 | import { Scroll, confirmScreen, drawLines } from "./common.ts"; | |
| 14 | import type { PaletteEntry } from "./entries.ts"; | |
| 15 | ||
| 16 | const mayAct = (session: Session): boolean => session.user?.isAdmin === true && session.user.kind !== "agent"; | |
| 17 | ||
| 18 | /** The branches the card lists; none for anyone the gate refuses. */ | |
| 19 | export async function merged(session: Session): Promise<MergedBranch[]> { | |
| 20 | return mayAct(session) ? mergedBranches(session.app, new Date()) : []; | |
| 21 | } | |
| 22 | ||
| 23 | /** One branch a line: name, short head, merge day; the same rows as the page. */ | |
| 24 | export function mergedLines(found: readonly MergedBranch[]): string[] { | |
| 25 | if (found.length === 0) return ["None."]; | |
| 26 | return found.map((b) => ` ${b.repo}:${b.branch} ${b.head.slice(0, 12)} merged ${b.mergedAt.slice(0, 10)}`); | |
| 27 | } | |
| 28 | ||
| 29 | /** Delete what `found` lists; what it says, or nothing for anyone the gate refuses. */ | |
| 30 | export async function deleteListed(session: Session, found: readonly MergedBranch[]): Promise<string> { | |
| 31 | if (!mayAct(session) || found.length === 0) return ""; | |
| 32 | const done = await deleteMerged(session.app, session.user, found.map(lineOf)); | |
| 33 | return done.ok ? done.value.says : MERGED_WORDS[done.error]; | |
| 34 | } | |
| 35 | ||
| 36 | export function mergedBranchesScreen(session: Session, ctx: Ctx): Screen { | |
| 37 | let found: MergedBranch[] = []; | |
| 38 | let note = ""; | |
| 39 | const load = (): void => void merged(session).then((f) => { found = f; ctx.invalidate(); }); | |
| 40 | load(); | |
| 41 | const screen: Screen = { | |
| 42 | title: `Branches of pulls merged over ${MERGED_DAYS} days ago`, | |
| 43 | keys: [binding(["d"], "delete all"), binding(["esc", "q"], "back")], | |
| 44 | render(area, s) { | |
| 45 | const c = ctx.theme.c; | |
| 46 | const lines = [...mergedLines(found), ...(note === "" ? [] : ["", note])]; | |
| 47 | drawLines(s, area, c, new Scroll(), lines.map((text) => [{ text, style: style(c.fg, c.bg) }])); | |
| 48 | }, | |
| 49 | key(e) { | |
| 50 | if (e.ctrl || e.alt) return true; | |
| 51 | if (e.key === "esc" || e.key === "q") ctx.pop(); | |
| 52 | else if (e.key === "d") { | |
| 53 | if (!mayAct(session) || found.length === 0) return true; | |
| 54 | const shown = found; | |
| 55 | ctx.push( | |
| 56 | confirmScreen(ctx, screen, { | |
| 57 | title: `Delete ${shown.length} merged branches?`, | |
| 58 | body: ["Each name and head goes in the receipt; recreate one with git branch name head."], | |
| 59 | actions: [{ label: "Cancel", variant: "ghost" }, { label: "Delete all", variant: "danger" }], | |
| 60 | onChoose: (i) => { | |
| 61 | if (i !== 1) return; | |
| 62 | void deleteListed(session, shown).then((says) => { note = says; load(); }); | |
| 63 | }, | |
| 64 | }), | |
| 65 | ); | |
| 66 | return true; | |
| 67 | } else return false; | |
| 68 | ctx.invalidate(); | |
| 69 | return true; | |
| 70 | }, | |
| 71 | }; | |
| 72 | return screen; | |
| 73 | } | |
| 74 | ||
| 75 | export const entry: PaletteEntry = { | |
| 76 | id: "merged-branches", | |
| 77 | title: "Branches of pulls merged over 7 days ago", | |
| 78 | hint: "delete the merged pulls' branches in one receipted step", | |
| 79 | after: ["maintenance", "maintenance-runs", "stale-pulls"], | |
| 80 | offered: mayAct, | |
| 81 | run: (session, ctx) => ctx.push(mergedBranchesScreen(session, ctx)), | |
| 82 | }; |
src/web/pages/maintenance.ts +37
| @@ -17,6 +17,7 @@ import { icon } from "../icons.ts"; | ||
| 17 | 17 | import { flashTo, page } from "../layout.ts"; |
| 18 | 18 | import { badge, btn, disclosure, field } from "../ui.ts"; |
| 19 | 19 | import { STALE_DAYS, STALE_WORDS, closeStale, nudge, stalePulls } from "../../maintain/stale_pulls.ts"; |
| 20 | import { MERGED_DAYS, MERGED_WORDS, deleteMerged, lineOf, mergedBranches, type MergedBranch } from "../../maintain/duties/merged_branches.ts"; | |
| 20 | 21 | import { writePauseFold } from "./maintenance_pause.ts"; |
| 21 | 22 | import { budgetRows } from "./maintenance_budgets.ts"; |
| 22 | 23 | |
| @@ -54,6 +55,7 @@ export async function maintenancePage(ctx: Ctx): Promise<Response> { | ||
| 54 | 55 | const s = await statusWithStandby(status(ctx.app)); |
| 55 | 56 | const ran = duties(ctx.app.config.dataDir); |
| 56 | 57 | const states = dutyStates(ctx.app.db); |
mergedBranches reads git for every historical merged pull on each page load; unbounded. Cap or cache it (body item 3). |
||
| 58 | const mergedPending = await mergedBranches(ctx.app, new Date()); | |
| 57 | 59 | const stalePending = stalePulls(ctx.app.db, new Date()); |
| 58 | 60 | const stale = stalePending.length; |
| 59 | 61 | const overdue = ran.filter((d) => d.overdue).length; |
| @@ -82,6 +84,9 @@ export async function maintenancePage(ctx: Ctx): Promise<Response> { | ||
| 82 | 84 | ${stale > 0 |
| 83 | 85 | ? fold("stale-pulls", `Pulls untouched for ${String(STALE_DAYS)} days`, String(stale), true, staleRows(ctx.auth.user!.kind !== "agent", stalePending)) |
| 84 | 86 | : null} |
| 87 | ${mergedPending.length > 0 | |
| 88 | ? fold("merged-branches", `Branches of pulls merged over ${String(MERGED_DAYS)} days ago`, String(mergedPending.length), true, mergedRows(ctx.auth.user!.kind !== "agent", mergedPending)) | |
| 89 | : null} | |
| 85 | 90 | ${idle |
| 86 | 91 | ? fold("maintenance-prepare", "Prepare for a power-off", `${String(ABOUT_TO_STOP_ROWS.length)} things stop`, false, |
| 87 | 92 | html`<p id="maintenance-standby" class="muted">${s.standby.says}</p> |
| @@ -180,3 +185,35 @@ export async function staleAction(ctx: Ctx): Promise<Response> { | ||
| 180 | 185 | const done = (what === "nudge" ? nudge : closeStale)(ctx.app, user, ctx.params["id"] ?? ""); |
| 181 | 186 | return flashTo(ctx, "/maintenance", done.ok ? { message: done.value.says } : { tone: "danger", message: STALE_WORDS[done.error] }); |
| 182 | 187 | } |
| 188 | ||
| 189 | /** | |
| 190 | * The merged branches as one card: every name and head is the preview, one button deletes them all. | |
| 191 | */ | |
| 192 | function mergedRows(withActions: boolean, found: readonly MergedBranch[]): Html { | |
| 193 | return html`<dl class="status-rows">${found.map( | |
| 194 | (b) => html`<div class="status-row" data-branch="${b.repo}:${b.branch}"><dt>${b.repo}:${b.branch}</dt><dd><code>${b.head.slice(0, 12)}</code> <span class="muted">merged ${b.mergedAt.slice(0, 10)}</span></dd></div>`, | |
| 195 | )}</dl> | |
| 196 | ${withActions | |
| 197 | ? html`<form method="post" action="/maintenance/branches/delete" class="stack"> | |
| 198 | ${found.map((b) => html`<input type="hidden" name="shown" value="${lineOf(b)}">`)} | |
| 199 | ${field({ name: "confirm", type: "checkbox", value: "yes", required: true, label: `Delete these ${String(found.length)} branches` })} | |
| 200 | <div class="form-actions">${btn("Delete all", { variant: "danger" })}</div> | |
| 201 | </form>` | |
| 202 | : null}`; | |
| 203 | } | |
| 204 | ||
| 205 | /** | |
outdated
Principle 7/6: the dl of rows is right, but the form also needs the receipt sentence twice (hint plus flash); keep one. Also the hand-rolled label class 'check' with inline checkbox: use the named field/confirm component from ui.ts if one exists. Required: a test posting here (see body item 2). |
||
| 206 | * POST /maintenance/branches/delete: delete the branches the card showed, receipted. Same-origin by | |
| 207 | * readForm. | |
| 208 | */ | |
| 209 | export async function mergedAction(ctx: Ctx): Promise<Response> { | |
| 210 | const user = ctx.auth.user; | |
| 211 | if (user === undefined || !user.isAdmin || user.kind === "agent") | |
| 212 | return flashTo(ctx, "/maintenance", { tone: "danger", message: MERGED_WORDS.forbidden }); | |
| 213 | const form = await readForm(ctx, "admin"); | |
| 214 | if (form instanceof Response) return form; | |
| 215 | if (form.get("confirm") !== "yes") return flashTo(ctx, "/maintenance", { tone: "danger", message: "Tick the box to confirm the delete." }); | |
| 216 | const shown = form.getAll("shown").filter((v): v is string => typeof v === "string" && v.length <= 400).slice(0, 500); | |
| 217 | const done = await deleteMerged(ctx.app, user, shown); | |
| 218 | return flashTo(ctx, "/maintenance", done.ok ? { message: done.value.says.slice(0, 600) } : { tone: "danger", message: MERGED_WORDS[done.error] }); | |
| 219 | } |
test/maintain-merged-branches.test.ts added +107
| @@ -0,0 +1,107 @@ | ||
| 1 | /** Merged branches (#13321): what the finder lists and leaves, and the one receipted deletion. */ | |
| 2 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 3 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { createBranch, deleteBranch } from "../src/actions/branches.ts"; | |
| 7 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 8 | import { createApp, type App } from "../src/app.ts"; | |
| 9 | import { createRepo, type Repo } from "../src/core/repos.ts"; | |
| 10 | import { createUser, type User } from "../src/core/users.ts"; | |
| 11 | import { resolveOid } from "../src/git/merge.ts"; | |
| 12 | import { repoDir } from "../src/git/repos.ts"; | |
| 13 | import { id } from "../src/kernel/id.ts"; | |
| 14 | import { duty, deleteMerged, lineOf, mergedBranches } from "../src/maintain/duties/merged_branches.ts"; | |
| 15 | import { duties } from "../src/maintain/registry.ts"; | |
| 16 | import { latest } from "../src/maintain/runs.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | const NOW = new Date("2026-11-14T12:00:00Z"); | |
| 21 | const ago = (d: number): string => new Date(NOW.getTime() - d * 86_400_000).toISOString(); | |
| 22 | let dir = "", app: App, admin: User, person: User, repo: Repo, seq = 0; | |
| 23 | ||
| 24 | const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => { | |
| 25 | if (!r.ok) throw new Error(JSON.stringify(r.error)); | |
| 26 | return r.value; | |
| 27 | }; | |
| 28 | const tip = (b: string) => resolveOid(repoDir(app.reposRoot, repo.ownerName, repo.name), `refs/heads/${b}`); | |
| 29 | ||
| 30 | /** A branch and a pull on it: merged `days` ago, or open when `days` is null. */ | |
| 31 | async function pull(branch: string, days: number | null, moved = false): Promise<void> { | |
| 32 | if ((await tip(branch)) === undefined) must(await createBranch(app, admin, repo, { name: branch })); | |
| 33 | if (moved) must(await commitToBranch(app, admin, repo, { branch, message: "more", files: [{ path: `${branch}.txt`, content: "x\n" }] })); | |
| 34 | const head = moved ? "1".repeat(40) : (await tip(branch))!; | |
| 35 | const issue = id(), n = ++seq; | |
| 36 | const when = ago(days ?? 1); | |
| 37 | app.db.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, ?6, ?7, ?7)").run(issue, repo.id, n, `P${n}`, admin.id, days === null ? "open" : "closed", when); | |
| 38 | app.db.query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id, merged_at) VALUES (?1, 'main', ?2, ?3, ?4, ?5, ?6)").run(issue, branch, head, head, repo.id, days === null ? null : when); | |
| 39 | } | |
| 40 | ||
| 41 | beforeAll(async () => { | |
| 42 | dir = await mkdtemp(join(tmpdir(), "forge-merged-branches-")); | |
| 43 | app = createApp({ dataDir: dir, port: 0 }); | |
| 44 | admin = must(await createUser(app.db, { username: "boss", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, isAdmin: true })); | |
| 45 | person = must(await createUser(app.db, { username: "pat", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true })); | |
| 46 | repo = must(await createRepo(app.db, app.reposRoot, { ownerId: admin.id, name: "r", visibility: "public", description: "r" })); | |
| 47 | must(await commitToBranch(app, admin, repo, { message: "seed", files: [{ path: "a.txt", content: "a\n" }] })); | |
| 48 | await pull("old-merged", 10); | |
| 49 | await pull("fresh-merged", 2); | |
| 50 | await pull("still-open", null); | |
| 51 | await pull("moved-on", 10, true); | |
| 52 | await pull("reused", 10); | |
| 53 | await pull("reused", null); // an open pull uses the same branch again | |
| 54 | }); | |
| 55 | afterAll(async () => { | |
| 56 | app.close(); | |
| 57 | await rm(dir, { recursive: true, force: true }); | |
| 58 | }); | |
| 59 | ||
| 60 | test("lists only a branch whose pull merged over seven days ago and has not moved", async () => { | |
| 61 | const names = (await mergedBranches(app, NOW)).map((b) => b.branch); | |
| 62 | expect(names).toEqual(["old-merged"]); | |
| 63 | }); | |
| 64 | ||
| 65 | test("never lists main, even when a pull merged from it", async () => { | |
| 66 | const issue = id(); | |
| 67 | app.db.query("INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at, updated_at) VALUES (?1, ?2, ?3, 'pull', 'm', '', ?4, 'closed', ?5, ?5)").run(issue, repo.id, ++seq, admin.id, ago(20)); | |
| 68 | app.db.query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id, merged_at) VALUES (?1, 'x', 'main', ?2, ?2, ?3, ?4)").run(issue, (await tip("main"))!, repo.id, ago(20)); | |
| 69 | expect((await mergedBranches(app, NOW)).map((b) => b.branch)).toEqual(["old-merged"]); | |
| 70 | }); | |
| 71 | ||
| 72 | test("the duty posts one finding with a number, and is registered", async () => { | |
| 73 | expect(duties).toContain(duty); | |
| 74 | const r = await duty.run({ db: app.db, bus: app.bus, now: NOW, app }); | |
| 75 | expect(r.findings).toHaveLength(1); | |
| 76 | expect(r.findings[0]!.probe?.number).toBe(1); | |
| 77 | expect(r.actions).toEqual([]); | |
| 78 | }); | |
| 79 | ||
| 80 | test("only a forge admin deletes", async () => { | |
| 81 | const shown = (await mergedBranches(app, NOW)).map(lineOf); | |
| 82 | expect(await deleteMerged(app, person, shown, NOW)).toEqual({ ok: false, error: "forbidden" }); | |
| 83 | expect(await tip("old-merged")).toBeDefined(); | |
| 84 | }); | |
| 85 | ||
| 86 | test("Delete all removes what the card showed, receipts names and heads, and leaves the rest", async () => { | |
| 87 | const head = (await tip("old-merged"))!; | |
| 88 | const done = must(await deleteMerged(app, admin, [`${repo.ownerName}/r:old-merged@${head}`, `${repo.ownerName}/r:still-open@${"0".repeat(40)}`], NOW)); | |
| 89 | expect(done.says).toContain(`boss/r:old-merged@${head}`); | |
| 90 | expect(await tip("old-merged")).toBeUndefined(); | |
| 91 | for (const b of ["main", "still-open", "fresh-merged", "moved-on", "reused"]) expect(await tip(b)).toBeDefined(); | |
| 92 | expect(JSON.stringify(latest(app.db, 5))).toContain(head); | |
| 93 | expect(await deleteMerged(app, admin, [], NOW)).toEqual({ ok: false, error: "nothing" }); | |
| 94 | }); | |
| 95 | ||
| 96 | test("the scan is bounded: at most `cap` rows, and a branch already deleted costs no row", async () => { | |
| 97 | await pull("cap-a", 11); | |
| 98 | await pull("cap-b", 12); | |
| 99 | await pull("gone", 13); | |
| 100 | must(await deleteBranch(app, admin, repo, "gone")); | |
| 101 | const all = (await mergedBranches(app, NOW)).map((b) => b.branch); | |
| 102 | expect(all).toEqual(expect.arrayContaining(["cap-a", "cap-b"])); | |
| 103 | expect(all).not.toContain("gone"); | |
| 104 | expect(all.length).toBeGreaterThanOrEqual(2); | |
| 105 | expect(await mergedBranches(app, NOW, 7, 1)).toHaveLength(1); | |
| 106 | expect((await mergedBranches(app, NOW, 7, 1))[0]!.branch).toBe(all[0]!); | |
| 107 | }); |
test/maintain-merged-web.test.ts added +126
| @@ -0,0 +1,126 @@ | ||
| 1 | /** Merged branches (#13321): the card, its action's gates, and the terminal screen. */ | |
| 2 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 3 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { createBranch } from "../src/actions/branches.ts"; | |
| 7 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 8 | import { createApp, type App } from "../src/app.ts"; | |
| 9 | import { createRepo, type Repo } from "../src/core/repos.ts"; | |
| 10 | import { createUser, type User } from "../src/core/users.ts"; | |
| 11 | import { resolveOid } from "../src/git/merge.ts"; | |
| 12 | import { repoDir } from "../src/git/repos.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | import { id } from "../src/kernel/id.ts"; | |
| 15 | import { mergedBranches } from "../src/maintain/duties/merged_branches.ts"; | |
| 16 | import { deleteListed, mergedLines } from "../src/tui/screens/mergedbranches.ts"; | |
| 17 | import { Session } from "../src/tui/session.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | let dir = "", app: App, servers: Servers, admin: User, person: User, repo: Repo, seq = 0; | |
| 22 | let adminCookie = "", personCookie = "", agentCookie = ""; | |
| 23 | ||
| 24 | async function user(name: string, o: { isAdmin?: boolean; agent?: boolean } = {}): Promise<User> { | |
| 25 | const made = await createUser(app.db, { username: name, email: `${name}@forge.test`, password: "a-good-passphrase", origin: "seed", trusted: true, ...(o.isAdmin ? { isAdmin: true } : {}) }); | |
| 26 | if (!made.ok) throw new Error(name); | |
| 27 | if (o.agent) app.db.query("UPDATE user SET is_agent = 1 WHERE id = ?1").run(made.value.id); | |
| 28 | return made.value; | |
| 29 | } | |
| 30 | async function login(username: string): Promise<string> { | |
| 31 | const res = await fetch(`${servers.url}/signin`, { | |
| 32 | method: "POST", redirect: "manual", | |
| 33 | headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url }, | |
| 34 | body: new URLSearchParams({ username, password: "a-good-passphrase" }), | |
| 35 | }); | |
| 36 | return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? ""; | |
| 37 | } | |
| 38 | const tip = (b: string) => resolveOid(repoDir(app.reposRoot, repo.ownerName, repo.name), `refs/heads/${b}`); | |
| 39 | /** A branch whose pull merged ten days ago. */ | |
| 40 | async function mergedPull(branch: string): Promise<string> { | |
| 41 | const made = await createBranch(app, admin, repo, { name: branch }); | |
| 42 | if (!made.ok) throw new Error(branch); | |
| 43 | const head = (await tip(branch))!, issue = id(), at = new Date(Date.now() - 10 * 86_400_000).toISOString(); | |
| 44 | app.db.query("INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at, updated_at) VALUES (?1, ?2, ?3, 'pull', 'P', '', ?4, 'closed', ?5, ?5)").run(issue, repo.id, ++seq, admin.id, at); | |
| 45 | app.db.query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id, merged_at) VALUES (?1, 'main', ?2, ?3, ?3, ?4, ?5)").run(issue, branch, head, repo.id, at); | |
| 46 | return head; | |
| 47 | } | |
| 48 | const post = (cookie: string, body: string, origin = servers.url): Promise<Response> => | |
| 49 | fetch(`${servers.url}/maintenance/branches/delete`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", origin, cookie }, body }); | |
| 50 | const form = async (head: string, branch: string, confirm: boolean): Promise<string> => | |
| 51 | new URLSearchParams({ shown: `${repo.ownerName}/r:${branch}@${head}`, ...(confirm ? { confirm: "yes" } : {}) }).toString(); | |
| 52 | const flashed = async (res: Response): Promise<string> => { | |
| 53 | const cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? ""; | |
| 54 | return decodeURIComponent((await (await fetch(`${servers.url}/maintenance`, { headers: { cookie: `${adminCookie}; ${cookie}` } })).text())); | |
| 55 | }; | |
| 56 | ||
| 57 | beforeAll(async () => { | |
| 58 | dir = await mkdtemp(join(tmpdir(), "forge-merged-web-")); | |
| 59 | app = createApp({ dataDir: dir, port: 0 }); | |
| 60 | servers = await serve(app); | |
| 61 | admin = await user("boss", { isAdmin: true }); | |
| 62 | person = await user("pat"); | |
| 63 | await user("robo", { isAdmin: true, agent: true }); | |
| 64 | repo = await (async () => { | |
| 65 | const made = await createRepo(app.db, app.reposRoot, { ownerId: admin.id, name: "r", visibility: "public", description: "r" }); | |
| 66 | if (!made.ok) throw new Error("repo"); | |
| 67 | return made.value; | |
| 68 | })(); | |
| 69 | const seeded = await commitToBranch(app, admin, repo, { message: "seed", files: [{ path: "a.txt", content: "a\n" }] }); | |
| 70 | if (!seeded.ok) throw new Error("seed"); | |
| 71 | adminCookie = await login("boss"); | |
| 72 | personCookie = await login("pat"); | |
| 73 | agentCookie = await login("robo"); | |
| 74 | }); | |
| 75 | afterAll(async () => { | |
| 76 | servers.stop(); | |
| 77 | app.close(); | |
| 78 | await rm(dir, { recursive: true, force: true }); | |
| 79 | }); | |
| 80 | ||
| 81 | test("the card lists the rows and the form with the confirm box", async () => { | |
| 82 | const head = await mergedPull("card-one"); | |
| 83 | const page = await (await fetch(`${servers.url}/maintenance`, { headers: { cookie: adminCookie } })).text(); | |
| 84 | expect(page).toContain('id="merged-branches"'); | |
| 85 | expect(page).toContain(`data-branch="boss/r:card-one"`); | |
| 86 | expect(page).toContain(head.slice(0, 12)); | |
| 87 | expect(page).toContain('action="/maintenance/branches/delete"'); | |
| 88 | expect(page).toContain(`value="boss/r:card-one@${head}"`); | |
| 89 | expect(page).toMatch(/<input[^>]*name="confirm"[^>]*type="checkbox"|<input[^>]*type="checkbox"[^>]*name="confirm"/); | |
| 90 | }); | |
| 91 | ||
| 92 | test("a non-admin and an agent are refused, a cross-origin post is refused, and nothing is deleted", async () => { | |
| 93 | const head = await mergedPull("refused"); | |
| 94 | const body = await form(head, "refused", true); | |
| 95 | expect((await post(personCookie, body)).status).toBe(403); | |
| 96 | expect(await flashed(await post(agentCookie, body))).toContain("Only a forge admin may do this."); | |
| 97 | expect((await post(adminCookie, body, "https://evil.example")).status).toBe(403); | |
| 98 | expect(await tip("refused")).toBe(head); | |
| 99 | }); | |
| 100 | ||
| 101 | test("a post without confirm=yes deletes nothing", async () => { | |
| 102 | const head = await mergedPull("unconfirmed"); | |
| 103 | const res = await post(adminCookie, await form(head, "unconfirmed", false)); | |
| 104 | expect(await flashed(res)).toContain("Tick the box"); | |
| 105 | expect(await tip("unconfirmed")).toBe(head); | |
| 106 | }); | |
| 107 | ||
| 108 | test("an admin's confirmed post deletes and flashes the receipt with the full head", async () => { | |
| 109 | const head = await mergedPull("doomed"); | |
| 110 | const res = await post(adminCookie, await form(head, "doomed", true)); | |
| 111 | expect(res.status).toBe(303); | |
| 112 | expect(await flashed(res)).toContain(`boss/r:doomed@${head}`); | |
| 113 | expect(await tip("doomed")).toBeUndefined(); | |
| 114 | }); | |
| 115 | ||
| 116 | test("the terminal door lists the same rows, deletes them for an admin who is a person and gives anyone else nothing", async () => { | |
| 117 | const head = await mergedPull("tui-one"); | |
| 118 | const as = (u: User | undefined) => new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: u }); | |
| 119 | const boss = as({ ...admin, isAdmin: true, kind: "user" }); | |
| 120 | const found = (await mergedBranches(app, new Date())).filter((b) => b.branch === "tui-one"); | |
| 121 | expect(mergedLines(found).join("\n")).toContain(`boss/r:tui-one ${head.slice(0, 12)}`); | |
| 122 | for (const who of [as(person), as({ ...admin, isAdmin: true, kind: "agent" }), as(undefined)]) expect(await deleteListed(who, found)).toBe(""); | |
| 123 | expect(await tip("tui-one")).toBe(head); | |
| 124 | expect(await deleteListed(boss, found)).toContain(`boss/r:tui-one@${head}`); | |
| 125 | expect(await tip("tui-one")).toBeUndefined(); | |
| 126 | }); |
test/palette-roster.test.ts +1
| @@ -136,6 +136,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 136 | 136 | ["resilience", "Resilience", "where snapshots go and the mirror; each protection green, red or untested"], |
| 137 | 137 | ["maintenance", "Maintenance", "prepare the forge for a power-off, check the drain, or end maintenance"], |
| 138 | 138 | ["stale-pulls", "Pulls untouched for 14 days", "ask whether a stale pull is still wanted, or close one an agent opened"], |
| 139 | ["merged-branches", "Branches of pulls merged over 7 days ago", "delete the merged pulls' branches in one receipted step"], | |
| 139 | 140 | ["maintenance-runs", "Maintenance duty runs", "what each duty found, did and probed"], |
| 140 | 141 | ["maintenance-duties", "Pause or resume a maintenance duty", "switch a duty off, or on again after it paused itself"], |
| 141 | 142 | ["maintenance-budgets", "Set a maintenance duty's budget", "runs per day and dollars per day a duty may use"], |
new above
offline
Per-row ref read for every merged pull ever, most already deleted. Bound the scan and test the bound.