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

On /queue each aged item has one action: the oldest pull opens for review, the oldest unstarted issue can be deferred #15271

Merged opened this

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

Merged

scout/forge:scout/15262-on-queue-each-aged-item-has-one-action-t → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/15262-on-queue-each-aged-item-has-one-action-t was merged into main as a1ebd6e.

Review

Sign in to review this change.
8 files changed +311 −12
docs/features/queue-defer.md added +18
@@ -0,0 +1,18 @@
1 ---
2 topic: Tell the crew
3 row: Defer the oldest issue from the queue
4 ---
5 # Defer the oldest issue from the queue (#15262)
6
7 `/:owner/:name/queue` names the oldest open pull and the oldest issue no run has started on. The pull's row is a
8 link: it opens the pull. The issue's row has a **Defer** button beside it, which puts that issue behind the Later
9 gate (`deferOldest` in `src/actions/defer_aged.ts`, the move `rankIssue` makes for Not now). A row "Deferred #N"
10 then offers **Undo** for 60 seconds.
11
12 Only a person who administers the repository sees the buttons or may use them, and only the oldest issue can be
13 deferred: the form names it, and a stale one is refused. Undo brings the issue back out of the gate; it does not
14 restore the estimate Not now voided, so that estimate stays void. Each move writes an `issue.ranked` event.
15
16 In the terminal, open the repository's Queue (`src/tui/screens/queuegrowth.ts`): `d` defers the oldest issue and
17 `u` undoes it inside the minute, with the same gate. Over MCP, `next_up` with `issue` and `to: "not-now"` defers
18 any issue as before, and `to: "undo"` takes back your own deferral of the last minute.
src/actions/defer_aged.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * The queue's one action on its oldest unstarted issue (#15262): defer it behind the Later gate,
3 * and take that back inside a minute. The move is `rankIssue`'s `not_now`, the one door the Next
4 * page and MCP `next_up` use; this adds only who may (a person who administers the repository),
5 * which issue (the oldest unstarted one, as the page names it) and the undo. The receipt is the
6 * `issue.ranked` event the move writes; the undo writes its own beside it.
7 */
8 import type { App } from "../app.ts";
9 import type { Database } from "bun:sqlite";
10 import { removeDependency } from "../core/dependencies.ts";
11 import { oldest } from "../core/growth.ts";
12 import { getIssue, type Issue } from "../core/issues.ts";
13 import { pillarsOf } from "../core/pillars.ts";
14 import { canAdmin, type Repo } from "../core/repos.ts";
15 import { sealedScope } from "../core/sealed.ts";
16 import type { User } from "../core/users.ts";
17 import { err, ok, type Result } from "../kernel/result.ts";
18 import { rankIssue } from "./next.ts";
19
20 export const DEFER_UNDO_MS = 60_000;
21 export const DEFER_FORBIDDEN = "Only a person who administers this repository can defer from the queue.";
22 export const DEFER_NOT_OLDEST = "That is no longer the oldest issue no run has started on.";
23 export const DEFER_TOO_LATE = "The minute to undo has passed; Top on the Next page brings it back.";
24
25 export type DeferError = { kind: "not_found" | "forbidden" | "invalid"; message: string };
26
27 const admin = (app: App, actor: User, repo: Repo) => actor.kind !== "agent" && canAdmin(app.db, repo, actor);
28
29 /**
30 * Whether the repository has a Later gate to defer behind; without one the button is not offered.
31 */
32 export const hasGate = (db: Database, repo: Repo): boolean => pillarsOf(db, repo).gate !== undefined;
33
34 /** Defer `number`, which must be the queue's oldest unstarted issue. */
35 export function deferOldest(app: App, actor: User | undefined, repo: Repo, number: number): Result<Issue, DeferError> {
36 if (actor === undefined || !admin(app, actor, repo)) return err({ kind: "forbidden", message: DEFER_FORBIDDEN });
37 const aged = oldest(app.db, repo.id, sealedScope(app.db, repo, actor)).issue;
38 if (aged === null || aged.number !== number) return err({ kind: "invalid", message: DEFER_NOT_OLDEST });
39 const moved = rankIssue(app, actor, repo, number, { to: "not_now" });
40 return moved.ok ? moved : err(moved.error);
41 }
42
43 /** Whether `number` was deferred by `actor` inside the undo minute and not moved since. */
44 export function deferUndoable(db: Database, actor: User, repo: Repo, number: number, now = Date.now()): boolean {
45 const last = db
46 .query<{ actor_id: string | null; created_at: string; to: string | null }, [string, number]>(
47 `SELECT actor_id, created_at, json_extract(payload, '$.to') AS "to" FROM event
48 WHERE kind = 'issue.ranked' AND +repo_id = ?1 AND json_extract(payload, '$.number') = ?2
49 ORDER BY seq DESC LIMIT 1`,
50 )
51 .get(repo.id, number);
52 if (last === null || last.to !== "not_now" || last.actor_id !== actor.id) return false;
53 const age = now - Date.parse(last.created_at);
54 return age >= 0 && age < DEFER_UNDO_MS;
55 }
56
57 /** Take the deferral back: the issue leaves the Later gate. */
58 export function undoDefer(app: App, actor: User | undefined, repo: Repo, number: number, now = Date.now()): Result<Issue, DeferError> {
59 if (actor === undefined || !admin(app, actor, repo)) return err({ kind: "forbidden", message: DEFER_FORBIDDEN });
60 const issue = getIssue(app.db, repo.id, number);
61 if (issue === undefined || issue.kind !== "issue") return err({ kind: "not_found", message: "No such issue." });
62 const gate = pillarsOf(app.db, repo).gate;
63 if (gate === undefined || !deferUndoable(app.db, actor, repo, number, now))
64 return err({ kind: "invalid", message: DEFER_TOO_LATE });
65 removeDependency(app.db, issue.id, gate.id);
66 app.bus.append({ kind: "issue.ranked", repoId: repo.id, actorId: actor.id, payload: { number, to: "undo", from: 0 } });
67 return ok(issue);
68 }
69
70 /** The issue `actor` last deferred here, while its minute runs; null when there is none. */
71 export function recentDefer(db: Database, actor: User, repo: Repo, now = Date.now()): number | null {
72 const last = db
73 .query<{ n: number | null }, [string, string]>(
74 `SELECT json_extract(payload, '$.number') AS n FROM event
75 WHERE kind = 'issue.ranked' AND +repo_id = ?1 AND actor_id = ?2 ORDER BY seq DESC LIMIT 1`,
76 )
77 .get(repo.id, actor.id);
78 return last?.n != null && deferUndoable(db, actor, repo, last.n, now) ? last.n : null;
79 }
src/http/mcp/tools/next_up.ts +13 −7
@@ -1,3 +1,4 @@
1 import { undoDefer } from "../../../actions/defer_aged.ts";
12 import { placeOf, rankIssue } from "../../../actions/next.ts";
23 import { nextUp, TOP, type NextRow } from "../../../core/next_up.ts";
34 import { notStartable } from "../../../crew/not_startable.ts";
@@ -24,14 +25,14 @@ const brief = (r: NextRow, week?: WeekView, at = 0) => ({
2425
2526 export const tool: Tool = {
2627 name: "next_up",
27 doc: "an app's one ranked list, the crew builds strictly from the top (`app`; with `issue` and `to` — `top`, `not-now` or `after:<number>` — a writer moves that issue and it saves at once; `top` lifts a gated issue past the Later gate; `all` lists beyond the top ten; each row carries its cost `estimate` range and `thisWeek`, and `projection` is one sentence on what the week can ship)",
28 doc: "an app's one ranked list, the crew builds strictly from the top (`app`; with `issue` and `to` — `top`, `not-now` or `after:<number>` — a writer moves that issue and it saves at once; `top` lifts a gated issue past the Later gate; `undo` takes back your `not-now` of the last minute; `all` lists beyond the top ten; each row carries its cost `estimate` range and `thisWeek`, and `projection` is one sentence on what the week can ship)",
2829 description: "The ranked list the crew builds from; `issue` + `to` (top, not-now, after:N) moves one.",
2930 inputSchema: {
3031 type: "object",
3132 properties: {
3233 app: APP_ARG,
3334 issue: { type: "integer", minimum: 1 },
34 to: { type: "string", pattern: "^(top|not-now|after:[1-9][0-9]{0,8})$" },
35 to: { type: "string", pattern: "^(top|not-now|undo|after:[1-9]\\d{0,8})$" },
3536 all: { type: "boolean" },
3637 },
3738 required: ["app"],
@@ -44,11 +45,16 @@ export const tool: Tool = {
4445 if (args["issue"] !== undefined) {
4546 const issue = issueArg(ctx, repo, args, "issue");
4647 if ("ok" in issue) return issue;
47 const place = typeof args["to"] === "string" ? placeOf(args["to"]) : undefined;
48 if (place === undefined) return bad("invalid_to", "to is top, not-now or after:<number>");
49 const moved = rankIssue(ctx.app, user, repo, issue.number, place);
50 if (!moved.ok)
51 return bad(moved.error.kind === "not_found" ? "no_such_issue" : moved.error.kind, moved.error.message);
48 if (args["to"] === "undo") {
49 const back = undoDefer(ctx.app, user, repo, issue.number);
50 if (!back.ok) return bad(back.error.kind === "not_found" ? "no_such_issue" : back.error.kind, back.error.message);
51 } else {

Indent the else-block body; as written it is mis-formatted and reads as dead structure.

52 const place = typeof args["to"] === "string" ? placeOf(args["to"]) : undefined;
53 if (place === undefined) return bad("invalid_to", "to is top, not-now, undo or after:<number>");
54 const moved = rankIssue(ctx.app, user, repo, issue.number, place);
55 if (!moved.ok)
56 return bad(moved.error.kind === "not_found" ? "no_such_issue" : moved.error.kind, moved.error.message);
57 }
5258 }
5359 const scope = sealedScope(ctx.app.db, repo, user);
5460 const next = nextUp(ctx.app.db, repo, scope, (ready) => notStartable(ctx.app, repo, ready, scope));
src/http/server.ts +2 −1
@@ -208,7 +208,7 @@ import { auditCsv, auditPage, auditProbeSubmit } from "../web/pages/audit.ts";
208208 import { apiPage, appApiPage } from "../web/pages/api.ts";
209209 import { flowsCheck, flowsPage, flowsProbe, flowsUpdate } from "../web/pages/flows.ts";
210210 import { findingAccept, findingsPage } from "../web/pages/findings.ts";
211 import { queueCeiling, queuePage, queueSwitch } from "../web/pages/queue.ts";
211 import { queueCeiling, queueDefer, queuePage, queueSwitch } from "../web/pages/queue.ts";
212212 import { chapterAct, chapterPage, chaptersPage } from "../web/pages/chapters.ts";
213213 import { betAct, betPage, betPropose, betsPage } from "../web/pages/bets.ts";
214214 import { changelogJson, changelogPage } from "../web/pages/changelog.ts";
@@ -1502,6 +1502,7 @@ export function buildRouter(): Router<Handler> {
15021502 router.add("GET", "/:owner/:name/queue", queuePage);
15031503 router.add("POST", "/:owner/:name/queue/planner", queueSwitch);
15041504 router.add("POST", "/:owner/:name/queue/ceiling", queueCeiling);
1505 router.add("POST", "/:owner/:name/queue/defer", queueDefer);
15051506 router.add("GET", "/:owner/:name/chapters", chaptersPage);
15061507 router.add("POST", "/:owner/:name/chapters", chapterAct);
15071508 router.add("GET", "/:owner/:name/chapters/:chapter", chapterPage);
src/tui/screens/queuegrowth.ts +22 −2
@@ -5,8 +5,11 @@
55 * weekly reset, `t` until a time typed in UTC, `n` switches it on. Each goes through
66 * `setPlannerSwitch`, the page's one door, so a web viewer sees it at once. The open-issue ceiling
77 * (#12868) is the same: `c` sets it, `r` resumes the planner for one plan, through `setCeiling`.
8 * `d` defers the oldest unstarted issue behind the Later gate and `u` takes it back inside a
9 * minute (#15262), through `deferOldest` and `undoDefer`, the page's gate: administrators only.
810 */
911
12 import { DEFER_TOO_LATE, deferOldest, hasGate, recentDefer, undoDefer } from "../../actions/defer_aged.ts";
1013 import { setCeiling, setPlannerSwitch, SWITCH_REFUSED, switchInput, type SwitchInput } from "../../actions/planner_switch.ts";
1114 import { growth, oldest, WHO } from "../../core/growth.ts";
1215 import { ceilingHold, CEILING_REASON, openCeiling, PAUSE_STOPS, pauseSentence, pausedUntil } from "../../core/planner_pause.ts";
@@ -53,7 +56,8 @@ export function queueLines(f: Session, repo: Repo, now = new Date()): string[] {
5356 `Pulls opened ${sum((d) => d.pullsOpened)} · landed ${sum((d) => d.pullsLanded)} · closed unmerged ${sum((d) => d.pullsClosed)} · open now ${g.open.pulls}`,
5457 `Opened by ${WHO.map((w) => `${w} ${sum((d) => d.openedBy[w])}`).join(" · ")}`,
5558 ...(age.pull === null ? [] : [`Oldest open pull: #${age.pull.number} ${age.pull.title}`]),
56 ...(age.issue === null ? [] : [`Oldest issue not started: #${age.issue.number} ${age.issue.title}`]),
59 ...(age.issue === null ? [] : [`Oldest issue not started: #${age.issue.number} ${age.issue.title}${mayFlip(f, repo) && hasGate(f.db, repo) ? " (d defers it)" : ""}`]),
60 ...(f.user === undefined || !mayFlip(f, repo) || recentDefer(f.db, f.user, repo, now.getTime()) === null ? [] : [`Deferred #${recentDefer(f.db, f.user, repo, now.getTime())}: u undoes it within a minute; its estimate stays void.`]),
5761 "",
5862 ...[...g.days].reverse().map((d) => `${d.day} ${d.issuesOpened} opened · ${d.issuesClosed} closed`),
5963 ];
@@ -74,11 +78,25 @@ export function queueScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
7478 else ctx.toast(done.error === "invalid" ? "The ceiling is a whole number from 0 (off) to 100000." : "Only the owner sets the ceiling.", "danger");
7579 ctx.invalidate();
7680 };
81 const defer = (): void => {
82 const aged = oldest(f.db, current().id, sealedScope(f.db, current(), f.user)).issue;
83 if (aged === null) return ctx.toast("No issue waits to be started.", "danger");
84 const done = deferOldest(f.app, f.user, current(), aged.number);
85 ctx.toast(done.ok ? `#${aged.number} is behind the Later gate. Undo it for the next minute.` : done.error.message, done.ok ? "success" : "danger");
86 ctx.invalidate();
87 };
88 const undo = (): void => {
89 const n = f.user === undefined ? null : recentDefer(f.db, f.user, current());
90 if (n === null) return ctx.toast(DEFER_TOO_LATE, "danger");
91 const done = undoDefer(f.app, f.user, current(), n);
92 ctx.toast(done.ok ? `#${n} is back; its estimate stays void.` : done.error.message, done.ok ? "success" : "danger");
93 ctx.invalidate();
94 };
7795 const screen: Screen = {
7896 title: "Queue",
7997 get keys() {
8098 return mayFlip(f, current())
81 ? [binding(["o"], "pause until on"), binding(["w"], "pause to weekly reset"), binding(["h"], "pause until the chapter closes"), binding(["t"], "pause until a time"), binding(["n"], "switch on"), binding(["c"], "set the ceiling"), binding(["r"], "resume past the ceiling")]
99 ? [binding(["o"], "pause until on"), binding(["w"], "pause to weekly reset"), binding(["h"], "pause until the chapter closes"), binding(["t"], "pause until a time"), binding(["n"], "switch on"), binding(["c"], "set the ceiling"), binding(["r"], "resume past the ceiling"), binding(["d"], "defer the oldest issue"), binding(["u"], "undo the deferral")]
82100 : [];
83101 },
84102 render(area, s) {
@@ -93,6 +111,8 @@ export function queueScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
93111 if (e.key === "w") return flip({ mode: "week" }), true;
94112 if (e.key === "h") return flip({ mode: "chapter" }), true;
95113 if (e.key === "n") return flip({ mode: "on" }), true;
114 if (e.key === "d") return defer(), true;
115 if (e.key === "u") return undo(), true;
96116 if (e.key === "r") return ceil({ mode: "resume" }), true;
97117 if (e.key === "c") {
98118 ctx.push(
src/web/pages/queue.ts +25 −2
@@ -5,6 +5,7 @@
55 * issues) is left out of every number and title (`core/sealed.ts`).
66 */
77
8 import { deferOldest, hasGate, recentDefer, undoDefer } from "../../actions/defer_aged.ts";
89 import { setCeiling, setPlannerSwitch, SWITCH_REFUSED, switchInput } from "../../actions/planner_switch.ts";
910 import { growth, oldest, WHO, type Growth } from "../../core/growth.ts";
1011 import { ceilingHold, CEILING_HELD_NOTE, CEILING_REASON, openCeiling, PAUSE_STOPS, pauseSentence, pausedUntil } from "../../core/planner_pause.ts";
@@ -99,16 +100,21 @@ export function queuePage(ctx: Ctx): Response {
99100 const age = oldest(ctx.app.db, repo.id, scope);
100101 const until = pausedUntil(ctx.app.db, repo.id, now);
101102 const base = repoBase(repo);
103 const post = `${base}/queue/defer`;
104 const undoable = owner ? recentDefer(ctx.app.db, user, repo, now.getTime()) : null;
105 const form = (mode: string, n: number, label: string, variant?: "outline") =>
106 html`<form method="post" action="${post}" data-defer${mode === "undo" ? "-undo" : ""}><input type="hidden" name="mode" value="${mode}"><input type="hidden" name="number" value="${String(n)}">${btn(label, variant === undefined ? {} : { variant })}</form>`;
outdated

Principle 1: 'Open it for review' says again what the row link already says. Remove it.

102107 const aged = [
103108 age.pull === null ? null : row({ href: `${base}/pulls/${age.pull.number}`, nav: true, title: html`Oldest open pull: #${age.pull.number} ${age.pull.title}`, trail: badge(ago(age.pull.openedAt, now)) }),
104 age.issue === null ? null : row({ href: `${base}/issues/${age.issue.number}`, nav: true, title: html`Oldest issue not started: #${age.issue.number} ${age.issue.title}`, trail: badge(ago(age.issue.openedAt, now)) }),
109 age.issue === null ? null : row({ href: `${base}/issues/${age.issue.number}`, nav: true, title: html`Oldest issue not started: #${age.issue.number} ${age.issue.title}`, trail: badge(ago(age.issue.openedAt, now)), ...(owner && hasGate(ctx.app.db, repo) ? { after: form("defer", age.issue.number, "Defer") } : {}) }),
110 undoable === null ? null : row({ title: html`Deferred #${undoable}`, meta: html`Undo within a minute; its estimate stays void.`, after: form("undo", undoable, "Undo", "outline") }),
105111 ].filter((r): r is Html => r !== null);
106112 const body = html`${repoHeader(ctx, repo, "issues")}
107113 ${pageHead("Queue", { sub: "Is the work growing or shrinking?" })}
108114 ${switchRow(repo, until, owner)}
109115 ${ceilingRow(repo, openCeiling(ctx.app.db, repo.id), ceilingHold(ctx.app.db, repo.id), owner)}
110116 <p><a href="${base}/chapters">Chapters</a></p>
outdated

Principle 7: the action belongs in the row of the item it acts on (trail), not as a loose form below the list. Also shorten the label.

111 ${aged.length === 0 ? null : html`<ul class="list setting-list">${aged}</ul>`}
117 ${aged.length === 0 ? null : html`<ul class="list setting-list" data-aged>${aged}</ul>`}
112118 ${growthRows(g)}`;
113119 const response = page({ ctx, title: `Queue · ${repo.name}`, crumbs: crumbsFor(repo), palette: repoPalette(ctx, repo), body });
114120 notePhase(ctx.request, "render", performance.now() - rendering);
@@ -144,3 +150,20 @@ export async function queueCeiling(ctx: Ctx): Promise<Response> {
144150 return flashTo(ctx, back, { tone: "danger", message: done.error === "invalid" ? "The ceiling is a whole number from 0 (off) to 100000." : "Only the owner sets the ceiling." });
145151 return flashTo(ctx, back, { message: mode === "set" ? (done.value === 0 ? "Ceiling off." : `Ceiling set to ${done.value}.`) : "The planner may open one plan past the ceiling." });
146152 }
153
154 // POST /:owner/:name/queue/defer
155 export async function queueDefer(ctx: Ctx): Promise<Response> {
156 const repo = loadRepo(ctx);
157 if (!repo) return notFoundPage(ctx);
158 const form = await readForm(ctx, "rw");
159 if (form instanceof Response) return form;
160 const back = backTo(form, `${repoBase(repo)}/queue`);
161 const mode = formField(form, "mode");
162 const raw = formField(form, "number");
163 const number = /^[1-9][0-9]{0,8}$/.test(raw) ? Number(raw) : 0;
164 if ((mode !== "defer" && mode !== "undo") || number === 0)
165 return flashTo(ctx, back, { tone: "danger", message: "Say which issue to defer or bring back." });
166 const done = mode === "defer" ? deferOldest(ctx.app, ctx.auth.user, repo, number) : undoDefer(ctx.app, ctx.auth.user, repo, number);
167 if (!done.ok) return flashTo(ctx, back, { tone: "danger", message: done.error.message });
168 return flashTo(ctx, back, { message: mode === "defer" ? `#${number} is behind the Later gate. Undo it for the next minute.` : `#${number} is back; its estimate stays void.` });
169 }
test/queue-defer.test.ts added +127
@@ -0,0 +1,127 @@
1 /**
2 * The queue's one action per aged item (#15262): defer the oldest unstarted issue, undo inside a
3 * minute.
4 */
5 import { afterAll, beforeAll, describe, 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 { deferOldest, recentDefer, undoDefer } from "../src/actions/defer_aged.ts";
11 import { openIssue } from "../src/actions/issues.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { repoGraph } from "../src/core/dependencies.ts";
14 import { getIssue } from "../src/core/issues.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19
20 describe("defer from the queue", () => {
21 let dir: string;
22 let app: App;
23 let servers: Servers;
24 let alice: User;
25 let bob: User;
26 let repo: Repo;
27 let first = 0;
28 let second = 0;
29 const deferred = (n: number) => repoGraph(app.db, repo.id, { sealed: true, lean: true }).deferred.has(getIssue(app.db, repo.id, n)!.id);
30 const open = (title: string): number => {
31 const o = openIssue(app, alice, repo, { title });
32 return o.ok ? o.value.number : -1;
33 };
34 beforeAll(async () => {
35 dir = await mkdtemp(join(tmpdir(), "forge-defer-"));
36 app = createApp({ dataDir: dir, port: 0 });
37 servers = await serve(app);
38 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
39 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
40 if (!a.ok || !b.ok) throw new Error("users");
41 alice = a.value;
42 bob = b.value;
43 const r = await createRepo(app, alice, { name: "d", visibility: "public" });
44 if (!r.ok) throw new Error(String(r.error));
45 repo = r.value;
46 first = open("Oldest");
47 second = open("Younger");
48 open("Later gate: not yet");
49 });
50 afterAll(async () => { servers.stop(); app.close(); await rm(dir, { recursive: true, force: true }); });
51
52 test("the page shows the button to an administrator only; the POST is same-origin", async () => {
53 const tok = createToken(app.db, alice.id, "t", "rw").token;
54 const bobTok = createToken(app.db, bob.id, "t", "rw").token;
55 const get = async (t: string | null) =>
56 (await fetch(`${servers.url}/alice/d/queue`, { headers: t === null ? {} : { authorization: `Bearer ${t}` } })).text();
57 expect(await get(null)).not.toContain("data-defer");
58 expect(await get(bobTok)).not.toContain("data-defer");
59 const mine = await get(tok);
60 expect(mine).toContain("data-defer");
61 expect(mine).toContain(`value="${first}"`);
62 const post = (origin: string | null, t: string, body: string) =>
63 fetch(`${servers.url}/alice/d/queue/defer`, {
64 method: "POST", redirect: "manual",
65 headers: { authorization: `Bearer ${t}`, "content-type": "application/x-www-form-urlencoded", ...(origin === null ? {} : { origin }) },
66 body,
67 });
68 expect((await post("https://evil.example", tok, `mode=defer&number=${first}`)).status).toBe(403);
69 expect(deferred(first)).toBe(false);
outdated

This asserts only that the issue exists; it would pass if the cross-origin POST had deferred it. Assert it is not deferred.

70 expect(recentDefer(app.db, alice, repo)).toBeNull();
71 expect((await post(servers.url, bobTok, `mode=defer&number=${first}`)).status).toBeLessThan(400);
72 expect(deferred(first)).toBe(false); // bob's refusal moved nothing
73 expect((await post(servers.url, tok, `mode=defer&number=${first}`)).status).toBeLessThan(400);
outdated

Vacuous: recentDefer is per actor, so alice's is null even if bob's POST deferred it. Assert the issue is not in repoGraph(...).deferred after bob's POST.

74 expect(deferred(first)).toBe(true);
75 expect(recentDefer(app.db, alice, repo)).toBe(first);
76 const after = await get(tok);
77 expect(after).toContain("data-defer-undo");
78 expect(after).not.toContain("Open it for review");
79 expect((await post(servers.url, tok, `mode=undo&number=${first}`)).status).toBeLessThan(400);
80 expect(recentDefer(app.db, alice, repo)).toBeNull();
81 expect(deferred(first)).toBe(false);
82 });
83
84 test("MCP next_up takes the same action and its undo", async () => {
85 const tok = createToken(app.db, alice.id, "m", "rw").token;
86 const call = async (args: Record<string, unknown>) =>
87 (await (await fetch(`${servers.url}/mcp`, {
88 method: "POST",
89 headers: { authorization: `Bearer ${tok}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
90 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "next_up", arguments: { app: "alice/d", ...args } } }),
91 })).text());
92 await call({ issue: first, to: "not-now" });
93 expect(recentDefer(app.db, alice, repo)).toBe(first);
94 const bobCall = (args: Record<string, unknown>) =>
95 fetch(`${servers.url}/mcp`, {
96 method: "POST",
97 headers: { authorization: `Bearer ${createToken(app.db, bob.id, "m", "rw").token}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
98 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "next_up", arguments: { app: "alice/d", ...args } } }),
99 });
100 await bobCall({ issue: first, to: "undo" });
101 expect(deferred(first)).toBe(true); // a non-administrator's undo changed nothing
102 await call({ issue: first, to: "undo" });
103 expect(recentDefer(app.db, alice, repo)).toBeNull();
104 expect(deferred(first)).toBe(false);
105 });
106
107 test("only an administrator, and only the oldest", () => {
108 expect(deferOldest(app, bob, repo, first).ok).toBe(false);
109 expect(deferOldest(app, undefined, repo, first).ok).toBe(false);
110 const wrong = deferOldest(app, alice, repo, second);
111 expect(wrong.ok).toBe(false);
112 });
113
114 test("defers behind the gate, then undoes inside the minute and not after", () => {
115 const done = deferOldest(app, alice, repo, first);
116 expect(done.ok).toBe(true);
117 const issue = getIssue(app.db, repo.id, first)!;
118 expect(repoGraph(app.db, repo.id, { sealed: true, lean: true }).deferred.has(issue.id)).toBe(true);
119 expect(recentDefer(app.db, alice, repo)).toBe(first);
120 expect(recentDefer(app.db, bob, repo)).toBeNull();
121 expect(undoDefer(app, alice, repo, first, Date.now() + 61_000).ok).toBe(false);
122 expect(undoDefer(app, bob, repo, first).ok).toBe(false);
123 expect(undoDefer(app, alice, repo, first).ok).toBe(true);
124 expect(repoGraph(app.db, repo.id, { sealed: true, lean: true }).deferred.has(issue.id)).toBe(false);
125 expect(undoDefer(app, alice, repo, first).ok).toBe(false);
126 });
127 });
test/tui-queue.test.ts +25
@@ -7,6 +7,11 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
77 import { mkdtemp, rm } from "node:fs/promises";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
10 import { oldest } from "../src/core/growth.ts";
11 import { sealedScope } from "../src/core/sealed.ts";
12 import { openIssue } from "../src/actions/issues.ts";
13 import { repoGraph } from "../src/core/dependencies.ts";
14 import { getIssue } from "../src/core/issues.ts";
1015 import { createRepo } from "../src/actions/repos.ts";
1116 import { createApp, type App as Forge } from "../src/app.ts";
1217 import { pausedUntil } from "../src/core/planner_pause.ts";
@@ -116,4 +121,24 @@ describe("the queue in the terminal", () => {
116121 expect(queueLines(session(undefined), repo).join("\n")).not.toContain("secret hole in login");
117122 expect(queueLines(session(ada), repo).join("\n")).toContain("secret hole in login");
118123 });
124
125 test("d defers the oldest issue and u undoes it, for an administrator only", async () => {
126 openIssue(forge, ada, repo, { title: "Later gate: not yet" });
127 const aged = oldest(forge.db, repo.id, sealedScope(forge.db, repo, ada)).issue!;
128 const gated = () => repoGraph(forge.db, repo.id, { sealed: true, lean: true }).deferred.has(getIssue(forge.db, repo.id, aged.number)!.id);
129 const reader = boot(dave);
130 await reader.open();
131 await reader.press("d");
132 expect(gated()).toBe(false);
133 reader.stop();
134 const h = boot(ada);
135 await h.open();
136 expect(h.text()).toContain("d defers it");
137 await h.press("d");
138 expect(gated()).toBe(true);
139 expect(h.text()).toContain(`Deferred #${aged.number}`);
140 await h.press("u");
141 expect(gated()).toBe(false);
142 h.stop();
143 });
119144 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs