Public: anyone can read this; the crew can change it.
When a new forge's crew cannot continue on a green pull, the pull and app page say why and offer Land it as it is #16247
scout/forge:scout/11892-when-a-new-forge-s-crew-cannot-continue → main 6 commits fork
10 files
changed +426
−4
docs/MCP.md +1 −1
| @@ -139,7 +139,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`; | ||
| 139 | 139 | | `maintenance` | `status`, `prepare`, `resume`, `pause-duty`, `resume-duty` | Prepare the forge for a power-off, check the drain, or end maintenance (admin) | 308 | |
| 140 | 140 | | `make_it_yours` | — | Fork an app you can see: code and history, following the original | 337 | |
| 141 | 141 | | `map` | — | An app's plan: ready or waiting, critical path, crew, parkedTwice; `done` adds closed; `first: N` ranks N first | 375 | |
| 142 | | `merge` | — | Land a pull, as its page's Merge button does; a person's only | 319 | | |
| 142 | | `merge` | `land` | Land a pull, as its page's Merge button does; a person's only | 362 | | |
| 143 | 143 | | `migrate` | — | Bring a repo in by public `url` (`name`, `crew`), history and all | 269 | |
| 144 | 144 | | `milestones` | — | How far each ask is | 391 | |
| 145 | 145 | | `mint_invite` | — | Mint a one-use invite link, shown once, valid `days` (1–30, default 7) | 225 | |
docs/features/land-as-is.md added +10
| @@ -0,0 +1,10 @@ | ||
| 1 | # Land it as it is | |
| 2 | ||
| 3 | When the crew cannot go on (its included credit is spent, or it has no model key) a green pull still goes live. | |
| 4 | ||
| 5 | - The pull page and the app's page each say so in one sentence, and offer **Land it as it is** with the preview link beside it, and **Add a key**. | |
| 6 | - The button is the pull's own ship action (`POST /:owner/:name/pulls/:n/ship`, same-origin checked, `mergePull` behind it). It is offered only for a pull whose check is green and whose verdict is "Ready to land"; a red pull never shows it. | |
| 7 | - MCP: the existing `merge` tool takes `action: "land"` (squash, only while the check is green); its plan carries `crew` with the same sentence. | |
| 8 | - Code: `src/web/studio/land_as_is.ts`. Test: `test/land-as-is.test.ts`. | |
| 9 | - Terminal: the palette's "<owner>/<name> — Land it as it is" (`src/tui/screens/landasis.ts`) while an open app has a pull to land; Enter lands the pull under the cursor, squashed, as the page's button does. `landable` gives the page, the terminal and MCP the same rows (a writer's, the crew stopped, the check green). | |
| 10 | - Only an admin is shown **Add a key**; anyone else is told only the admin can. |
src/http/mcp/tools/merge.ts +11 −3
| @@ -3,6 +3,7 @@ import { mergePull } from "../../../actions/pulls.ts"; | ||
| 3 | 3 | import { getPull, pullDir, pullMergeState } from "../../../core/pulls.ts"; |
| 4 | 4 | import { checkSummary } from "../../../core/runs.ts"; |
| 5 | 5 | import { mergeFailure } from "../../../web/pages/pull.ts"; |
| 6 | import { LAND_AS_IS, stalledWords } from "../../../web/studio/land_as_is.ts"; | |
| 6 | 7 | import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"; |
| 7 | 8 | |
| 8 | 9 | /** |
| @@ -13,7 +14,7 @@ import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts" | ||
| 13 | 14 | */ |
| 14 | 15 | export const tool: Tool = { |
| 15 | 16 | name: "merge", |
| 16 | doc: "`{ repo, number, strategy?, dryRun? }` (a person, never an agent: a person merges): land a pull as its page's Merge button does, `merge` (default) or `squash`; planned unless `dryRun` is false: the plan is the pull's `head`, `base`, `mergeable`, `conflicts` and `check` as `pull` reads them; landing is `mergePull`'s, with its refusals (conflict, review or check required, not a writer) in the page's words, and takes an rw token", | |
| 17 | doc: "`{ repo, number, strategy?, action?, dryRun? }` (a person, never an agent: a person merges): land a pull as its page's Merge button does, `merge` (default) or `squash`; `action: \"land\"` is the page's Land it as it is (squash, and only while the check is green); plans carry `crew` when the crew cannot go on; planned unless `dryRun` is false: the plan is the pull's `head`, `base`, `mergeable`, `conflicts` and `check` as `pull` reads them; landing is `mergePull`'s, with its refusals (conflict, review or check required, not a writer) in the page's words, and takes an rw token", | |
| 17 | 18 | description: "Land a pull, as its page's Merge button does; a person's only.", |
| 18 | 19 | inputSchema: { |
| 19 | 20 | type: "object", |
| @@ -21,6 +22,7 @@ export const tool: Tool = { | ||
| 21 | 22 | repo: REPO_ARG, |
| 22 | 23 | number: { type: "integer", minimum: 1 }, |
| 23 | 24 | strategy: { type: "string", enum: ["merge", "squash"] }, |
| 25 | action: { type: "string", enum: ["land"] }, | |
| 24 | 26 | dryRun: { type: "boolean" }, |
| 25 | 27 | }, |
| 26 | 28 | required: ["repo", "number"], |
| @@ -35,7 +37,9 @@ export const tool: Tool = { | ||
| 35 | 37 | const s = args["strategy"]; |
| 36 | 38 | if (s !== undefined && s !== "merge" && s !== "squash") |
| 37 | 39 | return bad("invalid", "strategy is merge or squash"); |
| 38 | const strategy = s === "squash" ? "squash" : "merge"; | |
| 40 | const act = args["action"]; | |
| 41 | if (act !== undefined && act !== "land") return bad("invalid", "action is land"); | |
| 42 | const strategy = s === "squash" || act === "land" ? "squash" : "merge"; | |
| 39 | 43 | const n = args["number"]; |
| 40 | 44 | const pull = |
| 41 | 45 | typeof n === "number" && Number.isInteger(n) && n > 0 |
| @@ -43,6 +47,7 @@ export const tool: Tool = { | ||
| 43 | 47 | : undefined; |
| 44 | 48 | if (pull === undefined || !mayView(ctx.app.db, repo, pull, user)) |
| 45 | 49 | return bad("no_such_pull", `no pull #${String(n)}`); |
| 50 | const stalled = stalledWords(ctx.app); | |
| 46 | 51 | const url = `/${repo.ownerName}/${repo.name}/pulls/${pull.number}`; |
| 47 | 52 | if (args["dryRun"] !== false) { |
| 48 | 53 | // The `pull` tool's reads, so the plan and the reading never disagree. |
| @@ -60,9 +65,12 @@ export const tool: Tool = { | ||
| 60 | 65 | conflicts: state?.conflicts ?? [], |
| 61 | 66 | check: { state: check.state, baseOid: check.run?.baseOid ?? "" }, |
| 62 | 67 | url, |
| 68 | ...(stalled === null ? {} : { crew: stalled }), | |
| 63 | 69 | says: "This is the plan; nothing changed. Send dryRun: false to merge.", |
| 64 | 70 | }); |
| 65 | 71 | } |
| 72 | if (act === "land" && checkSummary(ctx.app.db, pull.id, pull.headOid).state !== "ok") | |
| 73 | return bad("check_required", `${LAND_AS_IS} waits for a green check`); | |
| 66 | 74 | const merged = await mergePull(ctx.app, user, repo, pull, strategy); |
| 67 | 75 | if (!merged.ok) { |
| 68 | 76 | const error = merged.error; |
| @@ -80,7 +88,7 @@ export const tool: Tool = { | ||
| 80 | 88 | strategy, |
| 81 | 89 | mergeOid: merged.value.mergeOid, |
| 82 | 90 | url, |
| 83 | says: `Merged #${pull.number} into ${pull.baseBranch}.`, | |
| 91 | says: act === "land" ? `Landed #${pull.number} as it is.` : `Merged #${pull.number} into ${pull.baseBranch}.`, | |
| 84 | 92 | }); |
| 85 | 93 | }, |
| 86 | 94 | }; |
src/tui/screens/landasis.ts added +65
| @@ -0,0 +1,65 @@ | ||
| 1 | /** | |
| 2 | * Land it as it is, in the terminal (#11892): when the crew cannot go on, the | |
| 3 | * app's green pulls the viewer may land, from the same rows as the page | |
| 4 | * (`web/studio/land_as_is.ts`, a writer's, the check green). Enter lands the | |
| 5 | * pull under the cursor, squashed, as the page's button does, with the page's | |
| 6 | * refusals in its words. Offered in the palette only while there is one. | |
| 7 | */ | |
| 8 | ||
| 9 | import { mergePull } from "../../actions/pulls.ts"; | |
| 10 | import type { Repo } from "../../core/repos.ts"; | |
| 11 | import { mergeFailure } from "../../web/pages/pull.ts"; | |
| 12 | import { LAND_AS_IS, landable, stalledWords } from "../../web/studio/land_as_is.ts"; | |
| 13 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 14 | import { binding } from "../app/keys.ts"; | |
| 15 | import type { Command } from "../app/palette.ts"; | |
| 16 | import type { Session } from "../session.ts"; | |
| 17 | import { style } from "../term/style.ts"; | |
| 18 | import { truncate } from "../term/width.ts"; | |
| 19 | import { fill, len, split } from "../ui/layout.ts"; | |
| 20 | import { ListState, drawList, type ListRow } from "./common.ts"; | |
| 21 | ||
| 22 | export function landScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | |
| 23 | const state = new ListState(); | |
| 24 | let busy = false; | |
| 25 | return { | |
| 26 | title: `${repo.ownerName}/${repo.name} — ${LAND_AS_IS}`, | |
| 27 | keys: [binding(["j", "k"], "move cursor"), binding(["enter"], LAND_AS_IS)], | |
| 28 | render(area, s) { | |
| 29 | const c = ctx.theme.c; | |
| 30 | const all = landable(f.app, f.user, repo); | |
| 31 | const [head, list] = split(area, "v", [len(1), fill(1)]); | |
| 32 | s.text(head!.x, head!.y, truncate(stalledWords(f.app) ?? "The crew can go on; nothing waits here.", head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 33 | const lines: ListRow[] = all.map((p) => ({ title: p.title, meta: `#${p.number}` })); | |
| 34 | drawList(s, list!, c, state, lines); | |
| 35 | }, | |
| 36 | key(e) { | |
| 37 | const all = landable(f.app, f.user, repo); | |
| 38 | if (state.key(e, all.length)) return true; | |
| 39 | if (e.ctrl || e.alt || e.key !== "enter") return false; | |
| 40 | const at = all[state.index]; | |
| 41 | if (at === undefined || busy) return true; | |
| 42 | busy = true; | |
| 43 | void mergePull(f.app, f.user, repo, at, "squash") | |
| 44 | .then((done) => ctx.toast(done.ok ? `Landed #${at.number} as it is.` : mergeFailure(done.error), done.ok ? undefined : "danger")) | |
| 45 | .finally(() => { | |
| 46 | busy = false; | |
| 47 | ctx.invalidate(); | |
| 48 | }); | |
| 49 | return true; | |
| 50 | }, | |
| 51 | }; | |
| 52 | } | |
| 53 | ||
| 54 | /** The palette's command while a repository with a pull to land as it is is open. */ | |
| 55 | export function landCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] { | |
| 56 | if (repo === undefined || landable(f.app, f.user, repo).length === 0) return []; | |
| 57 | return [ | |
| 58 | { | |
| 59 | id: "land-as-is", | |
| 60 | title: `${repo.ownerName}/${repo.name} — ${LAND_AS_IS}`, | |
| 61 | hint: "the crew cannot go on: land a green pull as it is", | |
| 62 | run: () => ctx.push(landScreen(f, ctx, repo)), | |
| 63 | }, | |
| 64 | ]; | |
| 65 | } |
src/tui/screens/workspace.ts +2
| @@ -172,6 +172,7 @@ import { autonomyCommands } from "./autonomy.ts"; | ||
| 172 | 172 | import { trafficCommands } from "./trafficview.ts"; |
| 173 | 173 | import { chaptersCommands } from "./chapters.ts"; |
| 174 | 174 | import { schedulesCommands } from "./schedules.ts"; |
| 175 | import { landCommands } from "./landasis.ts"; | |
| 175 | 176 | import { shiftCommands } from "./subtitle_shift.ts"; |
| 176 | 177 | import { dataImportCommands } from "./dataimport.ts"; |
| 177 | 178 | import { jobsCommands } from "./jobs.ts"; |
| @@ -2001,6 +2002,7 @@ export function workspaceScreen( | ||
| 2001 | 2002 | ...autonomyCommands(f, ctx, repo), |
| 2002 | 2003 | ...trafficCommands(f, ctx, repo), |
| 2003 | 2004 | ...schedulesCommands(f, ctx, repo), |
| 2005 | ...landCommands(f, ctx, repo), | |
| 2004 | 2006 | ...shiftCommands(f, ctx, repo, () => screen), |
| 2005 | 2007 | ...dataImportCommands(f, ctx, repo), |
| 2006 | 2008 | ...jobsCommands(f, ctx, repo), |
src/web/pages/pull.ts +4
| @@ -32,6 +32,7 @@ import { tierLine, type TierState } from "../../checks/tiers.ts"; | ||
| 32 | 32 | import { fromKeptFork } from "../../core/landing_kind.ts"; |
| 33 | 33 | import { combinedCard } from "./pull-combined.ts"; |
| 34 | 34 | import { verdictLine, verdictOf, type VerdictInput } from "./pull-verdict.ts"; |
| 35 | import { landAsIs } from "../studio/land_as_is.ts"; | |
| 35 | 36 | import { getAppByRepo } from "../../core/apps.ts"; |
| 36 | 37 | import { labelsFor, listLabels } from "../../core/issues.ts"; |
| 37 | 38 | import { marksByName } from "../../core/marks.ts"; |
| @@ -1110,6 +1111,9 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> { | ||
| 1110 | 1111 | ${changeHead(ctx, repo, pull, { headOid: status.headOid, conflicts: status.conflicts.length })} |
| 1111 | 1112 | ${changeTabs(repo, pull, "files")} |
| 1112 | 1113 | ${verdictLine(verdict)} |
| 1114 | ${verdict.tone === "success" && mayMerge && check.state === "ok" && !stale | |
| 1115 | ? landAsIs(ctx, repo, pull) | |
| 1116 | : null} | |
| 1113 | 1117 | <p class="files-where muted small" id="files"> |
| 1114 | 1118 | <span class="mono">${headLabel} → ${pull.baseBranch}</span> |
| 1115 | 1119 | <span class="sep" aria-hidden="true">·</span> |
src/web/studio/app.ts +3
| @@ -65,6 +65,7 @@ import { schedulesCard } from "./schedules.ts"; | ||
| 65 | 65 | import { appPanels } from "./previews.ts"; |
| 66 | 66 | import { noCrewLine, pausedWords, servingHistory, type WordCtx } from "./words.ts"; |
| 67 | 67 | import { crewKeyCard, includedCredit } from "./crew_key.ts"; |
| 68 | import { landOnApp } from "./land_as_is.ts"; | |
| 68 | 69 | import { usdWords } from "../../spawn/credit.ts"; |
| 69 | 70 | import { |
| 70 | 71 | notePhase, |
| @@ -510,6 +511,7 @@ export async function studioApp( | ||
| 510 | 511 | : followingCard(ctx, repo, following)} |
| 511 | 512 | <div id="app-head">${head}</div> |
| 512 | 513 | ${ownerFacts ? crewKeyCard(ctx, true) : null} |
| 514 | ${ownerFacts ? landOnApp(ctx, repo) : null} | |
| 513 | 515 | <div class="stack"> |
| 514 | 516 | ${adapter} |
| 515 | 517 | ${schedules} |
| @@ -531,6 +533,7 @@ export async function studioApp( | ||
| 531 | 533 | ${askingLine(ctx, repo)} |
| 532 | 534 | ${policy} |
| 533 | 535 | ${ownerFacts ? crewKeyCard(ctx, true) : null} |
| 536 | ${ownerFacts ? landOnApp(ctx, repo) : null} | |
| 534 | 537 | ${ownerFacts |
| 535 | 538 | ? egressNote( |
| 536 | 539 | ctx.app.config.dataDir, |
src/web/studio/change.ts +4
| @@ -66,6 +66,7 @@ import { | ||
| 66 | 66 | import { previewBlock } from "../pages/apps.ts"; |
| 67 | 67 | import { lookCard } from "../pages/looks.ts"; |
| 68 | 68 | import { approveHereCard, keptChange, pullChecksLineFor, teamsCard, verdictFacts } from "../pages/pull.ts"; |
| 69 | import { landAsIs } from "./land_as_is.ts"; | |
| 69 | 70 | import { changeSummary, verdictLine, verdictOf } from "../pages/pull-verdict.ts"; |
| 70 | 71 | import { guestWalls, strangerCard } from "../pages/pull-guest.ts"; |
| 71 | 72 | import { combinedCard } from "../pages/pull-combined.ts"; |
| @@ -757,6 +758,9 @@ async function changeConversation( | ||
| 757 | 758 | )} |
| 758 | 759 | <div id="pull-check">${checkLine}</div> |
| 759 | 760 | ${when(runLine, (l) => l)} ${gate} ${decisionSection} |
| 761 | ${verdict.tone === "success" && writer && word === "look" | |
| 762 | ? landAsIs(ctx, repo, pull) | |
| 763 | : null} | |
| 760 | 764 | ${when(visionPreview, (v) => visionPreviewCard(v))} |
| 761 | 765 | ${look} |
| 762 | 766 | <div class="split"> |
src/web/studio/land_as_is.ts added +90
| @@ -0,0 +1,90 @@ | ||
| 1 | /** | |
| 2 | * Land it as it is (#11892): when the crew cannot go on (its included credit | |
| 3 | * is spent, or it has no model key) a green pull still lands. One sentence | |
| 4 | * says why the crew stopped; the pull's own ship action follows (squash, | |
| 5 | * `POST …/pulls/:n/ship`, same-origin checked, `mergePull` behind it), with | |
| 6 | * the preview beside it and, for an admin, the way to add a key. A red or | |
| 7 | * held pull is never offered it. `landable` and `landWords` give the pages, | |
| 8 | * the MCP `merge` tool and the terminal screen the same rows and the same | |
| 9 | * refusals. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { App } from "../../app.ts"; | |
| 13 | import { requireWriter } from "../../actions/access.ts"; | |
| 14 | import { getAppByRepo } from "../../core/apps.ts"; | |
| 15 | import { listOpenPulls, type Pull } from "../../core/pulls.ts"; | |
| 16 | import type { Repo } from "../../core/repos.ts"; | |
| 17 | import { checkSummary } from "../../core/runs.ts"; | |
| 18 | import type { User } from "../../core/users.ts"; | |
| 19 | import type { Ctx } from "../../http/context.ts"; | |
| 20 | import { repoBase } from "../chrome.ts"; | |
| 21 | import { html, when, type Html } from "../html.ts"; | |
| 22 | import { btn, card, listCard, row } from "../ui.ts"; | |
| 23 | import { crewCanRun, hasCrew, includedCredit } from "./crew_key.ts"; | |
| 24 | import { changeHref } from "./nouns.ts"; | |
| 25 | ||
| 26 | /** The one label, on the page, in the terminal and in the MCP tool's `action`. */ | |
| 27 | export const LAND_AS_IS = "Land it as it is"; | |
| 28 | export const ADD_KEY_HREF = "/settings/subscriptions"; | |
| 29 | ||
| 30 | /** | |
| 31 | * Why the crew cannot go on, in one plain sentence; null while it can, or when there is no | |
| 32 | * crew to stop. | |
| 33 | */ | |
| 34 | export function stalledWords(app: App): string | null { | |
| 35 | if (!hasCrew(app) || crewCanRun(app)) return null; | |
| 36 | return includedCredit(app) !== undefined | |
| 37 | ? "The crew cannot go on: the included credit is spent." | |
| 38 | : "The crew cannot go on: it has no model key."; | |
| 39 | } | |
| 40 | ||
| 41 | /** | |
| 42 | * The open pulls of this repository the viewer may land as they are: a writer's, the crew | |
| 43 | * stopped, the check green. | |
| 44 | */ | |
| 45 | export function landable(app: App, user: User | undefined, repo: Repo): Pull[] { | |
| 46 | if (stalledWords(app) === null || !requireWriter(app, user, repo).ok) return []; | |
| 47 | return listOpenPulls(app.db, repo.id).filter((p) => p.mergedAt === null && checkSummary(app.db, p.id, p.headOid).state === "ok"); | |
| 48 | } | |
| 49 | ||
| 50 | /** Where a pull's preview opens, when the repository is an app. */ | |
| 51 | const previewOf = (app: App, repo: Repo, pull: Pull): string | undefined => | |
| 52 | getAppByRepo(app.db, repo.id) === undefined ? undefined : `${repoBase(repo)}/app/pull-${pull.number}/open`; | |
| 53 | ||
| 54 | const landForm = (repo: Repo, pull: Pull): Html => | |
| 55 | html`<form method="post" action="${repoBase(repo)}/pulls/${pull.number}/ship" data-now="Landing">${btn(LAND_AS_IS, { size: "sm", variant: "primary", icon: "merge" })}</form>`; | |
| 56 | ||
| 57 | /** Who may add a key gets the link; anyone else is told why there is none. */ | |
| 58 | const keyOffer = (ctx: Ctx): Html => | |
| 59 | ctx.auth.user?.isAdmin === true | |
| 60 | ? btn("Add a key", { href: ADD_KEY_HREF, size: "sm" }) | |
| 61 | : html`<span class="muted small">Only this forge's admin can add a key.</span>`; | |
| 62 | ||
| 63 | /** The pull's own page: the sentence, the button, the preview beside it, the key. */ | |
| 64 | export function landAsIs(ctx: Ctx, repo: Repo, pull: Pull): Html | null { | |
| 65 | const words = stalledWords(ctx.app); | |
| 66 | if (words === null || !landable(ctx.app, ctx.auth.user, repo).some((p) => p.id === pull.id)) return null; | |
| 67 | return card( | |
| 68 | html`<div class="bar">${landForm(repo, pull)}${when(previewOf(ctx.app, repo, pull), (href) => btn("Preview", { href, size: "sm" }))}${keyOffer(ctx)}</div>`, | |
| 69 | { id: "land-as-is", head: html`${words}`, attrs: html`data-land-as-is role="status"` }, | |
| 70 | ); | |
| 71 | } | |
| 72 | ||
| 73 | /** | |
| 74 | * The app's page: the sentence once, then one row per green pull with its button. Reads | |
| 75 | * nothing while the crew can go on. | |
| 76 | */ | |
| 77 | export function landOnApp(ctx: Ctx, repo: Repo): Html | null { | |
| 78 | const words = stalledWords(ctx.app); | |
| 79 | const green = words === null ? [] : landable(ctx.app, ctx.auth.user, repo); | |
| 80 | if (words === null || green.length === 0) return null; | |
| 81 | return listCard( | |
| 82 | green.map((pull) => | |
| 83 | row({ | |
| 84 | title: html`<a href="${changeHref(repoBase(repo), pull.number)}">${pull.title}</a>`, | |
| 85 | trail: html`<span class="bar">${landForm(repo, pull)}${when(previewOf(ctx.app, repo, pull), (href) => btn("Preview", { href, size: "sm" }))}</span>`, | |
| 86 | }), | |
| 87 | ), | |
| 88 | { id: "land-as-is", head: html`${words} ${keyOffer(ctx)}`, attrs: html`data-land-as-is role="status"` }, | |
| 89 | ); | |
| 90 | } |
test/land-as-is.test.ts added +236
| @@ -0,0 +1,236 @@ | ||
| 1 | /** | |
| 2 | * Land it as it is (#11892): credit runs out after a pull went green; the | |
| 3 | * pull page and the app page say so in one sentence and offer the button, | |
| 4 | * and pressing it lands the pull. A red pull is never offered it. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { writeFileSync } from "node:fs"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { enableApp } from "../src/actions/apps.ts"; | |
| 13 | import { addToCrew, createAgent } from "../src/actions/crew.ts"; | |
| 14 | import { openPull } from "../src/actions/pulls.ts"; | |
| 15 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 16 | import { getPull, type Pull } from "../src/core/pulls.ts"; | |
| 17 | import type { Repo } from "../src/core/repos.ts"; | |
| 18 | import { claimRun, createRun, finishRun } from "../src/core/runs.ts"; | |
| 19 | import { createUser, type User } from "../src/core/users.ts"; | |
| 20 | import { createToken } from "../src/core/tokens.ts"; | |
| 21 | import { promote } from "./helpers/members.ts"; | |
| 22 | import { landable } from "../src/web/studio/land_as_is.ts"; | |
| 23 | import { landCommands } from "../src/tui/screens/landasis.ts"; | |
| 24 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 25 | import { STRANGER_NEVER_SEES } from "../src/design/first_five_minutes.ts"; | |
| 26 | import { LAND_AS_IS } from "../src/web/studio/land_as_is.ts"; | |
| 27 | ||
| 28 | describe("land it as it is", () => { | |
| 29 | let dataDir = ""; | |
| 30 | let app: App; | |
| 31 | let servers: Servers; | |
| 32 | let base = ""; | |
| 33 | let alice: User; | |
| 34 | let repo: Repo; | |
| 35 | let cookie = ""; | |
| 36 | let n = 0; | |
| 37 | ||
| 38 | const get = (path: string) => | |
| 39 | fetch(`${base}${path}`, { headers: { cookie: `${cookie}; forge_mode=studio` }, redirect: "manual" }).then((r) => r.text()); | |
| 40 | ||
| 41 | const pullWith = async (state: "ok" | "failed", who: User = alice, into: Repo = repo): Promise<Pull> => { | |
| 42 | n += 1; | |
| 43 | const repo = into; | |
| 44 | const alice = who; | |
| 45 | const branch = await commitToBranch(app, alice, repo, { | |
| 46 | branch: `feature/b${n}`, | |
| 47 | base: "main", | |
| 48 | message: `Change ${n}`, | |
| 49 | files: [{ path: `F${n}.md`, content: `${n}\n` }], | |
| 50 | }); | |
| 51 | if (!branch.ok) throw new Error(JSON.stringify(branch.error)); | |
| 52 | const opened = await openPull(app, alice, repo, { | |
| 53 | title: `Change ${n}`, | |
| 54 | body: "A change.", | |
| 55 | baseBranch: "main", | |
| 56 | headBranch: `feature/b${n}`, | |
| 57 | }); | |
| 58 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 59 | const pull = opened.value; | |
| 60 | const run = createRun(app.db, { | |
| 61 | repoId: repo.id, | |
| 62 | kind: "check", | |
| 63 | issueId: pull.id, | |
| 64 | env: `pull-${pull.number}`, | |
| 65 | commitOid: pull.headOid, | |
| 66 | reason: "pull", | |
| 67 | }); | |
| 68 | claimRun(app.db, run.id); | |
| 69 | finishRun(app.db, run.id, { state, summary: state === "ok" ? "check passed in 1s" : "check failed" }); | |
| 70 | return pull; | |
| 71 | }; | |
| 72 | ||
| 73 | const mcp = async (token: string, args: unknown) => { | |
| 74 | const res = await fetch(`${base}/mcp`, { | |
| 75 | method: "POST", | |
| 76 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, | |
| 77 | body: JSON.stringify({ jsonrpc: "2.0", id: n++, method: "tools/call", params: { name: "merge", arguments: args } }), | |
| 78 | }); | |
| 79 | const body = (await res.json()) as any; | |
| 80 | const text: string = body.result.content[0].text; | |
| 81 | return body.result.isError === true ? { error: text } : { value: JSON.parse(text) }; | |
| 82 | }; | |
| 83 | ||
| 84 | const spendCredit = () => | |
| 85 | writeFileSync( | |
| 86 | join(dataDir, "parent.json"), | |
| 87 | JSON.stringify({ credit: { token: "bearer-token-123", capUsd: 5, spentUsd: 5 } }), | |
| 88 | ); | |
| 89 | ||
| 90 | beforeAll(async () => { | |
| 91 | dataDir = await mkdtemp(join(tmpdir(), "forge-land-as-is-")); | |
| 92 | app = createApp({ dataDir, port: 0 }); | |
| 93 | servers = await serve(app); | |
| 94 | base = servers.url; | |
| 95 | const a = await createUser(app.db, { | |
| 96 | origin: "seed", trusted: true, username: "alice", email: "[email protected]", | |
| 97 | password: "a-good-passphrase", adminIfFirst: true, | |
| 98 | }); | |
| 99 | if (!a.ok) throw new Error(a.error); | |
| 100 | alice = a.value; | |
| 101 | cookie = ( | |
| 102 | (await fetch(`${base}/signin`, { | |
| 103 | method: "POST", | |
| 104 | body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), | |
| 105 | redirect: "manual", | |
| 106 | })).headers.get("set-cookie") ?? "" | |
| 107 | ).split(";")[0]!; | |
| 108 | const made = await createRepo(app, alice, { name: "garden", visibility: "public", description: "d" }); | |
| 109 | if (!made.ok) throw new Error(String(made.error)); | |
| 110 | repo = made.value; | |
| 111 | const seeded = await commitToBranch(app, alice, repo, { | |
| 112 | message: "Start", | |
| 113 | files: [ | |
| 114 | { path: "package.json", content: '{"name":"garden","scripts":{"start":"bun run server.ts"}}\n' }, | |
| 115 | { path: "server.ts", content: "Bun.serve({ port: Number(process.env.PORT), fetch: () => new Response('ok') });\n" }, | |
| 116 | ], | |
| 117 | }); | |
| 118 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 119 | const enabled = await enableApp(app, alice, repo, { slug: "garden" }); | |
| 120 | if (!enabled.ok) throw new Error(String(enabled.error)); | |
| 121 | const agent = await createAgent(app, alice, { username: "keeper" }); | |
| 122 | if (!agent.ok) throw new Error(String(agent.error)); | |
| 123 | expect(addToCrew(app, alice, repo, "keeper").ok).toBe(true); | |
| 124 | }); | |
| 125 | ||
| 126 | afterAll(async () => { | |
| 127 | servers.stop(); | |
| 128 | app.close(); | |
| 129 | await rm(dataDir, { recursive: true, force: true }); | |
| 130 | }); | |
| 131 | ||
| 132 | test("while the crew can go on, nothing is offered", async () => { | |
| 133 | // No credit file and no key: the crew has nothing to run on, so seed a key-less | |
| 134 | // forge with credit left. | |
| 135 | writeFileSync(join(dataDir, "parent.json"), JSON.stringify({ credit: { token: "bearer-token-123", capUsd: 5, spentUsd: 1 } })); | |
| 136 | const pull = await pullWith("ok"); | |
| 137 | const page = await get(`/alice/garden/pulls/${pull.number}`); | |
| 138 | expect(page).not.toContain("data-land-as-is"); | |
| 139 | expect(await get(`/alice/garden/pulls/${pull.number}/files`)).not.toContain("data-land-as-is"); | |
| 140 | }); | |
| 141 | ||
| 142 | test("credit runs out after a green pull: the sentence, the button, the preview and the key on both pages; pressing it lands", async () => { | |
| 143 | const pull = await pullWith("ok"); | |
| 144 | spendCredit(); | |
| 145 | const sentence = "The crew cannot go on: the included credit is spent."; | |
| 146 | for (const path of [`/alice/garden/pulls/${pull.number}`, `/alice/garden/pulls/${pull.number}/files`, "/alice/garden"]) { | |
| 147 | const page = await get(path); | |
| 148 | expect(page).toContain(sentence); | |
| 149 | expect(page).toContain(LAND_AS_IS); | |
| 150 | expect(page).toContain(`action="/alice/garden/pulls/${pull.number}/ship"`); | |
| 151 | expect(page).toContain(`/alice/garden/app/pull-${pull.number}/open`); | |
| 152 | expect(page).toContain('href="/settings/subscriptions"'); | |
| 153 | } | |
| 154 | const card = (await get(`/alice/garden/pulls/${pull.number}`)).split("data-land-as-is")[1]!.split("</form>")[0]!.toLowerCase(); | |
| 155 | for (const word of STRANGER_NEVER_SEES) expect(card.includes(word)).toBe(false); | |
| 156 | ||
| 157 | const pressed = await fetch(`${base}/alice/garden/pulls/${pull.number}/ship`, { | |
| 158 | method: "POST", | |
| 159 | headers: { cookie, origin: "https://evil.example" }, | |
| 160 | redirect: "manual", | |
| 161 | }); | |
| 162 | expect(pressed.status).toBe(403); // same-origin check: a foreign origin lands nothing | |
| 163 | expect(getPull(app.db, repo.id, pull.number)?.mergedAt).toBeNull(); | |
| 164 | const landed = await fetch(`${base}/alice/garden/pulls/${pull.number}/ship`, { | |
| 165 | method: "POST", | |
| 166 | headers: { cookie, origin: base }, | |
| 167 | redirect: "manual", | |
| 168 | }); | |
| 169 | expect(landed.status).toBe(303); | |
| 170 | expect(getPull(app.db, repo.id, pull.number)?.mergedAt).not.toBeNull(); | |
| 171 | }); | |
| 172 | ||
| 173 | test("a red pull is never offered it", async () => { | |
| 174 | spendCredit(); | |
| 175 | const pull = await pullWith("failed"); | |
| 176 | const page = await get(`/alice/garden/pulls/${pull.number}`); | |
| 177 | expect(page).not.toContain("data-land-as-is"); | |
| 178 | expect(await get(`/alice/garden/pulls/${pull.number}/files`)).not.toContain("data-land-as-is"); | |
| 179 | }); | |
| 180 | ||
| 181 | test("MCP merge action land: a green pull lands squashed, a red one is check_required, the plan carries crew", async () => { | |
| 182 | spendCredit(); | |
| 183 | const rw = createToken(app.db, alice.id, "rw", "rw").token; | |
| 184 | const green = await pullWith("ok"); | |
| 185 | const plan = await mcp(rw, { repo: "alice/garden", number: green.number, action: "land" }); | |
| 186 | expect(plan.value.crew).toBe("The crew cannot go on: the included credit is spent."); | |
| 187 | expect(getPull(app.db, repo.id, green.number)?.mergedAt).toBeNull(); | |
| 188 | const landed = await mcp(rw, { repo: "alice/garden", number: green.number, action: "land", dryRun: false }); | |
| 189 | expect(landed.value.strategy).toBe("squash"); | |
| 190 | expect(getPull(app.db, repo.id, green.number)?.mergedAt).not.toBeNull(); | |
| 191 | ||
| 192 | const red = await pullWith("failed"); | |
| 193 | const refused = await mcp(rw, { repo: "alice/garden", number: red.number, action: "land", dryRun: false }); | |
| 194 | expect(refused.error).toContain("check_required"); | |
| 195 | expect(getPull(app.db, repo.id, red.number)?.mergedAt).toBeNull(); | |
| 196 | }); | |
| 197 | ||
| 198 | test("the app page says it once and gives one row per green pull; the terminal lists the same pulls", async () => { | |
| 199 | spendCredit(); | |
| 200 | const a = await pullWith("ok"); | |
| 201 | const b = await pullWith("ok"); | |
| 202 | const page = await get("/alice/garden"); | |
| 203 | expect(page.split("The crew cannot go on").length - 1).toBe(1); | |
| 204 | expect(page).toContain(`action="/alice/garden/pulls/${a.number}/ship"`); | |
| 205 | expect(page).toContain(`action="/alice/garden/pulls/${b.number}/ship"`); | |
| 206 | const rows = landable(app, alice, repo).map((p) => p.number); | |
| 207 | expect(rows).toContain(a.number); | |
| 208 | expect(rows).toContain(b.number); | |
| 209 | const session = { app, user: alice } as any; | |
| 210 | const ctx = { push() {}, toast() {}, invalidate() {} } as any; | |
| 211 | expect(landCommands(session, ctx, repo).map((c) => c.id)).toEqual(["land-as-is"]); | |
| 212 | expect(landCommands(session, ctx, undefined)).toEqual([]); | |
| 213 | // The crew can go on again: nothing is offered, in the terminal either. | |
| 214 | writeFileSync(join(dataDir, "parent.json"), JSON.stringify({ credit: { token: "bearer-token-123", capUsd: 5, spentUsd: 1 } })); | |
| 215 | expect(landCommands(session, ctx, repo)).toEqual([]); | |
| 216 | }); | |
| 217 | ||
| 218 | test("a writer who is not an admin sees why there is no key link, and signed out is offered nothing", async () => { | |
| 219 | spendCredit(); | |
| 220 | const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 221 | if (!bob.ok) throw new Error(bob.error); | |
| 222 | promote(app.db, bob.value); | |
| 223 | const bobCookie = ((await fetch(`${base}/signin`, { method: "POST", body: new URLSearchParams({ username: "bob", password: "a-good-passphrase" }), redirect: "manual" })).headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 224 | const made = await createRepo(app, bob.value, { name: "bobs", visibility: "public", description: "d" }); | |
| 225 | if (!made.ok) throw new Error(String(made.error)); | |
| 226 | const seeded = await commitToBranch(app, bob.value, made.value, { message: "Start", files: [{ path: "a.md", content: "a\n" }] }); | |
| 227 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 228 | const pull = await pullWith("ok", bob.value, made.value); | |
| 229 | const page = await fetch(`${base}/bob/bobs/pulls/${pull.number}`, { headers: { cookie: `${bobCookie}; forge_mode=studio` } }).then((r) => r.text()); | |
| 230 | expect(page).toContain(LAND_AS_IS); | |
| 231 | expect(page).toContain("Only this forge's admin can add a key."); | |
| 232 | expect(page).not.toContain('href="/settings/subscriptions"'); | |
| 233 | // Signed out, nothing is offered. | |
| 234 | expect(landable(app, undefined, made.value)).toEqual([]); | |
| 235 | }); | |
| 236 | }); |
new above
offline