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

A repository's own crew can be switched off: no builder or planner run starts on it, and its page says so in one line #13688

Merged opened this

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

Merged

scout/forge:scout/13644-a-repository-s-own-crew-can-be-switched → main 4 commits fork 1 thread · 1 unresolved

  • Merged. scout/13644-a-repository-s-own-crew-can-be-switched was merged into main as f31d579.

Review

Sign in to review this change.
15 files changed +434 −7
docs/features/README.md +1
@@ -97,6 +97,7 @@ Read with the guide page [Tell the crew](../guide-tell-the-crew.md).
9797 - [A bug closes with a reason](bug-close.md)
9898 - [A business, as a map](atlas-plan.md)
9999 - [A maintainer keeps the code easy to change, and nothing else](crew-maintainer.md)
100 - [Switch a repository's crew off](crew-switch.md)
100101 - [A new app starts the crew on it](new-app-crew.md)
101102 - [A new forge builds at once](starter-crew.md)
102103 - [A new issue from any page](new-issue-anywhere.md)
docs/features/crew-switch.md added +11
@@ -0,0 +1,11 @@
1 # Switch a repository's crew off
2
3 A repository's admin can stop its crew building there without removing anyone. The switch is **Crew builds here**, on by default.
4
5 - **Web:** Settings → General → Crew builds here; untick and save. Off, the switch's reason is the one line that says so.
6 - **Terminal:** open the repository, then the palette's *Crew builds here*; Space turns it off or on. Only the repository's admins (people, never agents) see the command.
7 - **Off:** no builder or planner run starts on the repository, however it is asked. The tick holds every ready issue as `crew_off` and the map says "crew off for this repository"; the planner's pass says the same and plans nothing. Redirecting a wave proposal to the planner is refused with the same line before anything is written.
8 - **Carries on:** reviews, a child forge's proposals (they open as pulls and are reviewed), wave proposals already written, and the release keeper.
9 - Each change is a `repo.settings_updated` event: the settings row says who changed it last, and an open settings page and the terminal screen both follow it.
10 - Both doors write through `setCrewHere` in `src/actions/crew_switch.ts`; the row is `src/core/crew_switch.ts`.
11 - Tests: `test/crew-switch.test.ts`, `test/settings-lines.test.ts`.
src/actions/crew_switch.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * A repository admin turns `crew builds here` on or off (#13644). The settings page and any later
3 * door share this gate; each change is a `repo.settings_updated` event naming `crewHere`, the
4 * receipt the settings row ("last changed by") and the activity show.
5 */
6
7 import type { App } from "../app.ts";
8 import { crewBuildsHere, setCrewBuildsHere } from "../core/crew_switch.ts";
9 import { canAdmin, type Repo } from "../core/repos.ts";
10 import type { User } from "../core/users.ts";
11 import { err, ok, type Result } from "../kernel/result.ts";
12
13 export function setCrewHere(app: App, actor: User | undefined, repo: Repo, on: boolean): Result<{ on: boolean; changed: boolean }, "not_found"> {
14 // A person's switch: an agent never turns its own crew on or off.
15 if (actor === undefined || actor.kind === "agent" || !canAdmin(app.db, repo, actor)) return err("not_found");
16 const changed = setCrewBuildsHere(app.db, repo.id, on, actor.id, new Date());
17 if (changed)
18 app.bus.append({
19 kind: "repo.settings_updated",
20 repoId: repo.id,
21 actorId: actor.id,
22 payload: { changed: { crewHere: { from: !on, to: on } } },
23 });
24 return ok({ on: crewBuildsHere(app.db, repo.id), changed });
25 }
26
27 export const crewHereSaid = (on: boolean): string =>
28 on ? "Crew builds here: on. Builders and the planner start again." : "Crew builds here: off. No builder or planner run starts here.";
src/actions/proposals.ts +3
@@ -11,6 +11,7 @@
1111
1212 import type { App } from "../app.ts";
1313 import { listCrewRoles } from "../core/agents.ts";
14 import { CREW_OFF_LINE, crewBuildsHere } from "../core/crew_switch.ts";
1415 import { getProposal, moveProposal, type Proposal, type ProposalState } from "../core/proposals.ts";
1516 import { ARCHIVED_WHY, getRepoById, ownerFactRepoIds, canRead, type Repo } from "../core/repos.ts";
1617 import type { User } from "../core/users.ts";
@@ -98,6 +99,8 @@ export function redirectProposal(
9899 if (repo.archivedAt !== null) return fail("invalid", ARCHIVED_WHY);
99100 const planner = listCrewRoles(app.db, repo.id).find((c) => c.role === "planner")?.agent;
100101 if (planner === undefined) return fail("invalid", "no planner on this crew to hand it to");
102 // `crew builds here` off refuses the planner's run (#13644): said now, not lost.
103 if (!crewBuildsHere(app.db, repo.id)) return fail("invalid", CREW_OFF_LINE);
101104 const direction = ensureDirectionIssue(app, found.value.actor, repo);
102105 if (!direction) return fail("invalid", "this app has no direction issue to plan from");
103106 if (!moveProposal(app.db, proposal.id, ["pending", "later"], "redirected"))
src/core/crew_switch.ts added +29
@@ -0,0 +1,29 @@
1 /**
2 * `crew builds here` (#13644): a repository's switch for its own crew. On (no row) is the default;
3 * off (a `repo_crew_off` row) means no builder or planner run starts on it — the tick picks
4 * nothing and plans nothing, and the dispatcher refuses a new builder or planner run however it
5 * was asked. Reviewers, a child's proposals and the release keeper are not the crew's builds and
6 * carry on. A switch, not a deletion: the crew stays on the repository. Plain data in and out.
7 */
8
9 import type { Database } from "bun:sqlite";
10
11 /** The map's held reason, and the tick's word for it. */
12 export const CREW_OFF_HELD = "crew_off" as const;
13 /** What the map and the pages say of a ready issue while the switch is off. */
14 export const CREW_OFF_WORDS = "crew off for this repository";
15 /** The one line the settings page says while it is off. */
16 export const CREW_OFF_LINE = "Crew builds here: off. No builder or planner run starts on this repository; reviews, a child's proposals and releases carry on.";
17
18 export function crewBuildsHere(db: Database, repoId: string): boolean {
19 return db.query<{ n: number }, [string]>("SELECT 1 AS n FROM repo_crew_off WHERE repo_id = ?1").get(repoId) === null;
20 }
21
22 /** Switch it; true when that changed anything. */
23 export function setCrewBuildsHere(db: Database, repoId: string, on: boolean, actorId: string, now: Date): boolean {
24 if (on) return db.query("DELETE FROM repo_crew_off WHERE repo_id = ?1").run(repoId).changes > 0;
25 return (
26 db.query("INSERT OR IGNORE INTO repo_crew_off (repo_id, set_by, set_at) VALUES (?1, ?2, ?3)").run(repoId, actorId, now.toISOString())
27 .changes > 0
28 );
29 }
src/core/migration-pins/20261115150000-crew-off.pin added +1
@@ -0,0 +1,1 @@
1 e46e0ae7e9d245790865b5a4563f7ad0cb26b62b8bc64acfd2b071b7ce2815a5
src/core/migrations/20261115150000-crew-off.ts added +9
@@ -0,0 +1,9 @@
1 // A repository's own crew can be switched off (#13644): one row per repository whose admin
2 // turned `crew builds here` off; no row is on, the default. Additive.
3 export default `
4 CREATE TABLE IF NOT EXISTS repo_crew_off (
5 repo_id TEXT PRIMARY KEY REFERENCES repo(id) ON DELETE CASCADE,
6 set_by TEXT NOT NULL,
7 set_at TEXT NOT NULL
8 );
9 `;
src/crew/autonomy.ts +2
@@ -117,6 +117,7 @@ import { handedOverPulls, SKIP_SUMMARY, skipsReplan } from "./guard.ts";
117117 import { type Held, heldBy, heldWords, replannable } from "./held.ts";
118118 import { forgetBacklog, noteBacklog, waitingBy, waitingWords } from "./backlog.ts";
119119 import { ceilingHold, pausedUntil, pauseSentence } from "../core/planner_pause.ts";
120 import { CREW_OFF_WORDS, crewBuildsHere } from "../core/crew_switch.ts";
120121 import { holdHot, hotFiles, hotWords, learnPullFiles } from "./hot_files.ts";
121122 import { landedUnder, NO_PULL, stallReason } from "./stalls.ts";
122123 import { alreadyDone, BY_CREW, DONE_LIKE } from "../core/done_on_main.ts";
@@ -822,6 +823,7 @@ async function planIfThin(
822823 // planner splitting it is how work starts landing again.
823824 // The owner's switch and ceiling stop the planner's run where it is queued (`dispatch.ts`). The
824825 // tick says which one holds it, and gives the planner nothing the dispatcher would refuse.
826 if (!crewBuildsHere(app.db, repo.id)) return notPlanned(repo, CREW_OFF_WORDS);
825827 const until = pausedUntil(app.db, repo.id, now);
826828 if (until !== null) return notPlanned(repo, pauseSentence(until));
827829 const ceiling = splitPending(app, repo) ? null : ceilingHold(app.db, repo.id);
src/crew/dispatch.ts +7
@@ -30,6 +30,7 @@ import { addComment, splitPending } from "../actions/issues.ts";
3030 import { planAnotherRound } from "../actions/give_back.ts";
3131 import { announceRun } from "../actions/runs.ts";
3232 import { crewRole, getAgent, type Agent } from "../core/agents.ts";
33 import { crewBuildsHere } from "../core/crew_switch.ts";
3334 import { LANDED_LEAD } from "../core/done_on_main.ts";
3435 import type { ForgeEvent } from "../core/events.ts";
3536 import {
@@ -495,6 +496,12 @@ export function queueAgentRun(
495496 (ceilingHold(app.db, repo.id) !== null && !splitPending(app, repo)))
496497 )
497498 return undefined;
499 // `crew builds here` off (#13644): no builder or planner run starts on this repository, however
500 // it was asked; one already going (`again`) finishes. Reviewers carry on.
501 if (again === undefined && !crewBuildsHere(app.db, repo.id)) {
502 const role = crewRole(app.db, repo.id, agent.user.id);
503 if (role === "builder" || role === "planner") return undefined;
504 }
498505 // A chapter is open (#11603): builders and reviewers start only what it holds, and the crew rests
499506 // between chapters. A planner plans (its scope is kept where it opens issues); a run carrying on
500507 // finishes.
src/crew/held.ts +8
@@ -21,6 +21,8 @@
2121 * - `no_model_key`: no model key or account reaches this repository, so no run
2222 * would start (`no_key.ts`): every ready issue waits, ready and unparked,
2323 * until a key is added.
24 * - `crew_off`: the repository's admin switched `crew builds here` off
25 * (`core/crew_switch.ts`): no builder or planner run starts on it.
2426 * - `stalled`: a builder ran on it and left without a pull, and nobody
2527 * who directs the crew has spoken since. The next tick parks it in the
2628 * crew's name, which frees it (`stalls.ts`).
@@ -57,6 +59,7 @@ import { capReached, capReachedFor, runCapOf } from "./guard.ts";
5759 import { interruptionOf } from "./interrupted.ts";
5860 import { landedUnanswered } from "./landed.ts";
5961 import { NO_KEY_HELD, repoHasNoKey } from "./no_key.ts";
62 import { CREW_OFF_HELD, CREW_OFF_WORDS, crewBuildsHere } from "../core/crew_switch.ts";
6063 import { PARK_STRIKES, parkedCount } from "./parks.ts";
6164 import { retryReason } from "./retry.ts";
6265 import { heldFiles, type FileHold } from "./file_holds.ts";
@@ -74,6 +77,7 @@ export const HOLDS = [
7477 "done_on_main",
7578 "landed",
7679 NO_KEY_HELD,
80 CREW_OFF_HELD,
7781 "stalled",
7882 "run_cap",
7983 "parked_twice",
@@ -199,6 +203,8 @@ export function heldBy(
199203 const handed = withPlanner(app.db, repo);
200204 // Asked once for the pass, and only when a builder could otherwise start something.
201205 const noKey = ready.length > 0 && repoHasNoKey(app.db, repo, crew.filter((c) => c.role === "builder").map((c) => c.agent.user.id));
206 // `crew builds here` off (#13644): every ready issue waits, asked once for the pass.
207 const crewOff = ready.length > 0 && !crewBuildsHere(app.db, repo.id);
202208 const hot = hotFiles(repo.id, admit);
203209 const pins = new Map(heldFiles(app.db, repo.id).map((h) => [h.path, h]));
204210 const pinned = new Map<number, FileHold>();
@@ -256,6 +262,7 @@ export function heldBy(
256262 if (alreadyDone(app.db, [issue.id]).has(issue.id)) return "done_on_main";
257263 if (landedUnanswered(app.db, repo, issue) !== undefined) return "landed";
258264 if (noKey) return NO_KEY_HELD;
265 if (crewOff) return CREW_OFF_HELD;
259266 if (stalled(app, repo, issue, lastRuns)) return "stalled";
260267 if (capped().get(issue.id) ?? atRunCap(app, repo, issue)) return "run_cap";
261268 if (!isGo(repo) && parkedCount(app.db, repo, issue.id) >= PARK_STRIKES && retryReason(app.db, repo, issue, now) === undefined)
@@ -360,6 +367,7 @@ const HOLD_WORDS: Readonly<Record<HoldName, string>> = {
360367 done_on_main: "found done on the base branch; waits for a person to close it",
361368 landed: "a merged pull closes it with boxes unticked; waits for a person",
362369 [NO_KEY_HELD]: "this forge has no model key; it starts when one is added",
370 [CREW_OFF_HELD]: CREW_OFF_WORDS,
363371 stalled: "a builder ran on it and left without a pull",
364372 run_cap: "it has used its runs for the day",
365373 parked_twice: "parked twice; it is the planner's",
src/tui/screens/crewswitch.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * Crew builds here, in the terminal (#13644): the settings page's switch through the same
3 * `setCrewHere` (`actions/crew_switch.ts`), behind the same gate, a repository's admin who is a
4 * person. Space or Enter flips it. The write is a `repo.settings_updated` event on the bus, so an
5 * open settings page redraws, and this screen follows a change made there.
6 */
7
8 import { crewHereSaid, setCrewHere } from "../../actions/crew_switch.ts";
9 import { CREW_OFF_LINE, crewBuildsHere } from "../../core/crew_switch.ts";
10 import { canAdmin, type Repo } from "../../core/repos.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import { binding } from "../app/keys.ts";
13 import type { Command } from "../app/palette.ts";
14 import type { Session } from "../session.ts";
15 import { style } from "../term/style.ts";
16 import { drawLines, live, Scroll } from "./common.ts";
17
18 const NOT_YOURS = "An admin of this repository switches its crew.";
19
20 /** The settings page's gate: an admin of the repository, never an agent. */
21 export const maySwitchCrew = (f: Session, repo: Repo): boolean =>
22 f.user !== undefined && f.user.kind !== "agent" && canAdmin(f.db, repo, f.user);
23
24 /** What the screen says: the switch's state, and the key that flips it for whoever may. */
25 export function crewSwitchLines(f: Session, repo: Repo): string[] {
26 if (!maySwitchCrew(f, repo)) return [NOT_YOURS];
27 return crewBuildsHere(f.db, repo.id)
28 ? ["Crew builds here: on. Its builders and planner pick its ready issues.", "Space turns it off."]
29 : [CREW_OFF_LINE, "Space turns it on."];
30 }
31
32 export function crewSwitchScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
33 return {
34 title: `${repo.ownerName}/${repo.name} — Crew builds here`,
35 keys: [binding(["enter", "space"], "turn on or off"), binding(["esc", "q"], "back")],
36 async load(signal) {
37 live(f, signal, { repoId: repo.id, where: (e) => e.kind === "repo.settings_updated" }, () => ctx.invalidate());
38 },
39 render(area, s) {
40 const c = ctx.theme.c;
41 drawLines(s, area, c, new Scroll(), crewSwitchLines(f, repo).map((text) => [{ text, style: style(c.fg, c.bg) }]));
42 },
43 key(e) {
44 if (e.ctrl || e.alt) return true;
45 if (e.key === "esc" || e.key === "q") ctx.pop();
46 else if (e.key === "enter" || e.key === " " || e.key === "space") {
47 const set = setCrewHere(f.app, f.user, repo, !crewBuildsHere(f.db, repo.id));
48 if (set.ok) ctx.toast(crewHereSaid(set.value.on));
49 else ctx.toast(NOT_YOURS, "danger");
50 } else return false;
51 ctx.invalidate();
52 return true;
53 },
54 };
55 }
56
57 /** The palette's command while a repository the viewer administers is open. */
58 export function crewSwitchCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
59 if (repo === undefined || !maySwitchCrew(f, repo)) return [];
60 return [
61 {
62 id: "crew-builds-here",
63 title: `${repo.ownerName}/${repo.name} — Crew builds here`,
64 hint: "switch this repository's builders and planner off, or on again",
65 run: () => ctx.push(crewSwitchScreen(f, ctx, repo)),
66 },
67 ];
68 }
src/tui/screens/workspace.ts +2
@@ -185,6 +185,7 @@ import { autonomyCommands } from "./autonomy.ts";
185185 import { trafficCommands } from "./trafficview.ts";
186186 import { chaptersCommands } from "./chapters.ts";
187187 import { outsideAgentsCommands } from "./outsideagents.ts";
188 import { crewSwitchCommands } from "./crewswitch.ts";
188189 import { walletCapCommands } from "./wallet.ts";
189190 import { settingHistoryCommands } from "./settinghistory.ts";
190191 import { templateCommands } from "./template.ts";
@@ -2197,6 +2198,7 @@ export function workspaceScreen(
21972198 ...recheckWindowCommands(f, ctx, repo, () => screen),
21982199 ...deskCommands(f, ctx, repo),
21992200 ...outsideAgentsCommands(f, ctx, repo),
2201 ...crewSwitchCommands(f, ctx, repo),
22002202 ...walletCapCommands(f, ctx, repo),
22012203 ...templateCommands(f, ctx, repo),
22022204 ...settingHistoryCommands(f, ctx, repo),
src/web/pages/settings.ts +22 −1
@@ -127,6 +127,8 @@ import { proposalTokensSection } from "./proposal-tokens.ts";
127127 import { secretsSection } from "./secrets.ts";
128128 import { checkMemoryAt } from "../../apps/check-memory.ts";
129129 import { followSourcesCard, followUpstreamCard } from "./upstream-follow.ts";
130 import { crewHereSaid, setCrewHere } from "../../actions/crew_switch.ts";
131 import { CREW_OFF_LINE, crewBuildsHere } from "../../core/crew_switch.ts";
130132
131133 type Section =
132134 | "general"
@@ -270,6 +272,7 @@ export async function settingsPage(
270272 if (!branches.includes(repo.defaultBranch))
271273 branches.unshift(repo.defaultBranch);
272274
275 const crewHere = crewBuildsHere(ctx.app.db, repo.id);
273276 // Each row says who last changed it and when, from the settings record.
274277 const last = lastChanges(ctx.app.db, repo.id);
275278 const lineOf = (name: string, body: Html, reason: string | Html): Html => settingLine(name, body, reason, last.get(name));
@@ -304,6 +307,11 @@ export async function settingsPage(
304307 ${toggleOf("crewOutsiders", "Outsiders may trigger the crew", repo.crewOutsiders,
305308 "Anyone signed in who can read this repository starts and steers runs by commenting, on your budget. Off, only people who can write here direct the crew; anyone else's words stay on the thread. Turning it on or off is recorded in the activity.",
306309 "crewOutsidersShown")}
310 ${toggleOf("crewHere", "Crew builds here", crewHere,
311 crewHere
312 ? "On, this repository's builders and planner pick its ready issues. Off, none starts and the map says crew off for this repository; reviews, a child's proposals and releases carry on. A switch, not a removal: the crew stays on."
outdated

Principle 1: this line repeats the reason the toggle above already gives. Say it once.

313 : CREW_OFF_LINE,
314 "crewHereShown")}
307315 ${lineOf("polishShare", html`<input type="hidden" name="polishShareShown" value="1" />
308316 <label for="polish-share">Polish share, percent (0 to ${String(POLISH_SHARE_MAX)})</label>
309317 <input
@@ -473,6 +481,12 @@ export async function settingsUpdate(ctx: Ctx): Promise<Response> {
473481 };
474482 // The template mark has a form of its own (the App pane); no other form may clear it.
475483 const mark = form.get("templateShown") !== null ? { template: form.get("template") !== null } : {};
484 // `crew builds here` (#13644) is its own row, not the repository's; only a form that draws it
485 // reads it.
486 const crewHere =
487 form.get("crewHereShown") !== null && card !== "about" && card !== "template"
488 ? setCrewHere(ctx.app, ctx.auth.user, repo, form.get("crewHere") !== null)
489 : undefined;
476490 const updated = await updateRepoSettings(
477491 ctx.app,
478492 ctx.auth.user,
@@ -480,7 +494,14 @@ export async function settingsUpdate(ctx: Ctx): Promise<Response> {
480494 card === "template" ? mark : card === "about" ? about : card === "gates" ? gates : { ...about, ...gates },
481495 );
482496 const flash: Flash = updated.ok
483 ? { message: card === "template" && updated.value.template !== repo.template ? templateSaid(updated.value.template) : "Settings saved." }
497 ? {
498 message:
499 card === "template" && updated.value.template !== repo.template
500 ? templateSaid(updated.value.template)
501 : crewHere?.ok === true && crewHere.value.changed
502 ? `Settings saved. ${crewHereSaid(crewHere.value.on)}`
503 : "Settings saved.",
504 }
484505 : {
485506 tone: "danger",
486507 message:
test/crew-switch.test.ts added +235
@@ -0,0 +1,235 @@
1 /**
2 * `crew builds here` (#13644): switched off, a ready issue on the repository starts no run — the
3 * tick holds it as `crew_off`, the map says `crew off for this repository`, and the dispatcher
4 * refuses a builder's or a planner's run however it is asked. The change is receipted, an agent
5 * cannot flip it, and on again the same issue is picked.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
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 { addToCrew, createAgent } from "../src/actions/crew.ts";
13 import { setCrewHere } from "../src/actions/crew_switch.ts";
14 import { openIssue } from "../src/actions/issues.ts";
15 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
16 import { getAgentByName, type Agent } from "../src/core/agents.ts";
17 import { crewBuildsHere, CREW_OFF_WORDS } from "../src/core/crew_switch.ts";
18 import { getIssueById, type Issue } from "../src/core/issues.ts";
19 import { getRepoById, type Repo } from "../src/core/repos.ts";
20 import { listActiveRuns } from "../src/core/runs.ts";
21 import { createUser, type User } from "../src/core/users.ts";
22 import { driveRepo } from "../src/crew/autonomy.ts";
23 import { queueAgentRun } from "../src/crew/dispatch.ts";
24 import { heldNow, heldWords, mapHolds } from "../src/crew/held.ts";
25 import { lastChanges } from "../src/settings/last_change.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27 import { seatAs } from "./helpers/seat.ts";
28 import { openPull } from "../src/actions/pulls.ts";
29 import { proposePlan } from "../src/actions/plan.ts";
30 import { redirectProposal } from "../src/actions/proposals.ts";
31 import { getProposal } from "../src/core/proposals.ts";
32 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
33 import { createRepo as createRepoRow } from "../src/core/repos.ts";
34 import { createSession } from "../src/core/sessions.ts";
35 import { ensureDirectionIssue } from "../src/crew/autonomy.ts";
36 import { decideCut } from "../src/keeper/cadence.ts";
37 import { serve, type Servers } from "../src/http/server.ts";
38 import { createForgeApp } from "../src/tui/forge.ts";
39 import { crewSwitchCommands, crewSwitchScreen } from "../src/tui/screens/crewswitch.ts";
40 import { headlessTerminal } from "../src/tui/term/terminal.ts";
41 import { settleApp } from "./helpers/tui.ts";
42
43 quietLogs();
44
45 let dataDir: string;
46 let app: App;
47 let alice: User;
48 let repo: Repo;
49 let issue: Issue;
50 let builder: Agent;
51 let planner: Agent;
52 let reviewer: Agent;
53 let servers: Servers;
54
55 const fresh = () => getRepoById(app.db, repo.id)!;
56
57 beforeAll(async () => {
58 dataDir = await mkdtemp(join(tmpdir(), "forge-crew-switch-"));
59 app = createApp({ dataDir, port: 0 });
60 const a = await createUser(app.db, {
61 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
62 password: "a-good-passphrase", adminIfFirst: true,
63 });
64 if (!a.ok) throw new Error(a.error);
65 alice = a.value;
66 const made = await createRepo(app, alice, { name: "notes", visibility: "public" });
67 if (!made.ok) throw new Error(String(made.error));
68 repo = made.value;
69 const first = await commitToBranch(app, alice, repo, {
70 message: "Start",
71 files: [{ path: "package.json", content: `{"name":"notes"}\n` }],
72 });
73 if (!first.ok) throw new Error(JSON.stringify(first.error));
74 for (const name of ["b1", "p1", "r1"]) {
75 const made = await createAgent(app, alice, { username: name });
76 if (!made.ok) throw new Error(String(made.error));
77 expect(addToCrew(app, alice, repo, name).ok).toBe(true);
78 }
79 builder = getAgentByName(app.db, "b1")!;
80 planner = getAgentByName(app.db, "p1")!;
81 expect(seatAs(app.db, repo.id, planner.user.id, "planner")).toBe(true);
82 reviewer = getAgentByName(app.db, "r1")!;
83 expect(seatAs(app.db, repo.id, reviewer.user.id, "reviewer")).toBe(true);
84 servers = await serve(app);
85 const on = await updateRepoSettings(app, alice, repo, {
86 autonomy: "autonomous",
87 autonomyDirection: "Keep the notes tidy.",
88 autonomySlots: 1,
89 autonomyBy: alice.id,
90 });
91 expect(on.ok).toBe(true);
92 const opened = openIssue(app, alice, fresh(), { title: "Rename a note" });
93 if (!opened.ok) throw new Error(String(opened.error));
94 issue = opened.value;
95 });
96
97 afterAll(async () => {
98 servers.stop();
99 await rm(dataDir, { recursive: true, force: true });
100 });
101
102 describe("crew builds here", () => {
103 test("on by default", () => {
104 expect(crewBuildsHere(app.db, repo.id)).toBe(true);
105 });
106
107 test("an agent cannot switch it", () => {
108 expect(setCrewHere(app, builder.user, fresh(), false).ok).toBe(false);
109 expect(crewBuildsHere(app.db, repo.id)).toBe(true);
110 });
111
112 test("off: the ready issue is held as crew_off and the map says so", () => {
113 const off = setCrewHere(app, alice, fresh(), false);
114 expect(off.ok && off.value).toEqual({ on: false, changed: true });
115 const held = heldNow(app, fresh());
116 expect(held.startable).toHaveLength(0);
117 expect(heldWords(held)).toContain("crew_off=");
118 const holds = mapHolds(fresh(), held);
119 expect([...holds.holds.values()].map((h) => h.detail)).toContain(CREW_OFF_WORDS);
120 });
121
122 test("off: the tick starts no run and the dispatcher refuses a builder and a planner", async () => {
123 expect(await driveRepo(app, fresh())).not.toBe("picked");
124 expect(listActiveRuns(app.db, [repo.id])).toHaveLength(0);
125 expect(getIssueById(app.db, issue.id)!.assigneeId).toBeNull();
126 expect(queueAgentRun(app, fresh(), issue, builder, "assigned", alice.id)).toBeUndefined();
127 expect(queueAgentRun(app, fresh(), issue, planner, "assigned", alice.id)).toBeUndefined();
128 });
129
130 test("the change is receipted on the settings row", () => {
131 expect(lastChanges(app.db, repo.id).get("crewHere")?.by).toContain("alice");
132 });
133
134 test("on again: the same issue is picked", async () => {
135 const on = setCrewHere(app, alice, fresh(), true);
136 expect(on.ok && on.value).toEqual({ on: true, changed: true });
137 expect(heldWords(heldNow(app, fresh()))).not.toContain("crew_off");
138 expect(await driveRepo(app, fresh())).toBe("picked");
139 });
140 });
141
142 describe("crew builds here, off: what carries on", () => {
143 beforeAll(() => {
144 expect(setCrewHere(app, alice, fresh(), false).ok).toBe(true);
145 });
146
147 test("a child's proposal opens as a pull, and its review run starts", async () => {
148 const pushed = await commitToBranch(app, alice, fresh(), {
149 branch: "from-child",
150 message: "From the child",
151 files: [{ path: "child.md", content: "proposed\n" }],
152 });
153 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
154 const pull = await openPull(app, alice, fresh(), { title: "Proposed from a child forge", baseBranch: "main", headBranch: "from-child" });
155 if (!pull.ok) throw new Error(JSON.stringify(pull.error));
156 const asked = getIssueById(app.db, pull.value.id)!;
157 expect(queueAgentRun(app, fresh(), asked, reviewer, "review")).toBeDefined();
158 // The builder still is not started on it.
159 expect(queueAgentRun(app, fresh(), asked, builder, "feedback", alice.id)).toBeUndefined();
160 });
161
162 test("a wave proposal is written; redirecting it to the planner says crew off before writing anything", () => {
163 ensureDirectionIssue(app, alice, fresh());
164 const proposed = proposePlan(app, alice, fresh(), [{ key: "a", title: "Tidy", body: "", blockedBy: [] }], { title: "Spring" });
165 if (!proposed.ok) throw new Error(JSON.stringify(proposed.error));
166 const said = redirectProposal(app, alice, proposed.value.id, "Roses first");
167 expect(said.ok).toBe(false);
168 expect(!said.ok && said.error.message).toContain("Crew builds here: off");
169 expect(getProposal(app.db, proposed.value.id)!.state).toBe("pending");
170 });
171
172 test("the release keeper cuts: its cadence reads main and its own holds, not the switch", () => {
173 expect(crewBuildsHere(app.db, repo.id)).toBe(false);
174 const cut = decideCut({ main: "b".repeat(40), newest: { version: "1.0.0", sha: "a".repeat(40) }, live: "1.0.0", inFlight: false, gating: 0, lastCutAt: undefined, hold: undefined, now: Date.now() });
175 expect(cut.cut).toBe(true);
176 });
177
178 test("a writer who is not an admin posting crewHereShown does not change it", async () => {
179 const acme = createOrg(app.db, "acme", alice.id);
180 if (!acme.ok) throw new Error(acme.error);
181 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "wren", email: "[email protected]", password: "a-good-passphrase" });
182 if (!made.ok) throw new Error(made.error);
183 const team = createTeam(app.db, acme.value.id, "devs", "write");
184 if (!team.ok) throw new Error(team.error);
185 addTeamMember(app.db, team.value, made.value.id);
186 const lib = await createRepoRow(app.db, app.reposRoot, { ownerId: acme.value.id, name: "lib", visibility: "public", description: "", defaultBranch: "main" });
187 if (!lib.ok) throw new Error(lib.error);
188 const cookie = `forge_session=${createSession(app.db, made.value.id).token}`;
189 // Ticked on by a writer: refused, and the switch an admin set off stays off.
190 expect(setCrewHere(app, alice, lib.value, false).ok).toBe(true);
191 const res = await fetch(`${servers.url}/acme/lib/settings`, {
192 method: "POST",
193 headers: { cookie, origin: servers.url },
194 body: new URLSearchParams({ card: "gates", defaultBranch: "main", crewHereShown: "1", crewHere: "on" }),
195 redirect: "manual",
196 });
197 expect(res.status).not.toBe(303);
198 expect(crewBuildsHere(app.db, lib.value.id)).toBe(false);
199 expect(setCrewHere(app, made.value, lib.value, true).ok).toBe(false);
200 expect(crewBuildsHere(app.db, lib.value.id)).toBe(false);
201 });
202
203 test("the terminal: an admin flips it with space, the event the page follows is written, and a writer has no entry", async () => {
204 const key = (k: string) => ({ type: "key" as const, key: k, ctrl: false, alt: false, shift: false });
205 const kinds: string[] = [];
206 const off = app.bus.subscribe((e) => {
207 if (e.repoId === repo.id) kinds.push(e.kind);
208 });
209 const { app: tui, session } = createForgeApp(
210 app,
211 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice },
212 { terminal: headlessTerminal(160, 30), exitHooks: false },
213 );
214 tui.start();
215 tui.ctx.push(crewSwitchScreen(session, tui.ctx, fresh()));
216 await settleApp(tui);
217 expect(tui.screen.toText()).toContain("Crew builds here: off");
218 expect(crewSwitchCommands(session, tui.ctx, fresh())).toHaveLength(1);
219 tui.dispatch(key("space"));
220 await settleApp(tui);
221 expect(crewBuildsHere(app.db, repo.id)).toBe(true);
222 expect(kinds).toContain("repo.settings_updated");
223 expect(tui.screen.toText()).toContain("Crew builds here: on");
224 off();
225 tui.stop?.();
226
227 const wren = getAgentByName(app.db, "b1")!.user;
228 const other = createForgeApp(
229 app,
230 { sshUsername: wren.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: wren },
231 { terminal: headlessTerminal(160, 30), exitHooks: false },
232 );
233 expect(crewSwitchCommands(other.session, other.app.ctx, fresh())).toEqual([]);
234 });
235 });
test/settings-lines.test.ts +8 −6
@@ -38,7 +38,7 @@ afterAll(async () => {
3838 await rm(dir, { recursive: true, force: true });
3939 });
4040
41 const KEYS = ["defaultBranch", "protect", "requireReview", "requireChecks", "landing", "crewOutsiders", "polishShare"];
41 const KEYS = ["defaultBranch", "protect", "requireReview", "requireChecks", "landing", "crewOutsiders", "crewHere", "polishShare"];
4242
4343 test("every setting key is one row inside the form that posts to /settings, reason in a details", async () => {
4444 const html = await (
@@ -63,7 +63,7 @@ test("every setting key is one row inside the form that posts to /settings, reas
6363 });
6464
6565 /** The names the form posts beside `card=gates` (matched by gatesForm): on main before #10999 they were exactly these. */
66 const POSTED = ["defaultBranch", "protect", "requireReview", "requireChecks", "landingShown", "landing", "crewOutsidersShown", "crewOutsiders", "polishShareShown", "polishShare"];
66 const POSTED = ["defaultBranch", "protect", "requireReview", "requireChecks", "landingShown", "landing", "crewOutsidersShown", "crewOutsiders", "crewHereShown", "crewHere", "polishShareShown", "polishShare"];
6767
6868 const page = async (): Promise<string> =>
6969 (await fetch(`${servers.url}/olive/proj/settings`, { headers: { cookie, accept: "text/html" } })).text();
@@ -85,16 +85,18 @@ test("the form posts the same names to the same route, and each one lands", asyn
8585 const branch = /<option value="([^"]+)" selected/.exec(before)?.[1] ?? "";
8686 expect(branch).not.toBe("");
8787
88 const on = { card: "gates", defaultBranch: branch, protect: "on", requireReview: "on", requireChecks: "on", crewOutsidersShown: "1", crewOutsiders: "on", polishShareShown: "1", polishShare: "7" };
88 const on = { card: "gates", defaultBranch: branch, protect: "on", requireReview: "on", requireChecks: "on", crewOutsidersShown: "1", crewOutsiders: "on", crewHereShown: "1", crewHere: "on", polishShareShown: "1", polishShare: "7" };
8989 expect((await post(on)).status).toBe(303);
9090 let form = gatesForm(await page());
91 for (const key of ["protect", "requireReview", "requireChecks", "crewOutsiders"]) expect(checked(form, key), key).toBe(true);
91 for (const key of ["protect", "requireReview", "requireChecks", "crewOutsiders", "crewHere"]) expect(checked(form, key), key).toBe(true);
9292 expect(form).toMatch(/name="polishShare"[^>]*value="7"/);
9393
94 const off = { card: "gates", defaultBranch: branch, crewOutsidersShown: "1", polishShareShown: "1", polishShare: "0" };
94 const off = { card: "gates", defaultBranch: branch, crewOutsidersShown: "1", crewHereShown: "1", polishShareShown: "1", polishShare: "0" };
9595 expect((await post(off)).status).toBe(303);
9696 form = gatesForm(await page());
97 for (const key of ["protect", "requireReview", "requireChecks", "crewOutsiders"]) expect(checked(form, key), key).toBe(false);
97 for (const key of ["protect", "requireReview", "requireChecks", "crewOutsiders", "crewHere"]) expect(checked(form, key), key).toBe(false);
98 // Off, the switch's reason is the one line that says so, said once (#13644).
99 expect(form.split("No builder or planner run starts on this repository").length - 1).toBe(1);
98100 expect(form).toMatch(/name="polishShare"[^>]*value="0"/);
99101 });
100102

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs