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

A maintenance duty names a pull open more than 7 days with no push, with the one action that moves it #15666

Merged opened this

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

Merged

torque/forge:torque/15643-a-maintenance-duty-names-a-pull-open-mor → main 0 commits fork 3 threads · 3 unresolved

  • Merged. torque/15643-a-maintenance-duty-names-a-pull-open-mor was merged into main as 279c488.

Review

Sign in to review this change.
4 files changed +148 −39
docs/features/maintain.md +1 −1
@@ -10,7 +10,7 @@ Every minute the runner (`src/maintain/runner.ts`, inside `during("maintain")`)
1010
1111 A finding must carry a probe: `{ kind: "query" | "measurement", what, number, at }`. A finding without one is refused: the run keeps no findings or actions and its outcome reads `refused: finding "…" has no probe`. A duty that throws reads `failed: <message>`.
1212
13 `GET /api/v1/maintenance/runs?limit=20` (forge admin, `ro` scope) lists the latest rows. The shipped duty, `pulls-waiting`, counts open pulls older than 24 hours.
13 `GET /api/v1/maintenance/runs?limit=20` (forge admin, `ro` scope) lists the latest rows. The `stale-pulls` duty names each open pull with no push, comment or review for 7 days and the one action that moves it (nudge the builder; close with a reason once an agent's pull is 14 days quiet). It reads only: acting stays an owner's tap. The owner's Nudge and Close receipts (`src/maintain/stale_pulls.ts`) are recorded under the same name, `stale-pulls`, so that duty's runs mix the duty's findings with those taps.
1414
1515 The terminal door is the palette entry "Maintenance duty runs" (`src/tui/screens/maintainruns.ts`): the same rows through the same read, offered only to a forge admin; anyone else is offered nothing and sees no rows.
1616
src/maintain/duties/stale_pulls.ts +38 −19
@@ -1,26 +1,45 @@
1 /** Example duty (#11204): how many open pulls have waited over 24 hours. Reads only. */
1 /**
2 * Stale pulls (#15643): open pulls with no push, comment or review for 7 days, each named with the
3 * one action that moves it. Reads only: the owner taps "Nudge" or "Close" on /maintenance (#12420);

STALE_DAYS as CLOSE_DAYS hides that the close threshold is the finder's 14. Name it once here and test the 13/14 boundary.

4 * this duty never comments on or closes a pull. The finder is `stalePulls` (a push to the head
5 * branch counts as a touch, so a pull pushed to inside the window is never named).
6 * The action: nudge the builder; once a pull an agent opened has been quiet for 14 days, close it
7 * with a reason. A person's pull is only ever nudged.
8 */
29
3 import type { Duty } from "../duty.ts";
10 import { stalePulls, type StalePull } from "../stale_pulls.ts";
11 import type { Duty, Finding } from "../duty.ts";
412

The 7 is hard-coded in this string; build it from QUIET_DAYS so the probe cannot drift from the window.

5 const DAY_MS = 24 * 3_600_000;
6 const SQL = "SELECT COUNT(*) AS n FROM issue WHERE kind = 'pull' AND state = 'open' AND parked = 0 AND created_at < ?1";
13 export const QUIET_DAYS = 7;
14 /**
15 * An agent's pull this quiet is closed, not nudged: the finder's own 14 days (#12420), named here
16 * once.
17 */
18 export const CLOSE_DAYS = 14;
19 /** The most pulls named in one run; the rest are counted. */
20 export const NAMED_CAP = 20;
21 const READ = `stalePulls(db, now, ${QUIET_DAYS}): open pulls whose issue.updated_at is older than ${QUIET_DAYS} days, with no push to the head branch inside ${QUIET_DAYS} days`;
22 const OVER = `quiet pulls beyond the ${NAMED_CAP} named, of those read by stalePulls(db, now, ${QUIET_DAYS})`;
23
24 /** The one action for a pull: nudge, or (an agent's pull, long quiet) close with a reason. */
25 export const actionFor = (p: StalePull): "nudge the builder" | "close with a reason" =>
26 p.byAgent && p.ageDays >= CLOSE_DAYS ? "close with a reason" : "nudge the builder";
27
28 const oneLine = (s: string): string => s.replace(/\s+/g, " ").replace(/[<>`]/g, "").slice(0, 80);
729
830 export const duty: Duty = {
9 name: "pulls-waiting",
10 intervalMs: 3_600_000,
11 budget: { runsPerDay: 30, dollarsPerDay: 1, reason: "hourly is 24 a day; the rest is room for a catch-up, and it spends no money" },
31 name: "stale-pulls",
32 intervalMs: 24 * 3_600_000,
33 budget: { runsPerDay: 3, dollarsPerDay: 1, reason: "once a day; the rest is room for a catch-up, and it spends no money" },
1234 run({ db, now }) {
13 const cutoff = new Date(now.getTime() - DAY_MS).toISOString();
14 const n = (db.query(SQL).get(cutoff) as { n: number }).n;
15 if (n === 0) return { findings: [], actions: [] };
16 return {
17 findings: [
18 {
19 summary: `${n} open pull${n === 1 ? "" : "s"} waiting over 24 hours`,
20 probe: { kind: "query", what: SQL.replace("?1", `'${cutoff}'`), number: n, at: now.toISOString() },
21 },
22 ],
23 actions: [],
24 };
35 const found = stalePulls(db, now, QUIET_DAYS);
36 const at = now.toISOString();
outdated

The overflow finding's probe number is the total, while the others carry age in days. Add a test for the cap (21+ pulls gives 20 named plus one 'N more' finding).

37 const findings: Finding[] = found.slice(0, NAMED_CAP).map((p) => ({
38 summary: `${p.repo}#${p.number} "${oneLine(p.title)}" quiet ${p.ageDays} days: ${actionFor(p)}`,
39 probe: { kind: "query", what: `${READ}; number is this pull's days quiet`, number: p.ageDays, at },
40 }));
41 if (found.length > NAMED_CAP)
42 findings.push({ summary: `${found.length - NAMED_CAP} more quiet pulls, oldest named above`, probe: { kind: "query", what: OVER, number: found.length - NAMED_CAP, at } });
43 return { findings, actions: [] };
2544 },
2645 };
test/duty-stale-pulls.test.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * The stale-pulls duty (#15643): names a pull quiet over 7 days with one action; a push inside 7
3 * days keeps it off.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRepo, type Repo } from "../src/core/repos.ts";
11 import { createUser, type User } from "../src/core/users.ts";
12 import { id } from "../src/kernel/id.ts";
13 import { CLOSE_DAYS, NAMED_CAP, duty } from "../src/maintain/duties/stale_pulls.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17 let dir = "", app: App, owner: User, agent: User, repo: Repo, seq = 0;
18 const NOW = new Date("2026-11-22T12:00:00Z");
19 const ago = (d: number): string => new Date(NOW.getTime() - d * 86_400_000).toISOString();
20
21 function pull(author: User, days: number, branch = `b/${++seq}`): number {
22 const n = ++seq;
23 const issue = id();
24 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, 'open', ?6, ?6)").run(issue, repo.id, n, `Pull ${n}`, author.id, ago(days));
25 app.db.query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id) VALUES (?1, 'main', ?2, ?3, ?3, ?4)").run(issue, branch, "0".repeat(40), repo.id);
26 return n;
27 }
28 const run = async () => await duty.run({ db: app.db, bus: app.bus, now: NOW });
29
30 beforeAll(async () => {
31 dir = await mkdtemp(join(tmpdir(), "forge-duty-stale-pulls-"));
32 app = createApp({ dataDir: dir, port: 0 });
33 const o = await createUser(app.db, { username: "boss", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, isAdmin: true });
34 const a = await createUser(app.db, { username: "builder", email: "[email protected]", agent: true, origin: "agent" });
35 if (!o.ok || !a.ok) throw new Error("users");
36 owner = o.value;
37 agent = a.value;
38 const made = await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "r", visibility: "public", description: "r" });
39 if (!made.ok) throw new Error("repo");
40 repo = made.value;
41 });
42 afterAll(async () => {
43 app.close();
44 await rm(dir, { recursive: true, force: true });
45 });
46
47 test("a pull quiet 8 days is named with nudge; 15 days from an agent says close", async () => {
48 const eight = pull(agent, 8);
49 const old = pull(agent, 15);
50 const res = await run();
51 const text = res.findings.map((f) => f.summary);
52 expect(text.find((t) => t.includes(`r#${eight} `))).toMatch(/quiet 8 days: nudge the builder/);
53 expect(text.find((t) => t.includes(`r#${old} `))).toMatch(/quiet 15 days: close with a reason/);
54 expect(res.findings.every((f) => f.probe?.kind === "query")).toBe(true);
55 expect(res.actions).toEqual([]);
56 });
57
58 test("a pull touched inside 7 days is never named", async () => {
59 const fresh = pull(agent, 3);
60 const res = await run();
61 expect(res.findings.some((f) => f.summary.includes(`r#${fresh} `))).toBe(false);
62 });
63
64 test("a pull with a push to its head branch inside 7 days is not named, though its row is old", async () => {
65 const n = pull(agent, 20, "pushed/branch");
66 app.db.query("INSERT INTO event (kind, repo_id, payload, created_at) VALUES ('push', ?1, ?2, ?3)").run(repo.id, JSON.stringify({ updates: [{ ref: "refs/heads/pushed/branch" }] }), ago(2));
67 const res = await run();
68 expect(res.findings.some((f) => f.summary.includes(`r#${n} `))).toBe(false);
69 });
70
71 test("a person's quiet pull is only ever nudged", async () => {
72 const n = pull(owner, 30);
73 const res = await run();
74 expect(res.findings.find((f) => f.summary.includes(`r#${n} `))!.summary).toMatch(/nudge the builder/);
75 });
76
77 test("the close threshold is 14 days: 13 nudges, 14 closes", async () => {
78 expect(CLOSE_DAYS).toBe(14);
79 const thirteen = pull(agent, 13);
80 const fourteen = pull(agent, 14);
81 const text = (await run()).findings.map((f) => f.summary);
82 expect(text.find((t) => t.includes(`r#${thirteen} `))).toMatch(/: nudge the builder$/);
83 expect(text.find((t) => t.includes(`r#${fourteen} `))).toMatch(/: close with a reason$/);
84 });
85
86 test("an old pull with a recent comment or review (updated_at inside 7 days) is not named", async () => {
87 const n = pull(agent, 40);
88 app.db.query("UPDATE issue SET updated_at = ?1 WHERE repo_id = ?2 AND number = ?3").run(ago(1), repo.id, n);
89 expect((await run()).findings.some((f) => f.summary.includes(`r#${n} `))).toBe(false);
90 });
91
92 test("at most 20 pulls are named, then one finding counts the rest", async () => {
93 app.db.exec("DELETE FROM pull; DELETE FROM issue");
94 for (let i = 0; i < NAMED_CAP + 3; i++) pull(agent, 8 + i);
95 const res = await run();
96 expect(res.findings.length).toBe(NAMED_CAP + 1);
97 const last = res.findings.at(-1)!;
98 expect(last.summary).toBe("3 more quiet pulls, oldest named above");
99 expect(last.probe!.number).toBe(3);
100 expect(res.findings.slice(0, NAMED_CAP).every((f) => /quiet \d+ days/.test(f.summary))).toBe(true);
101 // The oldest are the ones named: 8 + 22 = 30 days is first, the 8-day pull is in the overflow.
102 expect(res.findings[0]!.summary).toMatch(/quiet 30 days/);
103 expect(res.findings.some((f) => /quiet 8 days/.test(f.summary))).toBe(false);
104 });
test/maintain.test.ts +5 −19
@@ -100,29 +100,15 @@ test("a duty that throws is recorded as failed and the next still runs", async (
100100 expect(rows.find((r) => r.duty === "t-fine")!.outcome).toBe("ok");
101101 });
102102
103 test("the example duty is registered and counts open pulls waiting over 24 hours, with its probe", async () => {
103 test("the pulls duty is registered and a run with no quiet pull leaves an ok row with no findings", async () => {
104104 clear();
105 expect(duties.map((d) => d.name)).toContain("pulls-waiting");
106 const now = new Date("2026-11-11T12:00:00Z");
107 app.db.exec("PRAGMA foreign_keys = OFF");
108 const ins = app.db.prepare("INSERT INTO issue (id, repo_id, number, kind, title, author_id, state, created_at) VALUES (?1, 'r', ?2, 'pull', 't', 'u', ?3, ?4)");
109 ins.run("p1", 1, "open", "2026-11-09T00:00:00.000Z");
110 ins.run("p2", 2, "open", "2026-11-11T11:00:00.000Z");
111 ins.run("p3", 3, "closed", "2026-11-01T00:00:00.000Z");
112 const m = startMaintain(app, { duties: duties.filter((d) => d.name === "pulls-waiting"), everyMs: 1e9 });
105 expect(duties.map((d) => d.name)).toContain("stale-pulls");
106 const m = startMaintain(app, { duties: duties.filter((d) => d.name === "stale-pulls"), everyMs: 1e9 });
113107 m.stop();
114 await m.tick(now);
108 await m.tick(new Date("2026-11-11T12:00:00Z"));
115109 const [row] = latest(app.db, 1);
116110 expect(row!.outcome).toBe("ok");
117 expect(row!.findings).toEqual(["1 open pull waiting over 24 hours"]);
118 expect(row!.probes[0]).toMatchObject({ kind: "query", number: 1, at: now.toISOString() });
119 app.db.exec("DELETE FROM issue WHERE id IN ('p1','p2','p3')");
120 });
121
122 test("the example duty's count searches an existing index, not the table", () => {
123 const plan = (app.db.query("EXPLAIN QUERY PLAN SELECT COUNT(*) AS n FROM issue WHERE kind = 'pull' AND state = 'open' AND parked = 0 AND created_at < ?1").all("x") as { detail: string }[]).map((r) => r.detail).join("\n");
124 expect(plan).toMatch(/USING (COVERING )?INDEX/);
125 expect(plan).not.toMatch(/SCAN|TEMP B-TREE/);
111 expect(row!.findings).toEqual([]);
126112 });
127113
128114 test("GET /api/v1/maintenance/runs lists the latest rows for an admin only", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs