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

Cut a wave: an admin opens a draft waves/<next>.md as a pull listing every pull merged since the last wave #1558

Closed opened this
Closed without merging

scout/forge:scout/1508-cut-a-wave-an-admin-opens-a-draft-waves → main 5 commits fork 5 threads · 5 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +746 −1
README.md +16
@@ -703,6 +703,22 @@ Invariants are proven by faults, not by hope. No dependencies were added.
703703
704704 In the forge itself: a pull's check runs `fast` when the manifest has one, in a clone holding the fork point and the head as `FORGE_CHECK_BASE` and `HEAD` (`origin/main` is not a ref there), with `FORGE_CHECK_LEARNED` naming tests earlier land attempts taught the pull (`src/checks/history.ts`, `learned.ts`). Landing (`landIfGreen`) runs `full` once on the merge with its base before merging (`src/checks/landing.ts`); red comments on the pull with the tests named, is remembered per head and base, and the files ride the pull's next fast run. The pull page's checks line shows the tier words.
705705
706 ## Cut a wave
707
708 A repository admin opens **Settings → Cut a wave** to open a pull that adds
709 `waves/<next>.md` (format: `src/story/wave.ts`) listing every pull merged since
710 the last wave. The headline and highlights are `TODO` placeholders to write
711 before it lands. A wave that does not parse stops the cut and is named; no
712 merged pulls since the last wave is refused.
713
714 The same cut is in the terminal (`R` in a repository's workspace, then confirm)
715 and over MCP (`cut_wave` with `repo: "owner/name"`; it returns the pull's
716 number, or the refusal in words). All three are admin-only. A branch
717 `wave-<version>` is replaced only when it is a previous cut left by a closed,
718 unmerged wave pull and still at its `Cut wave <version>` commit; any other
719 branch of that name is kept and the cut is refused. One cut runs per
720 repository at a time.
721
706722 ## Limits
707723
708724 Every limit the owner can hit is declared in `src/settings/limits.ts` with its default, bounds and reason, and changed live by a forge admin at `/admin/limits`, `PUT /api/v1/admin/limits/:key` or the `limits` MCP tool (never by an agent). Each change is kept with who made it.
scripts/gate.ts +1
@@ -62,6 +62,7 @@ export const GATE: readonly string[] = [
6262 "test/review-from-green.test.ts",
6363 "test/themes.test.ts",
6464 "test/waves.test.ts",
65 "test/wave-cut.test.ts",
6566 "test/crew-wrapup.test.ts",
6667 "test/crew-limits.test.ts",
6768 "test/crew-parks.test.ts",
src/actions/wave.ts added +129
@@ -0,0 +1,129 @@
1 /**
2 * Cut a wave: open a pull that adds `waves/<next>.md`, listing every pull
3 * merged since the last wave. Admin only; the file is made by
4 * `story/cut.ts` and committed on a fresh branch, never on the default one.
5 */
6
7 import type { App } from "../app.ts";
8 import { listOpenPullsFromHead, mergedPulls, pullForBranch } from "../core/pulls.ts";
9 import type { Repo } from "../core/repos.ts";
10 import type { User } from "../core/users.ts";
11 import { commitLog, readerFor, listPaths } from "../git/read.ts";
12 import { resolveOid } from "../git/merge.ts";
13 import { repoDir } from "../git/repos.ts";
14 import { err, ok, type Result } from "../kernel/result.ts";
15 import { cutWave, WAVE_BRANCH, type CutError, type WaveFile } from "../story/cut.ts";
16 import { requireRepoAdmin } from "./access.ts";
17 import { deleteBranch } from "./branches.ts";
18 import { editFiles } from "./contents.ts";
19
20 export type CutWaveError =
21 | "not_found"
22 | CutError
23 | { kind: "branch_exists"; branch: string }
24 | { kind: "failed"; reason: string };
25
26 /** The plain reason a cut was refused, for every door. */
27 export function cutWords(e: CutWaveError): string {
28 if (typeof e === "string") return "That is not yours to do.";
29 switch (e.kind) {
30 case "malformed":
outdated

No caller passes version; nothing reaches it from the page. Drop it, or wire it into the MCP and terminal doors so it is used and tested.

31 return `${e.path} does not parse (${e.reason}); fix it first. Nothing was written.`;
32 case "nothing_new":
33 return "No pull has merged since the last wave, so there is nothing to cut.";
34 case "exists":
35 return `${e.path} already exists.`;
36 case "already_open":
37 return `Wave ${e.version} is already open as #${e.number}.`;
38 case "bad_version":
39 return `“${e.version}” is not a version.`;
40 case "branch_exists":
41 return `branch ${e.branch} exists and is not a previous wave cut; nothing was changed.`;
42 case "failed":
43 return `The pull could not be opened (${e.reason}).`;
44 }
45 }
46
47 /** Repositories mid-cut: a second cut at the same moment is refused, not raced. */
48 const cutting = new Set<string>();
49
50 const WAVE_FILE = /^waves\/[^/]+\.md$/;
51
52 export async function cutWaveFor(
53 app: App,
54 actor: User | undefined,
55 repo: Repo,
56 ): Promise<Result<{ number: number; version: string; pulls: number }, CutWaveError>> {
57 const admin = requireRepoAdmin(app, actor, repo);
58 if (!admin.ok) return admin;
59 if (cutting.has(repo.id)) return err({ kind: "failed", reason: "a cut is already running" });
60 cutting.add(repo.id);
61 try {
62 return await cut(app, admin.value, repo);
outdated

High: this deletes whatever wave-<v> holds, and nothing checks that it was a wave cut. A person's branch with that name, or a closed pull's unmerged work, is lost. Replace it only when it is provably a previous cut's branch. Otherwise refuse and name the branch.

63 } finally {
64 cutting.delete(repo.id);
65 }
66 }
67
68 /** Whether `branch` is provably an earlier cut of `version`, left by a closed wave pull. */
69 async function isOldCut(app: App, repo: Repo, dir: string, branch: string, version: string): Promise<boolean> {
70 const last = pullForBranch(app.db, repo.id, branch);
71 if (!last || last.state !== "closed" || last.mergedAt !== null || last.title !== `Wave ${version}`)
72 return false;
73 const tip = await commitLog(dir, `refs/heads/${branch}`, { limit: 1 });
74 return tip.ok && tip.value[0]?.subject === `Cut wave ${version}`;
75 }
76
77 async function cut(
78 app: App,
79 admin: User,
80 repo: Repo,
81 ): Promise<Result<{ number: number; version: string; pulls: number }, CutWaveError>> {
82 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
83 const tip = `refs/heads/${repo.defaultBranch}`;
84 const listed = await listPaths(dir, tip);
85 const files: WaveFile[] = [];
86 for (const path of listed.ok ? listed.value.paths.filter((p) => WAVE_FILE.test(p)) : []) {
87 const blob = await readerFor(dir).object(`${tip}:${path}`);
88 files.push({
89 path,
90 text: blob.ok ? new TextDecoder().decode(blob.value.body) : "",
91 });
92 }
93 const base = app.config.url ?? `http://localhost:${app.config.port}`;
94 // Every merged pull; `cutWave` keeps those since the last wave's day and
95 // drops what a wave already lists and the wave pulls themselves.
96 const merged = mergedPulls(app.db, repo.id).map((p) => ({
97 headBranch: p.headBranch,
98 number: p.number,
99 title: p.title,
100 url: new URL(`/${repo.ownerName}/${repo.name}/pulls/${p.number}`, base).toString(),
101 mergedAt: p.mergedAt ?? "",
102 }));
103 const cut = cutWave(files, merged, new Date().toISOString().slice(0, 10));
104 if (!cut.ok) return cut;
105 const { path, text, version: v, pulls } = cut.value;
106 const branch = `${WAVE_BRANCH}${v}`;
107 // One open wave pull per version; only a branch a closed wave pull left is replaced.
108 const open = listOpenPullsFromHead(app.db, repo.id, branch)[0];
109 if (open) return err({ kind: "already_open", version: v, number: open.number });
110 if ((await resolveOid(dir, `refs/heads/${branch}`)) !== undefined) {
111 if (!(await isOldCut(app, repo, dir, branch, v))) return err({ kind: "branch_exists", branch });
112 await deleteBranch(app, admin, repo, branch);

Low: the result of deleteBranch is thrown away. If the delete fails (for example an origin push refusal on a mirrored repository), editFiles then fails with a vaguer reason. Return {kind:"failed", reason} from the delete's error so the refusal says why.

113 }
114 const edit = await editFiles(app, admin, repo, {
115 newBranch: branch,
116 message: `Cut wave ${v}`,
117 files: [{ path, content: text }],
118 openPull: {
119 title: `Wave ${v}`,
120 body: `Lists ${pulls} merged pull${pulls === 1 ? "" : "s"}. The headline and highlights are placeholders: write them before this lands.`,
121 },
122 });
123 if (!edit.ok || !edit.value.pull)
124 return err({
125 kind: "failed",
126 reason: edit.ok ? "no pull opened" : typeof edit.error === "string" ? edit.error : edit.error.kind,
127 });
128 return ok({ number: edit.value.pull.number, version: v, pulls });
129 }
src/core/pulls.ts +26
@@ -911,3 +911,29 @@ export function landingTrailers(
911911 line("Co-authored-by", lander),
912912 ].join("\n");
913913 }
914
915 /**
916 * Every pull of a repository that has merged, oldest merge first. Capped at
917 * the newest `cap`, so a busy repository cannot mean an unbounded page.
918 * Which of them a wave lists is `story/cut.ts`'s call, not this query's.
919 */
920 export function mergedPulls(
921 db: Database,
922 repoId: string,
923 cap = 2_000,
924 ): Pull[] {
925 const ids = db
926 .query<{ issue_id: string }, [string, number]>(
927 `SELECT pull.issue_id FROM pull JOIN issue ON issue.id = pull.issue_id
928 WHERE issue.repo_id = ?1 AND pull.merged_at IS NOT NULL
929 ORDER BY pull.merged_at DESC LIMIT ?2`,
930 )
931 .all(repoId, cap)
932 .map((r) => r.issue_id)
933 .reverse();
934 const issues = getIssuesByIds(db, ids);
935 return joinMany(
936 db,
937 ids.map((id) => issues.get(id)).filter((i): i is Issue => i !== undefined),
938 );
939 }
src/http/mcp.ts +24
@@ -35,6 +35,7 @@ import {
3535 unlinkIssue,
3636 } from "../actions/dependencies.ts";
3737 import { holdPull, releasePull } from "../actions/holds.ts";
38 import { cutWaveFor, cutWords } from "../actions/wave.ts";
3839 import { openPlan, parsePlan, PLAN_MAX } from "../actions/plan.ts";
3940 import { cancelRepoRun } from "../actions/runs.ts";
4041 import { clientRows } from "../spawn/clients.ts";
@@ -448,6 +449,29 @@ const TOOLS: readonly Tool[] = [
448449 });
449450 },
450451 },
452 {
453 name: "cut_wave",
454 description:
455 "Cut a wave: open a pull that adds waves/<next>.md, listing every pull merged since the last wave. For an admin of the repository; anyone else is refused. Refused with the reason when nothing merged since the last wave, a wave file does not parse, or a wave pull is already open. Returns the new pull's number.",
456 inputSchema: {
457 type: "object",
458 properties: { repo: REPO_ARG },
459 required: ["repo"],
460 },
461 writes: true,
462 async run(ctx, user, args) {
463 const repo = repoArg(ctx, user, args);
464 if (isAnswer(repo)) return repo;
465 const cut = await cutWaveFor(ctx.app, user, repo);
466 if (!cut.ok) return bad("refused", cutWords(cut.error));
467 return good({
468 says: `Opened wave ${cut.value.version} as #${cut.value.number} with ${cut.value.pulls} pull${cut.value.pulls === 1 ? "" : "s"}.`,
469 number: cut.value.number,
470 version: cut.value.version,
471 pulls: cut.value.pulls,
472 });
473 },
474 },
451475 {
452476 name: "edit",
453477 description:
src/http/server.ts +2
@@ -301,6 +301,7 @@ import {
301301 repoDelete,
302302 settingsPage,
303303 settingsUpdate,
304 waveCut,
304305 webhookCreate,
305306 webhookDelete,
306307 } from "../web/pages/settings.ts";
@@ -1069,6 +1070,7 @@ export function buildRouter(): Router<Handler> {
10691070 // Settings (owner-gated inside the handlers).
10701071 router.add("GET", "/:owner/:name/settings", settingsPage);
10711072 router.add("POST", "/:owner/:name/settings", settingsUpdate);
1073 router.add("POST", "/:owner/:name/settings/wave", waveCut);
10721074 router.add("GET", "/:owner/:name/settings/app", appSettingsPage);
10731075 router.add("POST", "/:owner/:name/settings/app", appSettingsUpdate);
10741076 router.add("POST", "/:owner/:name/settings/app/disable", appDisable);
src/story/cut.ts added +122
@@ -0,0 +1,122 @@
1 /**
2 * Cutting a wave: from the waves already written and the pulls merged, the
3 * text of the next `waves/<version>.md`. Pure — files and pulls in, one
4 * file out. The headline and highlights are marked placeholders; a person
5 * or the crew writes the words before the pull lands.
6 */
7
8 import {
9 MIN_HIGHLIGHTS,
10 parseWave,
11 wavePath,
12 writeWave,
13 type Wave,
14 type WavePull,
15 } from "./wave.ts";
16
17 export interface WaveFile {
18 path: string;
19 text: string;
20 }
21 export interface MergedPull {
22 number: number;
23 title: string;
24 url: string;
25 /** ISO instant the pull merged. */
26 mergedAt: string;
27 /** The branch it merged from; a wave's own pull comes from `wave-*`. */
28 headBranch: string;
29 }
30 export interface Cut {
31 path: string;
32 text: string;
33 version: string;
34 pulls: number;
35 }
36 export type CutError =
37 | { kind: "malformed"; path: string; reason: string }
38 | { kind: "nothing_new" }
39 | { kind: "bad_version"; version: string }
40 | { kind: "exists"; path: string }
41 | { kind: "already_open"; version: string; number: number };
42
43 export const PLACEHOLDER = "TODO";
44
45 /** The branch prefix a cut opens its pull from. */
46 export const WAVE_BRANCH = "wave-";
47
48 const num = (v: string): number[] =>
49 v.split("-")[0]!.split(".").map(Number);
50 const newer = (a: string, b: string): boolean => {
51 const x = num(a);
52 const y = num(b);
53 for (let i = 0; i < 3; i++) if (x[i]! !== y[i]!) return x[i]! > y[i]!;
54 return false;
55 };
56
57 /** The next patch version after `v`, or 0.1.0 when there is no wave yet. */
58 export const nextVersion = (v: string | undefined): string => {
59 if (v === undefined) return "0.1.0";
60 const [a, b, c] = num(v);
61 return `${a}.${b}.${c! + 1}`;
62 };
63
64 /** One pull as a wave line: no brackets, one line. */
65 const line = (p: MergedPull): WavePull => ({
66 title: `#${p.number} ${p.title.replace(/[\[\]]/g, "").replace(/\s+/g, " ").trim()}`.trimEnd(),
67 url: p.url,
68 });
69
70 export function cutWave(
71 files: readonly WaveFile[],
72 merged: readonly MergedPull[],
73 today: string,
74 version?: string,
75 ): { ok: true; value: Cut } | { ok: false; error: CutError } {
76 const waves: Wave[] = [];
77 for (const f of files) {
78 const r = parseWave(f.path, f.text);
79 if (!r.ok)
80 return {
81 ok: false,
82 error: {
83 kind: "malformed",
84 path: f.path,
85 reason: r.error.message.slice(f.path.length + 2),
86 },
87 };
88 waves.push(r.value);
89 }
90 let last: Wave | undefined;
91 let top: string | undefined;
92 for (const w of waves) {
93 if (!last || w.date > last.date) last = w;
94 if (top === undefined || newer(w.version, top)) top = w.version;
95 }
96 const listed = new Set(waves.flatMap((w) => w.pulls.map((p) => p.url)));
97 const fresh = merged.filter(
98 (p) =>
99 !listed.has(p.url) &&
100 !p.headBranch.startsWith(WAVE_BRANCH) &&
101 (last === undefined || p.mergedAt.slice(0, 10) >= last.date),
102 );
103 if (fresh.length === 0) return { ok: false, error: { kind: "nothing_new" } };
104
105 const v = version ?? nextVersion(top);
106 const path = wavePath(v);
107 if (waves.some((w) => w.version === v) || files.some((f) => f.path === path))
108 return { ok: false, error: { kind: "exists", path } };
109 const wave: Wave = {
110 version: v,
111 date: today,
112 headline: `${PLACEHOLDER}: write the headline`,
113 highlights: Array.from({ length: MIN_HIGHLIGHTS }, (_, i) => ({
114 title: `${PLACEHOLDER}: highlight ${i + 1}`,
115 why: `${PLACEHOLDER}: why it matters`,
116 })),
117 pulls: fresh.map(line),
118 };
119 const text = writeWave(wave);
120 if (!text.ok) return { ok: false, error: { kind: "bad_version", version: v } };
121 return { ok: true, value: { path, text: text.value, version: v, pulls: fresh.length } };
122 }
src/tui/screens/workspace.ts +31
@@ -38,6 +38,7 @@ import { editFiles } from "../../actions/contents.ts";
3838 import { err, ok } from "../../kernel/result.ts";
3939 import { createBranch } from "../../actions/branches.ts";
4040 import { pinRepo, syncRepoNow, unpinRepo } from "../../actions/origins.ts";
41 import { cutWaveFor, cutWords } from "../../actions/wave.ts";
4142 import { isPinned } from "../../core/pins.ts";
4243 import { canAdmin, type Repo } from "../../core/repos.ts";
4344 import type { TreeEntry } from "../../git/read.ts";
@@ -1309,6 +1310,7 @@ export function workspaceScreen(
13091310 binding(["S"], "sync now", {
13101311 disabled: repo.origin === null || !admin(),
13111312 }),
1313 binding(["R"], "cut a wave", { disabled: !admin() }),
13121314 binding([","], "settings", { disabled: !admin() }),
13131315 ]),
13141316 binding(["r"], "refresh"),
@@ -1647,6 +1649,35 @@ export function workspaceScreen(
16471649 });
16481650 return true;
16491651 }
1652 if (plain && e.key === "R" && repo !== undefined && admin()) {
1653 ctx.push(
1654 confirmScreen(ctx, screen, {
1655 title: "Cut a wave",
1656 body: [
1657 "Open a pull that adds waves/<next>.md,",
1658 "listing every pull merged since the last wave.",
1659 ],
1660 actions: [
1661 { label: "Cancel", variant: "ghost" },
1662 { label: "Cut", variant: "default" },
1663 ],
1664 selected: 0,
1665 onChoose: (index) => {
1666 if (index !== 1) return;
1667 runAsync(ctx, async () => {
1668 const cut = await cutWaveFor(f.app, f.user, repo);
1669 if (!cut.ok) ctx.toast(cutWords(cut.error), "danger");
1670 else
1671 ctx.toast(
1672 `opened wave ${cut.value.version} as #${cut.value.number}`,
1673 "success",
1674 );
1675 });
1676 },
1677 }),
1678 );
1679 return true;
1680 }
16501681 if (plain && e.key === "F" && f.signedIn) {
16511682 // A repository that lives at an origin is forked *there* — a local
16521683 // fork of a mirror would be a copy of a copy, with nowhere to
src/web/pages/settings.ts +35 −1
@@ -37,6 +37,7 @@ import {
3737 type AppEnvName,
3838 type AppEnvScope,
3939 } from "../../core/app_env.ts";
40 import { cutWaveFor, cutWords } from "../../actions/wave.ts";
4041 import { addToCrew, listCrew, removeFromCrew } from "../../actions/crew.ts";
4142 import { getAgentByName, isCrewRole, setCrewRole } from "../../core/agents.ts";
4243 import { isAutonomy } from "../../core/repos.ts";
@@ -307,13 +308,24 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
307308 </form>`,
308309 { head: html`${icon("branch")}<h2>Branch and gates</h2>` },
309310 );
311 const wave = card(
312 html`<form method="post" action="${base}/settings/wave">
313 <p class="muted">
314 Opens a pull that adds <code>waves/&lt;next&gt;.md</code>, listing every
315 pull merged since the last wave. The headline and highlights are left
316 as placeholders for you to write.
317 </p>
318 <div class="form-actions">${btn("Cut a wave", { variant: "primary" })}</div>
319 </form>`,
320 { head: html`${icon("tag")}<h2>Cut a wave</h2>` },
321 );
310322 const secrets = secretsSection(ctx, "repo", `${repo.ownerName}/${repo.name}`);
311323 return settingsPageResponse(
312324 ctx,
313325 repo,
314326 "general",
315327 "Settings",
316 html`${lead}<div class="mt">${body}</div>${secrets
328 html`${lead}<div class="mt">${body}</div><div class="mt">${wave}</div>${secrets
317329 ? html`<div class="mt">${secrets}</div>`
318330 : null}`,
319331 );
@@ -1782,3 +1794,25 @@ export async function autonomySettingsUpdate(ctx: Ctx): Promise<Response> {
17821794 }),
17831795 });
17841796 }
1797
1798 /** POST /:owner/:name/settings/wave — open the pull that adds the next wave. */
1799 export async function waveCut(ctx: Ctx): Promise<Response> {
1800 const gate = await adminForm(ctx);
1801 if (gate instanceof Response) return gate;
1802 const { repo } = gate;
1803 const base = repoBase(repo);
1804 const cut = await cutWaveFor(ctx.app, ctx.auth.user, repo);
1805 if (!cut.ok) {
1806 const e = cut.error;
1807 return flashTo(
1808 ctx,
1809 typeof e === "object" && e.kind === "already_open"
1810 ? `${base}/pulls/${e.number}`
1811 : `${base}/settings`,
1812 { tone: "danger", message: cutWords(e) },
1813 );
1814 }
1815 return flashTo(ctx, `${base}/pulls/${cut.value.number}`, {
1816 message: `Opened wave ${cut.value.version} with ${cut.value.pulls} pull${cut.value.pulls === 1 ? "" : "s"}. Write the headline and highlights, then ship it.`,
1817 });
1818 }
test/mcp.test.ts +28
@@ -17,6 +17,8 @@ import { getRepoById, type Repo } from "../src/core/repos.ts";
1717 import { createRun, listRuns } from "../src/core/runs.ts";
1818 import { createToken } from "../src/core/tokens.ts";
1919 import { createUser, type User } from "../src/core/users.ts";
20 import { mergePull, openPull } from "../src/actions/pulls.ts";
21 import { getPull } from "../src/core/pulls.ts";
2022 import { serve, type Servers } from "../src/http/server.ts";
2123 import { limitChanges, limitValue } from "../src/settings/limits.ts";
2224
@@ -162,6 +164,7 @@ describe("the forge over MCP", () => {
162164 "share",
163165 "say",
164166 "pull",
167 "cut_wave",
165168 "edit",
166169 "asks",
167170 "asks_act",
@@ -676,4 +679,29 @@ describe("the forge over MCP", () => {
676679 expect(doc.openapi).toBe("3.1.0");
677680 expect(doc.paths["/mcp"].post).toBeDefined();
678681 });
682
683 test("cut_wave: an admin opens the wave pull, anyone else is refused", async () => {
684 const none = await tool(rw, "cut_wave", { repo: "alice/game" });
685 expect(none.error).toContain("nothing to cut");
686 await commitToBranch(app, alice, game, {
687 branch: "shipped",
688 base: "main",
689 message: "shipped",
690 files: [{ path: "s.txt", content: "s" }],
691 });
692 const opened = await openPull(app, alice, game, {
693 title: "Shipped",
694 baseBranch: "main",
695 headBranch: "shipped",
696 });
697 if (!opened.ok) throw new Error("pull failed");
698 const merged = await mergePull(app, alice, game, opened.value, "squash");
699 if (!merged.ok) throw new Error("merge failed");
700 expect((await tool(bobRw, "cut_wave", { repo: "alice/game" })).error).toBeDefined();
701 expect((await tool(ro, "cut_wave", { repo: "alice/game" })).error).toBeDefined();
702 const cut = await tool(rw, "cut_wave", { repo: "alice/game" });
703 expect(cut.value.version).toBe("0.1.0");
704 expect(cut.value.pulls).toBe(1);
705 expect(getPull(app.db, game.id, cut.value.number)?.title).toBe("Wave 0.1.0");
706 });
679707 });
test/tui-workspace.test.ts +68
@@ -23,6 +23,7 @@ import { signUp } from "../src/actions/users.ts";
2323 import { createApp, type App as Forge } from "../src/app.ts";
2424 import { getRepo, type Repo } from "../src/core/repos.ts";
2525 import { listPulls } from "../src/core/pulls.ts";
26 import { mergePull, openPull } from "../src/actions/pulls.ts";
2627 import type { User } from "../src/core/users.ts";
2728 import { blobForRender } from "../src/git/read.ts";
2829 import { listBranches } from "../src/git/branches.ts";
@@ -790,6 +791,73 @@ describe("the terminal workspace", () => {
790791 });
791792 });
792793
794 describe("cut a wave in the terminal", () => {
795 test("an admin's G opens the wave pull; a non-admin's G opens nothing", async () => {

Nit: this test name still says G, but the key is R (the pull moved off G because G already scrolls a file). Rename it so a failure points at the right key.

796 const dataDir = await mkdtemp(join(tmpdir(), "forge-tui-wave-"));
797 const forge = createApp({ dataDir, port: 0 });
798 try {
799 const mk = async (username: string): Promise<User> => {
800 const r = await signUp(forge, {
801 username,
802 email: `${username}@forge.test`,
803 password: "a-long-passphrase",
804 });
805 if (!r.ok) throw new Error("signup failed");
806 return r.value;
807 };
808 const alice = await mk("alice");
809 const bob = await mk("bob");
810 const made = await createRepo(forge, alice, { name: "lamp", visibility: "public" });
811 if (!made.ok) throw new Error("repo failed");
812 const repo = made.value;
813 await commitToBranch(forge, alice, repo, { message: "seed", files: [{ path: "a.txt", content: "a" }] });
814 await commitToBranch(forge, alice, repo, {
815 branch: "one",
816 base: "main",
817 message: "one",
818 files: [{ path: "one.txt", content: "1" }],
819 });
820 const opened = await openPull(forge, alice, repo, { title: "One", baseBranch: "main", headBranch: "one" });
821 if (!opened.ok) throw new Error("pull failed");
822 const merged = await mergePull(forge, alice, repo, opened.value, "squash");
823 if (!merged.ok) throw new Error("merge failed");
824 const waves = (): number =>
825 forge.db
826 .query<{ n: number }, [string]>("SELECT count(*) n FROM issue WHERE repo_id = ?1 AND title LIKE 'Wave %'")
827 .get(repo.id)!.n;
828 const run = async (user: User, name: string, keys: string[]): Promise<string> => {
829 const terminal = headlessTerminal(120, 40);
830 const { app } = createForgeApp(
831 forge,
832 { sshUsername: name, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user },
833 { terminal, exitHooks: false },
834 );
835 app.start();
836 try {
837 await settleApp(app);
838 const send = (key: string): void =>
839 app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
840 for (const ch of `/lamp`) send(ch);
841 for (const k of ["enter", "enter"]) send(k);
842 await settleUntil(app, `${name === "bob" ? "alice" : name}/lamp`);
843 for (const k of keys) send(k);
844 await settleApp(app);
845 return app.screen.toText();
846 } finally {
847 app.stop();
848 }
849 };
850 await run(bob, "bob", ["R", "right", "enter"]);
851 expect(waves()).toBe(0);
852 await run(alice, "alice", ["R", "right", "enter"]);
853 expect(waves()).toBe(1);
854 } finally {
855 forge.close();
856 await rm(dataDir, { recursive: true, force: true });
857 }
858 });
859 });
860
793861 const text = (bytes: Uint8Array): string => new TextDecoder().decode(bytes);
794862
795863 /** How many commits a ref has. The git binary answers, as it always does. */
test/wave-cut.test.ts added +264
@@ -0,0 +1,264 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { mergePull, openPull } from "../src/actions/pulls.ts";
7 import { setIssueStateThrough } from "../src/actions/issues.ts";
8 import { commitToBranch } from "../src/actions/repos.ts";
9 import { getPull, type Pull } from "../src/core/pulls.ts";
10 import { getRepo, type Repo } from "../src/core/repos.ts";
11 import { getUserByName, type User } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { readerFor } from "../src/git/read.ts";
14 import { repoDir } from "../src/git/repos.ts";
15 import { cutWave } from "../src/story/cut.ts";
16 import { parseWave } from "../src/story/wave.ts";
17
18 describe("cut a wave", () => {
19 let dataDir: string;
20 let app: App;
21 let servers: Servers;
22 let base: string;
23 let owner: User;
24 let repo: Repo;
25 const shipped: Pull[] = [];
26 let ownerCookie = "";
27 let strangerCookie = "";
28
29 const signup = async (username: string): Promise<string> => {
30 const res = await fetch(`${base}/signup`, {
31 method: "POST",
32 body: new URLSearchParams({
33 username,
34 email: `${username}@f.dev`,
35 password: "wave-password-1",
36 }),
37 redirect: "manual",
38 });
39 return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
40 };
41 const cut = (cookie: string, headers: Record<string, string> = {}) =>
42 fetch(`${base}/olive/proj/settings/wave`, {
43 method: "POST",
44 headers: { cookie, ...headers },
45 redirect: "manual",
46 });
47 const ship = async (branch: string, title: string): Promise<Pull> => {
48 await commitToBranch(app, owner, repo, {
49 branch,
50 base: "main",
51 message: title,
52 files: [{ path: `${branch}.txt`, content: title }],
53 });
54 const opened = await openPull(app, owner, repo, {
55 title,
56 baseBranch: "main",
57 headBranch: branch,
58 });
59 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
60 const merged = await mergePull(app, owner, repo, opened.value, "squash");
61 if (!merged.ok) throw new Error(JSON.stringify(merged.error));
62 return getPull(app.db, repo.id, opened.value.number)!;
63 };
64 const branchFile = async (branch: string, path: string) => {
65 const o = await readerFor(
66 repoDir(app.reposRoot, repo.ownerName, repo.name),
67 ).object(`refs/heads/${branch}:${path}`);
68 return o.ok ? new TextDecoder().decode(o.value.body) : undefined;
69 };
70 const wavePulls = () =>
71 app.db
72 .query<{ n: number }, [string]>(
73 "SELECT count(*) n FROM issue WHERE repo_id = ?1 AND title LIKE 'Wave %'",
74 )
75 .get(repo.id)!.n;
76
77 beforeAll(async () => {
78 dataDir = await mkdtemp(join(tmpdir(), "forge-wave-cut-"));
79 app = createApp({ dataDir, port: 0 });
80 servers = await serve(app);
81 base = servers.url;
82 ownerCookie = await signup("olive");
83 strangerCookie = await signup("stranger");
84 await fetch(`${base}/new`, {
85 method: "POST",
86 headers: { cookie: ownerCookie },
87 body: new URLSearchParams({ name: "proj", visibility: "public" }),
88 redirect: "manual",
89 });
90 owner = getUserByName(app.db, "olive")!;
91 repo = getRepo(app.db, "olive", "proj")!;
92 await commitToBranch(app, owner, repo, {
93 branch: "main",
94 message: "base",
95 files: [{ path: "a.txt", content: "a" }],
96 });
97 });
98
99 afterAll(async () => {
100 servers.stop();
101 app.close();
102 await rm(dataDir, { recursive: true, force: true });
103 });
104
105 test("a cut with nothing merged is refused with a reason", async () => {
106 const res = await cut(ownerCookie);
107 expect(res.status).toBe(303);
108 expect(wavePulls()).toBe(0);
109 const page = await fetch(`${base}/olive/proj/settings`, {
110 headers: { cookie: ownerCookie },
111 });
112 expect(await page.text()).toContain("Cut a wave");
113 });
114
115 test("a non-admin and a cross-origin POST are refused; nothing opens", async () => {
116 shipped.push(await ship("one", "First [thing]"));
117 shipped.push(await ship("two", "Second thing"));
118 expect((await cut(strangerCookie)).status).toBe(404);
119 expect((await cut("")).status).toBe(404);
120 const cross = await cut(ownerCookie, { origin: "http://evil.example" });
121 expect(cross.status).toBeGreaterThanOrEqual(400);
122 expect(wavePulls()).toBe(0);
123 });
124
125 test("an admin's cut opens a pull whose file lists exactly the merged pulls", async () => {
126 const res = await cut(ownerCookie);
127 expect(res.status).toBe(303);
128 expect(wavePulls()).toBe(1);
129 const text = await branchFile("wave-0.1.0", "waves/0.1.0.md");
130 expect(text).toBeDefined();
131 const wave = parseWave("waves/0.1.0.md", text!);
132 expect(wave.ok).toBe(true);
133 if (!wave.ok) return;
134 const titles = wave.value.pulls.map((p) => p.title);
135 expect(titles).toEqual([
136 `#${shipped[0]!.number} First thing`,
137 `#${shipped[1]!.number} Second thing`,
138 ]);
139 expect(text).toContain("TODO");
140 });
141
142 test("a second cut while the wave pull is open is refused and points at it", async () => {
143 const open = app.db
144 .query<{ number: number }, [string]>(
145 "SELECT number FROM issue WHERE repo_id = ?1 AND title = 'Wave 0.1.0'",
146 )
147 .get(repo.id)!;
148 const res = await cut(ownerCookie);
149 expect(res.status).toBe(303);
150 expect(res.headers.get("location")).toContain(`/olive/proj/pulls/${open.number}`);
151 expect(wavePulls()).toBe(1);
152 });
153
154 test("a closed, unmerged wave pull leaves a branch the next cut replaces", async () => {
155 const first = app.db
156 .query<{ number: number }, [string]>(
157 "SELECT number FROM issue WHERE repo_id = ?1 AND title = 'Wave 0.1.0'",
158 )
159 .get(repo.id)!;
160 const closed = await setIssueStateThrough(
161 app,
162 owner,
163 repo,
164 getPull(app.db, repo.id, first.number)!,
165 "closed",
166 );
167 expect(closed.ok).toBe(true);
168 const res = await cut(ownerCookie);
169 expect(res.status).toBe(303);
170 expect(res.headers.get("location")).not.toContain(`/pulls/${first.number}`);
171 expect(res.headers.get("location")).toContain("/pulls/");
172 expect(wavePulls()).toBe(2);
173 expect(await branchFile("wave-0.1.0", "waves/0.1.0.md")).toBeDefined();
174 });
175
176 test("a branch that is not a previous cut survives, and the cut is refused", async () => {
177 // Close the open 0.1.0 wave pull and put a person's work on its branch.
178 const open = app.db
179 .query<{ number: number }, [string]>(
180 "SELECT i.number FROM issue i WHERE i.repo_id = ?1 AND i.title = 'Wave 0.1.0' AND i.state = 'open'",
181 )
182 .get(repo.id)!;
183 await setIssueStateThrough(app, owner, repo, getPull(app.db, repo.id, open.number)!, "closed");
184 await commitToBranch(app, owner, repo, {
185 branch: "wave-0.1.0",
186 message: "my own work",
187 files: [{ path: "mine.txt", content: "mine" }],
188 });
189 const before = wavePulls();
190 const res = await cut(ownerCookie);
191 expect(res.status).toBe(303);
192 expect(wavePulls()).toBe(before);
193 expect(await branchFile("wave-0.1.0", "mine.txt")).toBe("mine");
194 });
195 });
196
197 describe("cutWave (pure)", () => {
198 const good = `---
199 version: 0.2.0
200 date: 2026-10-01
201 headline: h
202 ---
203
204 ## Highlights
205
206 - **A** — a
207 - **B** — b
208 - **C** — c
209
210 ## Pulls
211
212 - [#1 Old](http://x/p/1)
213 `;
214 const pull = (n: number, at: string) => ({
215 number: n,
216 title: `T${n}`,
217 url: `http://x/p/${n}`,
218 mergedAt: at,
219 headBranch: `b${n}`,
220 });
221
222 test("lists pulls from the last wave's day on, skipping those already listed", () => {
223 const r = cutWave(
224 [{ path: "waves/0.2.0.md", text: good }],
225 [pull(1, "2026-10-01T05:00:00Z"), pull(2, "2026-09-30T05:00:00Z"), pull(3, "2026-10-03T05:00:00Z")],
226 "2026-10-05",
227 );
228 expect(r.ok).toBe(true);
229 if (!r.ok) return;
230 expect(r.value.path).toBe("waves/0.2.1.md");
231 expect(r.value.pulls).toBe(1);
232 expect(r.value.text).toContain("[#3 T3](http://x/p/3)");
233 expect(r.value.text).toContain("TODO");
234 });
235
236 test("a malformed earlier wave stops the cut and is named", () => {
237 const r = cutWave(
238 [
239 { path: "waves/0.2.0.md", text: good },
240 { path: "waves/0.1.0.md", text: "no front matter" },
241 ],
242 [pull(3, "2026-10-03T05:00:00Z")],
243 "2026-10-05",
244 );
245 expect(r).toMatchObject({ ok: false, error: { kind: "malformed", path: "waves/0.1.0.md" } });
246 });
247
248 test("a wave's own pull is not listed in the next wave", () => {
249 const r = cutWave(
250 [{ path: "waves/0.2.0.md", text: good }],
251 [pull(3, "2026-10-03T05:00:00Z"), { ...pull(4, "2026-10-04T05:00:00Z"), headBranch: "wave-0.2.0" }],
252 "2026-10-05",
253 );
254 expect(r.ok).toBe(true);
255 if (!r.ok) return;
256 expect(r.value.pulls).toBe(1);
257 expect(r.value.text).not.toContain("T4");
258 });
259
260 test("nothing new is refused", () => {
261 const r = cutWave([{ path: "waves/0.2.0.md", text: good }], [pull(1, "2026-10-01T05:00:00Z")], "2026-10-05");
262 expect(r).toEqual({ ok: false, error: { kind: "nothing_new" } });
263 });
264 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs