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

Archive a repository or app: spin it down, hide it from the home and the inbox, keep it reachable by link #1132

Closed opened this in answer to
Closed without merging

scout/forge:scout/1113-archive-a-repository-or-app-spin-it-down → main 12 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
44 files changed +733 −24
.bash_profile added
No content changes.
.bashrc added
No content changes.
.claude/agents added
No content changes.
.claude/commands added
No content changes.
.claude/hooks added
No content changes.
.claude/launch.json added
No content changes.
.claude/loop.md added
No content changes.
.claude/output-styles added
No content changes.
.claude/routines added
No content changes.
.claude/scheduled_tasks.json added
No content changes.
.claude/settings.json added
No content changes.
.claude/settings.local.json added
No content changes.
.claude/skills added
No content changes.
.claude/workflows added
No content changes.
.gitconfig added
No content changes.
.gitmodules added
No content changes.
.idea added
No content changes.
.mcp.json added
No content changes.
.profile added
No content changes.
.ripgreprc added
No content changes.
.vscode added
No content changes.
.zprofile added
No content changes.
.zshrc added
No content changes.
docs/APPS.md +4
@@ -1086,3 +1086,7 @@ refused), `placement` (`"metal"` or `"cloud"`, optional) and `volumes`
10861086 sync cadence in seconds, 10–86400). `src/apps/service.ts` validates it; the
10871087 manifest carries it as `service`, `null` for a web app. Running it, exposing
10881088 the ports and syncing volumes are not built yet (issue #391).
1089
1090 ## Archive
1091
1092 Settings → Danger zone → Archive (or `PATCH /api/v1/repos/:owner/:name {"archived": true}`, or the MCP `archive` tool) puts a repository to rest: its app's environments stop and their data is kept, the crew is held (no pick, no queued run, no review sweep), and it leaves the home's apps, the explorer's lists and the inbox. The page, its link and git keep working; the page says "Archived on <date>" with one button to wake it, and waking redeploys production and the open pulls' previews. The repository JSON carries `archivedAt`. From the home, "Archive apps…" selects several at once, and for a day after, the home offers one button to undo.
docs/MCP.md +1
@@ -37,6 +37,7 @@ for a tunnel and a forge that sleeps.
3737 | `health` | how this forge is: the version and commit it runs, draining or not, the rollout and its incidents | |
3838 | `audit` | who can do what, per app, read from its contract.json in git: yes, own or no per door, and whether outsiders may direct its crew (`crewOutsiders`) | |
3939 | `outsiders` | `{ repo, on?, dryRun? }`: whether people who cannot write may direct the crew; with `on`, planned first (`dryRun` is true unless `false`); set only by the app's admin with an admin token, never an agent | yes |
40 | `archive` | `{ repo, archived?, dryRun? }`: put a repository to rest (app stopped, data kept, crew held, off the lists) or wake it; planned first (`dryRun` is true unless `false`); a person who administers it, admin token, never an agent | yes |
4041 | `probe` | knock on a running app's doors as nobody, a user and an admin; the ones that disobey its contract | |
4142 | `following` | where a fork stands against what it follows, and what the crew is doing about it | |
4243 | `spawn` | `{ name, apps?, crew?, dryRun? }`: a child forge, planned first (`dryRun` is true unless `false`); an admin's, and an `ro` token may plan but not make | yes |
scripts/gate.ts +1
@@ -80,6 +80,7 @@ export const GATE: readonly string[] = [
8080 "test/dependencies.test.ts",
8181 "test/map-closing.test.ts",
8282 "test/autonomy.test.ts",
83 "test/archive.test.ts",
8384 "test/studio.test.ts",
8485 "test/studio-words.test.ts",
8586 "test/following.test.ts",
src/actions/repos.ts +72
@@ -5,6 +5,8 @@
55 */
66
77 import { requireVerified } from "./verify.ts";
8 import { appsRuntime } from "../apps/runtime.ts";
9 import { getAppByRepo } from "../core/apps.ts";
810 import type { App } from "../app.ts";
911 import { canSeeSealed } from "../core/sealed.ts";
1012 import { capacityValue } from "../core/capacity.ts";
@@ -248,6 +250,9 @@ export async function updateRepoSettings(
248250 // one on a team that administers the repository (`crew/direct.ts`).
249251 if (settings.crewOutsiders !== undefined && admin.value.kind === "agent")
250252 return err("not_found");
253 // Putting a repository to rest, or waking it, is a person's call too.
254 if (settings.archived !== undefined && admin.value.kind === "agent")
255 return err("not_found");
251256 // The work on a sealed report stays private until it merges into its
252257 // base, whoever owns it (`core/sealed.ts`).
253258 if (repo.sealedFor !== null && settings.visibility === "public")
@@ -278,6 +283,18 @@ export async function updateRepoSettings(
278283 actorId: admin.value.id,
279284 payload: { changed },
280285 });
286 // Rest is its own line in the record, and it moves the app: archiving
287 // stops every environment (the data stays), waking brings production and
288 // the open pulls' previews back (#1113).
289 if (settings.archived !== undefined && settings.archived !== (repo.archivedAt !== null)) {
290 app.bus.append({
291 kind: settings.archived ? "repo.archived" : "repo.unarchived",
292 repoId: repo.id,
293 actorId: admin.value.id,
294 payload: {},
295 });
296 await restApp(app, updated);
297 }
281298 // Who may start and steer the crew is its own line in the record, on and
282299 // off: on is a door opened to everyone who can read (`crew/direct.ts`).
283300 if (changed.includes("crewOutsiders"))
@@ -290,6 +307,61 @@ export async function updateRepoSettings(
290307 return ok(updated);
291308 }
292309
310 export interface ArchiveAnswer {
311 /** Whether the repository is archived, after this call. */
312 readonly archived: boolean;
313 /** Whether it was before it. */
314 readonly was: boolean;
315 /** Nothing changed: this was the plan. */
316 readonly dryRun: boolean;
317 }
318
319 /** Archive or wake one repository — the API's flag for the MCP, with a dry run. */
320 export async function setArchived(
321 app: App,
322 actor: User | undefined,
323 repo: Repo,
324 archived: boolean,
325 dryRun: boolean,
326 ): Promise<Result<ArchiveAnswer, "not_found">> {
327 const admin = requireRepoAdmin(app, actor, repo);
328 if (!admin.ok || admin.value.kind === "agent") return err("not_found");
329 const was = repo.archivedAt !== null;
330 if (dryRun) return ok({ archived, was, dryRun });
331 const updated = await updateRepoSettings(app, actor, repo, { archived });
332 if (!updated.ok) return err("not_found");
333 return ok({ archived: updated.value.archivedAt !== null, was, dryRun });
334 }
335
336 /** Make the app match the repository's rest: stopped, or running again. */
337 async function restApp(app: App, repo: Repo): Promise<void> {
338 const runtime = appsRuntime(app);
339 const record = getAppByRepo(app.db, repo.id);
340 if (runtime === undefined || record === undefined) return;
341 if (repo.archivedAt !== null) await runtime.stopRepo(repo.id);
342 else await runtime.reconcileApp(record, repo, "wake");
343 }
344
345 /**
346 * Archive or wake several repositories in one go — the home's select-and-
347 * archive. Each is its own admin check; the ones the actor may not touch
348 * are skipped and counted out, never named.
349 */
350 export async function setArchivedMany(
351 app: App,
352 actor: User | undefined,
353 repos: readonly Repo[],
354 archived: boolean,
355 ): Promise<number> {
356 let done = 0;
357 for (const repo of repos) {
358 if ((repo.archivedAt !== null) === archived) continue;
359 const updated = await updateRepoSettings(app, actor, repo, { archived });
360 if (updated.ok) done++;
361 }
362 return done;
363 }
364
293365 export interface OutsidersAnswer {
294366 /** Whether outsiders may trigger the crew, after this call. */
295367 readonly on: boolean;
src/apps/runtime.ts +9 −3
@@ -608,7 +608,7 @@ export class AppsRuntime {
608608 known.add(record.id);
609609 const repo = getRepoById(this.app.db, record.repoId);
610610 // A forge coming back does not restart a suspended owner's apps.
611 if (repo && accountActive(this.app.db, repo.ownerId))
611 if (repo && repo.archivedAt === null && accountActive(this.app.db, repo.ownerId))
612612 present.push({ record, repo });
613613 }
614614 for (const { record, repo } of present)
@@ -896,8 +896,13 @@ export class AppsRuntime {
896896 reason: string,
897897 actorId?: string,
898898 ): Run | undefined {
899 // A suspended or removed owner's app does not deploy.
900 if (this.stopped || !accountActive(this.app.db, repo.ownerId))
899 // A suspended or removed owner's app does not deploy, and neither does
900 // an archived one: it rests until it is woken (#1113).
901 if (
902 this.stopped ||
903 repo.archivedAt !== null ||
904 !accountActive(this.app.db, repo.ownerId)
905 )
901906 return undefined;
902907 if (!this.mayRun(record, repo, env, commitOid)) return undefined;
903908 const state = this.envFor(record, env);
@@ -1470,6 +1475,7 @@ export class AppsRuntime {
14701475 const repo = getRepoById(this.app.db, record.repoId);
14711476 // Waking runs code without a run row: the owner's standing is asked here.
14721477 if (!repo || !accountActive(this.app.db, repo.ownerId)) return undefined;
1478 if (repo.archivedAt !== null) return undefined;
14731479 // So is whose code it is: a preview asleep at a head nobody who can
14741480 // write approved — built before the gate, or approved by someone who
14751481 // can no longer write — is taken down, not woken. Approving the head
src/core/repos.ts +35 −5
@@ -116,6 +116,12 @@ export interface Repo {
116116 * default; on a public repository it hands strangers the owner's budget.
117117 */
118118 readonly crewOutsiders: boolean;
119 /**
120 * When the repository was put to rest (#1113), or null. An archived
121 * repository keeps its git, its data and its address; its app is stopped,
122 * the crew leaves it alone, and the lists that name what is live omit it.
123 */
124 readonly archivedAt: string | null;
119125 /** The issue the planner is given, when the map has run dry. */
120126 readonly directionIssueId: string | null;
121127 /** The repo this was forked from, or null. */
@@ -160,6 +166,7 @@ interface RepoRow {
160166 autonomy_slots: number;
161167 autonomy_by: string | null;
162168 crew_outsiders: number;
169 archived_at: string | null;
163170 direction_issue_id: string | null;
164171 fork_parent_id: string | null;
165172 sealed_for: string | null;
@@ -197,6 +204,7 @@ function toRepo(row: RepoRow): Repo {
197204 autonomySlots: row.autonomy_slots,
198205 autonomyBy: row.autonomy_by,
199206 crewOutsiders: row.crew_outsiders === 1,
207 archivedAt: row.archived_at,
200208 directionIssueId: row.direction_issue_id,
201209 forkParentId: row.fork_parent_id,
202210 sealedFor: row.sealed_for,
@@ -626,8 +634,22 @@ export interface ListReposOptions {
626634 cursor?: string;
627635 /** Repositories that run an app first, each half newest first (not with `cursor`). */
628636 appsFirst?: boolean;
637 /**
638 * Archived repositories (#1113): left out unless asked for. `only` is the
639 * archive's own shelf; `include` is every repository, at rest or not.
640 * @default "omit"
641 */
642 archived?: "omit" | "only" | "include";
629643 }
630644
645 /** The SQL a list adds for `archived`: a resting repository is not live. */
646 const archivedClause = (options: ListReposOptions): string =>

Defaulting to omit changes every existing caller of listReposVisibleTo, listReposWritableTo and listReposByOwner: audit, map, board, org/profile, the TUI dashboard and new-forge. Most of those are right to hide a resting repository. But nothing passes only except the 24-hour undo shelf, so after a day an archived repository is reachable only if you already know its URL. Add one archived shelf that uses only, and pass include where hiding is wrong (audit).

647 options.archived === "only"
648 ? " AND repo.archived_at IS NOT NULL"
649 : options.archived === "include"
650 ? ""
651 : " AND repo.archived_at IS NULL";
652
631653 // Visibility in SQL: public, owned, or owned by an org the viewer is on a
632654 // team of. Site admins see everything. The same rule canRead applies, so a
633655 // listing never shows a repo whose page would 404.
@@ -645,7 +667,7 @@ export function listReposVisibleTo(
645667 options: ListReposOptions = {},
646668 ): Repo[] {
647669 const params: (string | number)[] = [viewer?.id ?? ""];
648 let where = viewer ? VISIBLE : PUBLIC_VISIBLE;
670 let where = (viewer ? VISIBLE : PUBLIC_VISIBLE) + archivedClause(options);
649671 if (options.query !== undefined && options.query.trim() !== "") {
650672 params.push(`%${likeEscape(options.query.trim())}%`);
651673 const p = params.length;
@@ -679,7 +701,7 @@ export function listReposWritableTo(
679701 ): Repo[] {
680702 if (!viewer) return [];
681703 const params: (string | number)[] = [viewer.id];
682 let where = REPO_WRITABLE;
704 let where = REPO_WRITABLE + archivedClause(options);
683705 if (options.query !== undefined && options.query.trim() !== "") {
684706 params.push(`%${likeEscape(options.query.trim())}%`);
685707 const p = params.length;
@@ -710,7 +732,7 @@ export function listReposByOwner(
710732 const params: (string | number)[] = [viewer?.id ?? "", ownerName];
711733 let where = `user.username = ?2 COLLATE NOCASE AND ${
712734 viewer ? VISIBLE : PUBLIC_VISIBLE
713 }`;
735 }${archivedClause(options)}`;
714736 if (options.query !== undefined && options.query.trim() !== "") {
715737 params.push(`%${likeEscape(options.query.trim())}%`);
716738 const p = params.length;
@@ -1014,6 +1036,8 @@ export interface RepoSettings {
10141036 autonomyBy?: string | null;
10151037 /** Whether someone who cannot write here may start or steer a run. */
10161038 crewOutsiders?: boolean;
1039 /** Put the repository to rest (true) or wake it (false) — #1113. */
1040 archived?: boolean;
10171041 }
10181042
10191043 /** Update the mutable repo fields, leaving unspecified ones untouched. */
@@ -1026,7 +1050,8 @@ export function updateRepoSettings(
10261050 `UPDATE repo SET visibility = ?1, description = ?2, protect_default = ?3,
10271051 default_branch = ?4, require_review = ?5, require_checks = ?7,
10281052 autonomy = ?8, autonomy_direction = ?9, autonomy_ceiling_usd = ?10,
1029 autonomy_slots = ?11, autonomy_by = ?12, crew_outsiders = ?13
1053 autonomy_slots = ?11, autonomy_by = ?12, crew_outsiders = ?13,
1054 archived_at = ?14
10301055 WHERE id = ?6`,
10311056 ).run(
10321057 settings.visibility ?? repo.visibility,
@@ -1042,6 +1067,11 @@ export function updateRepoSettings(
10421067 settings.autonomySlots ?? repo.autonomySlots,
10431068 settings.autonomyBy === undefined ? repo.autonomyBy : settings.autonomyBy,
10441069 (settings.crewOutsiders ?? repo.crewOutsiders) ? 1 : 0,
1070 settings.archived === undefined
1071 ? repo.archivedAt
1072 : settings.archived
1073 ? (repo.archivedAt ?? new Date().toISOString())
1074 : null,
10451075 );
10461076 return getRepoById(db, repo.id)!;
10471077 }
@@ -1060,7 +1090,7 @@ export function listAutonomousRepos(db: Database): Repo[] {
10601090 .query<
10611091 RepoRow,
10621092 []
1063 >(`${SELECT} WHERE repo.autonomy != 'off' ORDER BY repo.name`)
1093 >(`${SELECT} WHERE repo.autonomy != 'off' AND repo.archived_at IS NULL ORDER BY repo.name`)
10641094 .all()
10651095 .map(toRepo);
10661096 }
src/core/schema.ts +5
@@ -1578,6 +1578,11 @@ export const migrations: readonly string[] = [
15781578 expires_at TEXT NOT NULL
15791579 );
15801580 `,
1581 // 74 — a repository at rest (#1113): when it was archived, or NULL. The
1582 // row, the git and the app's data all stay; only the running stops.
1583 `
1584 ALTER TABLE repo ADD COLUMN archived_at TEXT;
1585 `,
15811586 ];
15821587
15831588 /**
src/crew/autonomy.ts +1 −1
@@ -331,7 +331,7 @@ export async function driveRepo(
331331 repo: Repo,
332332 now = new Date(),
333333 ): Promise<Drove> {
334 if (repo.autonomy === "off") return "off";
334 if (repo.autonomy === "off" || repo.archivedAt !== null) return "off";
335335 const status = autonomyStatus(app, repo, now);
336336 if (status.paused !== null) return "paused";
337337 const by = getUserById(app.db, repo.autonomyBy!);
src/crew/dispatch.ts +2
@@ -254,6 +254,8 @@ export function queueAgentRun(
254254 ): Run | undefined {
255255 // A suspended or removed owner's repositories run nothing, whoever asks.
256256 if (!accountActive(app.db, repo.ownerId)) return undefined;
257 // An archived repository's crew is held, whoever asks (#1113).
258 if (repo.archivedAt !== null) return undefined;
257259 // The day's ceiling gates every run the crew starts on its own, not only
258260 // the picks: a review, a feedback run or a conflict run past the ceiling
259261 // is money the person did not agree to. A person's own assignment is not
src/crew/review.ts +2 −1
@@ -322,7 +322,8 @@ export async function sweepReviews(app: App): Promise<number> {
322322 const stalled = new Set<string>();
323323 for (const id of repoIds) {
324324 const repo = getRepoById(app.db, id);
325 if (!repo) continue;
325 // An archived repository's crew is held (#1113).
326 if (!repo || repo.archivedAt !== null) continue;
326327 for (const pull of openPullsOldestFirst(app.db, repo.id)) {
327328 if (queued >= SWEEP_SENDS) return forgetSettled(stalled, queued);
328329 if (!pull.authorIsAgent || !greenHead(app.db, pull)) continue;
src/design/activity.ts +2
@@ -112,6 +112,8 @@ const WORDS: Record<string, string> = {
112112 "repo.forked": "forked a repository",
113113 "repo.settings_updated": "changed repository settings",
114114 "repo.crew_outsiders": "changed who may trigger the crew",
115 "repo.archived": "archived a repository",
116 "repo.unarchived": "woke an archived repository",
115117 "repo.mirrored": "mirrored a repository",
116118 "repo.imported": "imported issues and pulls",
117119 "repo.pinned": "pinned a repository",
src/http/api.ts +4
@@ -1645,6 +1645,10 @@ export function apiRoutes(router: Router<Handler>): void {
16451645 ...(typeof input.crewOutsiders === "boolean"
16461646 ? { crewOutsiders: input.crewOutsiders }
16471647 : {}),
1648 // Rest (#1113): stops the app and holds the crew; false wakes it.
1649 ...(typeof input.archived === "boolean"
1650 ? { archived: input.archived }
1651 : {}),
16481652 });
16491653 if (!updated.ok) return respondAccess(updated.error, 422);
16501654 return json(repoJson(ctx, updated.value));
src/http/mcp.ts +43 −1
@@ -81,7 +81,7 @@ import {
8181 directionNote,
8282 OUTSIDERS_NOTE,
8383 } from "../crew/direct.ts";
84 import { setCrewOutsiders } from "../actions/repos.ts";
84 import { setArchived, setCrewOutsiders } from "../actions/repos.ts";
8585 import { mapJson, marksFor } from "../web/pages/map.ts";
8686 import { undoFleetOp } from "../actions/fleet.ts";
8787 import { applyLimb, isLimbAction, previewLimb } from "../actions/limbs.ts";
@@ -680,6 +680,48 @@ const TOOLS: readonly Tool[] = [
680680 });
681681 },
682682 },
683 {
684 name: "archive",
685 description:
686 "Put a repository to rest, or wake it. Archived: its app's environments stop (the data is kept), the crew is held, and it leaves the home, the explorer and the inbox; the page, the link and git still work, and the page says when it was archived. Without `archived`, says which way it is. With `archived`, it plans — `dryRun` is true unless you say false — and only an admin of the repository, with an admin token and never as an agent, changes it. The same as Settings → Archive and PATCH /api/v1/repos/:owner/:name {archived}.",
687 inputSchema: {
688 type: "object",
689 properties: {
690 repo: REPO_ARG,
691 archived: { type: "boolean" },
692 dryRun: {
693 type: "boolean",
694 description: "Plan only (the default). Send false to do it.",
695 },
696 },
697 required: ["repo"],
698 },
699 writes: true,
700 dryByDefault: true,
701 async run(ctx, user, args) {
702 const repo = repoArg(ctx, user, args);
703 if (isAnswer(repo)) return repo;
704 if (typeof args["archived"] !== "boolean")
705 return good({
706 archived: repo.archivedAt !== null,
707 archivedAt: repo.archivedAt,
708 });
709 const dryRun = args["dryRun"] !== false;
710 if (!dryRun && !scopeAllows(ctx.auth.scope ?? "ro", "admin"))
711 return bad("forbidden", "archiving needs an admin token");
712 const set = await setArchived(ctx.app, user, repo, args["archived"], dryRun);
713 if (!set.ok)
714 return bad("forbidden", "only a person who administers this repository archives it");
715 return good({
716 ...set.value,
717 says: dryRun
718 ? `This is the plan; nothing changed. It is ${set.value.was ? "archived" : "awake"} now; send dryRun: false to ${set.value.archived ? "archive it" : "wake it"}.`
719 : set.value.archived
720 ? "Archived: the app is stopped, its data kept, the crew held. Wake it with archived: false."
721 : "Awake: the app is coming back up and the crew may work again.",
722 });
723 },
724 },
683725 {
684726 name: "probe",
685727 description:
src/http/server.ts +4
@@ -199,6 +199,7 @@ import {
199199 import {
200200 frontUpdate,
201201 liveAppsFragment,
202 archiveMany,
202203 liveOnYouFragment,
203204 studioDoor,
204205 } from "../web/studio/home.ts";
@@ -282,6 +283,7 @@ import {
282283 crewRoleUpdate,
283284 crewSettingsPage,
284285 dangerPage,
286 repoArchive,
285287 hooksPage,
286288 labelCreate,
287289 labelDelete,
@@ -603,6 +605,7 @@ export function buildRouter(): Router<Handler> {
603605 // home's shelf and its "On you" card answer for themselves, so an event
604606 // fetches a region and not the page. Literal, above /:owner.
605607 router.add("GET", "/live/apps", liveAppsFragment);
608 router.add("POST", "/apps/archive", archiveMany);
606609 router.add("GET", "/live/on-you", liveOnYouFragment);
607610 router.add("GET", "/live/feed", liveFeedFragment);
608611 // Whether a hostname is an app's verified domain — what Caddy's
@@ -1107,6 +1110,7 @@ export function buildRouter(): Router<Handler> {
11071110 router.add("POST", "/:owner/:name/settings/hooks", webhookCreate);
11081111 router.add("POST", "/:owner/:name/settings/hooks/:id/delete", webhookDelete);
11091112 router.add("GET", "/:owner/:name/settings/danger", dangerPage);
1113 router.add("POST", "/:owner/:name/settings/archive", repoArchive);
11101114 router.add("POST", "/:owner/:name/settings/delete", repoDelete);
11111115 router.add(
11121116 "POST",
src/web/chrome.ts +22
@@ -341,6 +341,28 @@ export function scopeHeader(
341341 <span class="mono">${scope.upstream}</span>
342342 </p>`,
343343 )}
344 ${when(
345 repo?.archivedAt,
346 // At rest (#1113): the page says so, and the one button wakes it.
347 (at) =>
348 html`<form
349 class="repo-lineage row"
350 method="post"
351 action="${base}/settings/archive"
352 >
353 ${icon("clock", 16)}
354 <span
355 >Archived on <time datetime="${at}">${at.slice(0, 10)}</time> — its
356 app is stopped and its crew held.</span
357 >
358 ${admin
359 ? html`<input type="hidden" name="archived" value="0" />${btn(
360 "Wake it",
361 { size: "sm", variant: "primary" },
362 )}`
363 : null}
364 </form>`,
365 )}
344366 ${studio ? studioOriginNote(repo) : whereRow(ctx, scope)}
345367 ${tabs(items, "Repository")}
346368 </header>`;
src/web/pages/apps.ts +29 −9
@@ -89,8 +89,11 @@ interface AppEntry {
8989 * (`canRead` resolves org ownership from the database), and a listing must
9090 * not get slower as the forge grows more apps.
9191 */
92 function appsForViewer(ctx: Ctx): AppEntry[] {
93 const repos = listReposVisibleTo(ctx.app.db, ctx.auth.user, { limit: 200 });
92 function appsForViewer(ctx: Ctx, archived: "omit" | "only" = "omit"): AppEntry[] {
93 const repos = listReposVisibleTo(ctx.app.db, ctx.auth.user, {
94 limit: 200,
95 archived,
96 });
9497 const records = appsForRepos(
9598 ctx.app.db,
9699 repos.map((repo) => repo.id),
@@ -129,11 +132,14 @@ export function envLabel(env: EnvName): string {
129132 * never sees its crew or its cost.
130133 */
131134 export async function appsList(ctx: Ctx): Promise<Response> {
132 const entries = appsForViewer(ctx);
135 // The archived shelf (#1113): resting apps, still one click from waking.
136 const archived = ctx.url.searchParams.get("archived") === "1";
137 const resting = appsForViewer(ctx, "only");
138 const entries = archived ? resting : appsForViewer(ctx);
133139 const liveCount = entries.filter(
134140 (e) => e.production?.state === "running",
135141 ).length;
136 const live = ctx.url.searchParams.get("live") === "1";
142 const live = !archived && ctx.url.searchParams.get("live") === "1";
137143 const shown = live
138144 ? entries.filter((e) => e.production?.state === "running")
139145 : entries;
@@ -147,22 +153,32 @@ export async function appsList(ctx: Ctx): Promise<Response> {
147153 })
148154 : btn("Sign in to make one", { href: "/signin", size: "sm" });
149155 const filters =
150 entries.length === 0
156 entries.length === 0 && resting.length === 0
151157 ? null
152158 : html`<div class="filters mb">
153159 ${seg([
154160 {
155161 label: "All",
156162 href: "/apps",
157 current: !live,
158 count: entries.length,
163 current: !live && !archived,
164 ...(archived ? {} : { count: entries.length }),
159165 },
160166 {
161167 label: "Live",
162168 href: "/apps?live=1",
163169 current: live,
164 count: liveCount,
170 ...(archived ? {} : { count: liveCount }),
165171 },
172 ...(resting.length === 0
173 ? []
174 : [
175 {
176 label: "Archived",
177 href: "/apps?archived=1",
178 current: archived,
179 count: resting.length,
180 },
181 ]),
166182 ])}
167183 </div>`;
168184 const rows = await shelfRows(
@@ -176,7 +192,11 @@ export async function appsList(ctx: Ctx): Promise<Response> {
176192 ${shown.length === 0
177193 ? empty({
178194 icon: "rocket",
179 title: live ? "Nothing is live" : "Nothing runs here yet",
195 title: live
196 ? "Nothing is live"
197 : archived
198 ? "Nothing is archived"
199 : "Nothing runs here yet",
180200 note: live
181201 ? "Nothing is serving right now — clear the filter to see every app."
182202 : "A new app is a repository with a small working app in it, served at its own hostname a few seconds later.",
src/web/pages/audit.ts +2
@@ -44,6 +44,7 @@ const AUDIT_LIMIT = 200;
4444 export async function auditPage(ctx: Ctx): Promise<Response> {
4545 const repos = listReposVisibleTo(ctx.app.db, ctx.auth.user, {
4646 limit: AUDIT_LIMIT,
47 archived: "include",
4748 });
4849 const records = appsForRepos(
4950 ctx.app.db,
@@ -296,6 +297,7 @@ function probeFoot(
296297 export async function auditCsv(ctx: Ctx): Promise<Response> {
297298 const repos = listReposVisibleTo(ctx.app.db, ctx.auth.user, {
298299 limit: AUDIT_LIMIT,
300 archived: "include",
299301 });
300302 const records = appsForRepos(
301303 ctx.app.db,
src/web/pages/settings.ts +49 −1
@@ -1658,6 +1658,26 @@ export function dangerPage(ctx: Ctx): Response {
16581658 const base = repoBase(repo);
16591659 const full = `${repo.ownerName}/${repo.name}`;
16601660
1661 const archived = repo.archivedAt !== null;
1662 const rest = card(
1663 html`<p>
1664 ${archived
1665 ? html`Archived <strong>${full}</strong> on ${time(repo.archivedAt!)}.
1666 Its app is stopped and its crew held; the data, the code and the
1667 address are all still here.`
1668 : html`Archiving <strong>${full}</strong> stops its app's
1669 environments (their data is kept), holds its crew, and takes it
1670 off the home, the explorer and the inbox. The page, its link
1671 and git keep working, and one button wakes it.`}
1672 </p>
1673 <form class="form-actions" method="post" action="${base}/settings/archive">
1674 <input type="hidden" name="archived" value="${archived ? "0" : "1"}" />
1675 ${btn(archived ? "Wake it" : "Archive this repository", {
1676 variant: archived ? "primary" : "secondary",
1677 })}
1678 </form>`,
1679 { head: html`${icon("clock")}<h2>Archive</h2>` },
1680 );
16611681 const body = card(
16621682 html`<p>
16631683 Deleting <strong>${full}</strong> removes its issues, pull requests,
@@ -1680,7 +1700,35 @@ export function dangerPage(ctx: Ctx): Response {
16801700 <h2>Delete this repository</h2>`,
16811701 },
16821702 );
1683 return settingsPageResponse(ctx, repo, "danger", "Danger zone", body);
1703 return settingsPageResponse(
1704 ctx,
1705 repo,
1706 "danger",
1707 "Danger zone",
1708 html`${rest}<div class="mt">${body}</div>`,
1709 );
1710 }
1711
1712 /** POST /:owner/:name/settings/archive — put the repository to rest, or wake it. */
1713 export async function repoArchive(ctx: Ctx): Promise<Response> {
1714 const gate = await adminForm(ctx);
1715 if (gate instanceof Response) return gate;
1716 const { repo, form } = gate;
1717 const archived = field(form, "archived") !== "0";
1718 const updated = await updateRepoSettings(ctx.app, ctx.auth.user, repo, {
1719 archived,
1720 });
1721 return flashTo(
1722 ctx,
1723 repoBase(repo),
1724 updated.ok
1725 ? {
1726 message: archived
1727 ? "Archived. The app is stopped and its data kept."
1728 : "Awake. The app is coming back up.",
1729 }
1730 : { tone: "danger", message: "That could not be changed." },
1731 );
16841732 }
16851733
16861734 /**
src/web/studio/home.ts +86 −3
@@ -18,7 +18,14 @@ import { appsRuntime } from "../../apps/runtime.ts";
1818 import { appsForRepos } from "../../core/apps.ts";
1919 import { WEIGHT_MAX, WEIGHT_NAMES } from "../../core/front.ts";
2020 import { LOOK_SIZES } from "../../core/looks.ts";
21 import { canRead, getRepo, type Repo } from "../../core/repos.ts";
21 import { setArchivedMany } from "../../actions/repos.ts";
22 import {
23 canAdmin,
24 canRead,
25 getRepo,
26 listReposWritableTo,
27 type Repo,
28 } from "../../core/repos.ts";
2229 import { type User } from "../../core/users.ts";
2330 import type { Ctx } from "../../http/context.ts";
2431 import { edgeLoginUrl } from "../../http/edge.ts";
@@ -27,7 +34,7 @@ import { repoBase, signInFirst } from "../chrome.ts";
2734 import { field, readForm, type Form } from "../form.ts";
2835 import { liveRegionsJs } from "../client.ts";
2936 import { html, when, type Html } from "../html.ts";
30 import { fragment, page, redirect } from "../layout.ts";
37 import { flashTo, fragment, page, redirect } from "../layout.ts";
3138 import { liveClientJs } from "../live.ts";
3239 import {
3340 btn,
@@ -61,6 +68,81 @@ const APPS_LIVE = "app.serving,app.stopped,run.finished";
6168 /** How many of your apps the rail names before "All apps". */
6269 const RAIL_APPS = 8;
6370
71 /** How long an archive can be taken back from the home. */
72 const UNDO_MS = 24 * 60 * 60 * 1000;
73
74 /**
75 * Select and archive (#1113): every app you can write, a checkbox each, one
76 * button; and for a day after, what you archived with one button to take it
77 * back. Both are plain forms to `POST /apps/archive`.
78 */
79 function archiveTools(ctx: Ctx, user: User, writable: readonly Repo[]): Html {
80 // Archiving needs admin (`archiveMany` checks it again): offer only doors
81 // that open.
outdated

The undo shelf lists every archived repo the viewer can write, but waking needs admin. Filter with canAdmin, or a writer gets an Undo button that answers "Nothing changed."

82 const db = ctx.app.db;
83 const repos = writable.filter((repo) => canAdmin(db, repo, user));
84 const since = new Date(Date.now() - UNDO_MS).toISOString();
85 const recent = listReposWritableTo(db, user, {
86 archived: "only",
87 limit: 200,
88 }).filter((repo) => repo.archivedAt! >= since && canAdmin(db, repo, user));
89 const names = (list: readonly Repo[], on: boolean): Html =>
90 html`${list.map(
91 (repo) =>
92 html`<label class="check row"
93 ><input type="checkbox" name="repo" value="${repo.ownerName}/${repo.name}"${on ? html` checked` : null} />
94 <span class="truncate">${repo.ownerName}/${repo.name}</span></label
outdated

repos here is every app the viewer can write (writableAppsOf), not every app they administer. Filter it with canAdmin before offering checkboxes, the way archiveMany does on the way in.

95 >`,
96 )}`;
97 return html`${when(
98 repos.length > 0,
99 () => html`<details class="home-archive">
100 <summary class="small muted">Archive apps…</summary>
101 <form method="post" action="/apps/archive" class="stack">
102 <input type="hidden" name="archived" value="1" />
103 ${names(repos, false)} ${btn("Archive selected", { size: "sm" })}
104 </form>
105 </details>`,
106 )}
107 ${when(
108 recent.length > 0,
109 () => html`<form method="post" action="/apps/archive" class="stack">
110 <input type="hidden" name="archived" value="0" />
111 <p class="small muted">Archived in the last day:</p>
112 ${names(recent, true)} ${btn("Undo", { size: "sm" })}
113 </form>`,
114 )}`;
115 }
116
117 /**
118 * POST /apps/archive — archive (`archived=1`) or wake (`archived=0`) the
119 * repositories named by `repo` fields (`owner/name`). Each is checked for
120 * admin on its own; an unreadable or unadministered name is skipped, never
121 * told apart from a missing one.
122 */
123 export async function archiveMany(ctx: Ctx): Promise<Response> {
124 const user = ctx.auth.user;
125 if (!user) return signInFirst(ctx);
126 const form = await readForm(ctx, "admin");
127 if (form instanceof Response) return form;
128 const archived = field(form, "archived") !== "0";
129 const picked: Repo[] = [];
130 for (const name of form.getAll("repo").slice(0, 200)) {
131 const [owner, repoName, ...rest] =
132 typeof name === "string" ? name.split("/") : [];
133 if (!owner || !repoName || rest.length > 0) continue;
134 const repo = getRepo(ctx.app.db, owner, repoName);
135 if (repo && canAdmin(ctx.app.db, repo, user)) picked.push(repo);
136 }
137 const done = await setArchivedMany(ctx.app, user, picked, archived);
138 return flashTo(ctx, "/", {
139 message:
140 done === 0
141 ? "Nothing changed."
142 : `${archived ? "Archived" : "Woke"} ${done} ${done === 1 ? "repository" : "repositories"}.${archived ? " Undo is on the home for a day." : ""}`,
143 });
144 }
145
64146 /**
65147 * Your apps, one step away (#599): a narrow column on a desk — each app's
66148 * name and how production is — and the verbs that were the shelf's head.
@@ -105,7 +187,8 @@ function yourApps(ctx: Ctx, user: User): Html {
105187 ${when(user.isAdmin, () =>
106188 btn("Front page", { href: "/front", size: "sm", icon: "globe" }),
107189 )}
108 </div>`,
190 </div>
191 <div class="home-apps-archive">${archiveTools(ctx, user, repos)}</div>`,
109192 {
110193 head: html`${icon("rocket")}
111194 <h2>Your apps</h2>`,
test/archive.test.ts added +359
@@ -0,0 +1,359 @@
1 /**
2 * Archive (#1113): a repository put to rest stops its app and keeps its
3 * data, holds its crew, leaves the lists that name what is live, and stays
4 * reachable by link; waking brings it all back.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { existsSync, readdirSync } 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 { AppsRuntime } from "../src/apps/runtime.ts";
13 import { envDataDir } from "../src/apps/data.ts";
14 import { newApp } from "../src/actions/apps.ts";
15 import { addToCrew, createAgent } from "../src/actions/crew.ts";
16 import { openIssue } from "../src/actions/issues.ts";
17 import { openPull } from "../src/actions/pulls.ts";
18 import { commitToBranch, updateRepoSettings } from "../src/actions/repos.ts";
19 import type { AppRecord } from "../src/core/apps.ts";
20 import { getRepoById, listAutonomousRepos, type Repo } from "../src/core/repos.ts";
21 import { listRuns } from "../src/core/runs.ts";
22 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
23 import { createToken } from "../src/core/tokens.ts";
24 import { createUser, getUserByName, type User } from "../src/core/users.ts";
25 import { driveRepo } from "../src/crew/autonomy.ts";
26 import { queueAgentRun } from "../src/crew/dispatch.ts";
27 import { askLinesFor } from "../src/web/studio/asks.ts";
28 import { serve, type Servers } from "../src/http/server.ts";
29
30 describe("an archived repository", () => {
31 let dataDir: string;
32 let app: App;
33 let servers: Servers;
34 let runtime: AppsRuntime;
35 let alice: User;
36 let repo: Repo;
37 let record: AppRecord;
38 let token = "";
39 const DOMAIN = "apps.test";
40
41 const viaHost = (path = "/", init: RequestInit = {}, label = "rest") =>
42 fetch(`${servers.url}${path}`, {
43 ...init,
44 headers: { ...(init.headers as Record<string, string>), host: `${label}.${DOMAIN}` },
45 redirect: "manual",
46 });
47 const api = (path: string, init: RequestInit = {}) => {
48 const headers = new Headers(init.headers);
49 headers.set("authorization", `Bearer ${token}`);
50 if (typeof init.body === "string" && !headers.has("content-type"))
51 headers.set("content-type", "application/json");
52 return fetch(`${servers.url}${path}`, { ...init, headers });
53 };
54 const fresh = () => getRepoById(app.db, repo.id)!;
55
56 async function production(): Promise<void> {
57 const deadline = Date.now() + 60_000;
58 while (Date.now() < deadline) {
59 const run = listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).find(
60 (r) => r.env === "production" && r.state === "ok",
61 );
62 if (run && (await viaHost()).status === 200) return;
63 await Bun.sleep(100);
64 }
65 throw new Error("production did not come up");
66 }
67
68 beforeAll(async () => {
69 dataDir = await mkdtemp(join(tmpdir(), "forge-archive-"));
70 app = createApp({ dataDir, port: 0 });
71 servers = await serve(app);
72 runtime = new AppsRuntime(app, {
73 domain: DOMAIN,
74 scheme: "http",
75 publicPort: servers.port,
76 forgeUrl: servers.url,
77 });
78 await runtime.start();
79 const made = await createUser(app.db, {
80 trusted: true,
81 username: "alice",
82 email: "[email protected]",
83 password: "a-good-passphrase",
84 adminIfFirst: true,
85 });
86 if (!made.ok) throw new Error(made.error);
87 alice = made.value;
88 token = createToken(app.db, alice.id, "t", "admin").token;
89 const app1 = await newApp(app, alice, {
90 name: "rest",
91 description: "Rests",
92 visibility: "public",
93 });
94 if (!app1.ok) throw new Error(String(app1.error));
95 repo = app1.value.repo;
96 record = app1.value.app;
97 await production();
98 }, 90_000);
99
100 afterAll(async () => {
101 await runtime.stop();
102 servers.stop();
103 app.close();
104 await rm(dataDir, { recursive: true, force: true });
105 });
106
107 test("it is listed while awake", async () => {
108 expect(await (await api("/live/apps")).text()).toContain("alice/rest");
109 expect(fresh().archivedAt).toBeNull();
110 });
111
112 test("archiving stops production, keeps its data, and says when", async () => {
113 const dataPath = envDataDir(dataDir, record.id, "production");
114 expect(existsSync(dataPath)).toBe(true);
115 const before = readdirSync(dataPath);
116 expect(before.length).toBeGreaterThan(0);
117
118 const patched = await api("/api/v1/repos/alice/rest", {
119 method: "PATCH",
120 body: JSON.stringify({ archived: true }),
121 });
122 expect(patched.status).toBe(200);
123 const json = (await patched.json()) as { archivedAt: string | null };
124 expect(json.archivedAt).toMatch(/^\d{4}-\d\d-\d\dT/);
125
126 expect((await viaHost()).status).not.toBe(200);
127 expect(readdirSync(dataPath)).toEqual(before);
128 expect(listAutonomousRepos(app.db).map((r) => r.id)).not.toContain(repo.id);
129 });
130
131 test("the home and /live/apps omit it; a link still opens it", async () => {
132 // The undo shelf names it; the apps list does not.
133 const live = await (await api("/live/apps")).text();
134 expect(live).toContain("No apps yet.");
135 expect(live).not.toContain('href="/alice/rest"');
136 const explore = await api("/api/v1/repos");
137 expect(JSON.stringify(await explore.json())).not.toContain('"name":"rest"');
138 const page = await api("/alice/rest");
139 expect(page.status).toBe(200);
140 const text = await page.text();
141 expect(text).toContain("Archived on");
142 expect(text).toContain("Wake it");
143 const single = (await (await api("/api/v1/repos/alice/rest")).json()) as {
144 archivedAt: string | null;
145 };
146 expect(single.archivedAt).not.toBeNull();
147 });
148
149 test("an archived shelf lists it past the day, and the audit still covers it", async () => {
150 const all = await (await api("/apps")).text();
151 expect(all).not.toContain("alice/rest");
152 expect(all).toContain("/apps?archived=1");
153 const shelf = await (await api("/apps?archived=1")).text();
154 expect(shelf).toContain("alice/rest");
155 expect(await (await api("/audit")).text()).toContain("alice/rest");
156 });
157
158 test("the home offers undo for a day, and undo wakes it", async () => {
159 const home = await (await api("/")).text();
160 expect(home).toContain('value="alice/rest" checked');
161 const woke = await api("/apps/archive", {
162 method: "POST",
163 headers: {
164 "content-type": "application/x-www-form-urlencoded",
165 origin: servers.url,
166 },
167 body: "archived=0&repo=alice%2Frest",
168 redirect: "manual",
169 });
170 expect(woke.status).toBe(303);
171 expect(fresh().archivedAt).toBeNull();
172 await production();
173 expect(await (await api("/live/apps")).text()).toContain("alice/rest");
174 });
175
176 test("select and archive several at once from the home", async () => {
177 const res = await api("/apps/archive", {
178 method: "POST",
179 headers: {
180 "content-type": "application/x-www-form-urlencoded",
181 origin: servers.url,
182 },
183 body: "archived=1&repo=alice%2Frest&repo=nobody%2Fnothing",
184 redirect: "manual",
185 });
186 expect(res.status).toBe(303);
187 expect(fresh().archivedAt).not.toBeNull();
188 expect((await viaHost()).status).not.toBe(200);
189 });
190
191 test("the crew does not pick or take its issues", async () => {
192 const agent = await createAgent(app, alice, { username: "mason" });
193 if (!agent.ok) throw new Error(String(agent.error));
194 expect(addToCrew(app, alice, fresh(), "mason").ok).toBe(true);
195 const on = await updateRepoSettings(app, alice, fresh(), {
196 autonomy: "autonomous",
197 autonomyDirection: "Keep going.",
198 autonomyCeilingUsd: 10,
199 autonomySlots: 1,
200 autonomyBy: alice.id,
201 });
202 expect(on.ok).toBe(true);
203 const issue = openIssue(app, alice, fresh(), { title: "Do a thing" });
204 if (!issue.ok) throw new Error(String(issue.error));
205 expect(await driveRepo(app, fresh())).toBe("off");
206 const mason = getUserByName(app.db, "mason")!;
207 expect(
208 queueAgentRun(app, fresh(), issue.value, mason as never, "assigned"),
209 ).toBeUndefined();
210 });
211
212 test("waking brings production back with its data", async () => {
213 const woke = await api("/api/v1/repos/alice/rest", {
214 method: "PATCH",
215 body: JSON.stringify({ archived: false }),
216 });
217 expect(((await woke.json()) as { archivedAt: unknown }).archivedAt).toBeNull();
218 await production();
219 expect(readdirSync(envDataDir(dataDir, record.id, "production")).length).toBeGreaterThan(0);
220 });
221
222 test("MCP plans first, then archives; an agent cannot", async () => {
223 const call = async (args: Record<string, unknown>, bearer = token) => {
224 const res = await fetch(`${servers.url}/mcp`, {
225 method: "POST",
226 headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" },
227 body: JSON.stringify({
228 jsonrpc: "2.0",
229 id: 1,
230 method: "tools/call",
231 params: { name: "archive", arguments: { repo: "alice/rest", ...args } },
232 }),
233 });
234 return JSON.stringify(await res.json());
235 };
236 expect(await call({ archived: true })).toContain("nothing changed");
237 expect(fresh().archivedAt).toBeNull();
238 await call({ archived: true, dryRun: false });
239 expect(fresh().archivedAt).not.toBeNull();
240 const mason = getUserByName(app.db, "mason")!;
241 const agentToken = createToken(app.db, mason.id, "t", "admin").token;
242 await call({ archived: false, dryRun: false }, agentToken);
243 expect(fresh().archivedAt).not.toBeNull();
244 await call({ archived: false, dryRun: false });
245 expect(fresh().archivedAt).toBeNull();
246 });
247
248 test("a writer who cannot administer sees no archive control and cannot archive", async () => {
249 const bob = await createUser(app.db, {
250 trusted: true,
251 username: "bob",
252 email: "[email protected]",
253 password: "a-good-passphrase",
254 });
255 if (!bob.ok) throw new Error(bob.error);
256 const org = createOrg(app.db, "guild", alice.id);
257 if (!org.ok) throw new Error("org");
258 const writers = createTeam(app.db, org.value.id, "writers", "write");
259 if (!writers.ok) throw new Error("team");
260 addTeamMember(app.db, writers.value, bob.value.id);
261 const made = await newApp(app, alice, {
262 name: "crate",
263 description: "Crates",
264 visibility: "public",
265 owner: "guild",
266 });
267 if (!made.ok) throw new Error(String(made.error));
268 const crate = made.value.repo;
269 const bobToken = createToken(app.db, bob.value.id, "t", "admin").token;
270 const asBob = (path: string, init: RequestInit = {}) =>
271 fetch(`${servers.url}${path}`, {
272 ...init,
273 headers: {
274 ...(init.headers as Record<string, string>),
275 authorization: `Bearer ${bobToken}`,
276 },
277 redirect: "manual",
278 });
279 const control = 'name="repo" value="guild/crate"';
280 // The positive control: someone who can administer it is offered it.
281 expect(await (await api("/")).text()).toContain(control);
282 expect(await (await asBob("/")).text()).not.toContain(control);
283 const res = await asBob("/apps/archive", {
284 method: "POST",
285 headers: {
286 "content-type": "application/x-www-form-urlencoded",
287 origin: servers.url,
288 },
289 body: "archived=1&repo=guild%2Fcrate",
290 });
291 expect(res.status).toBe(303);
292 expect(getRepoById(app.db, crate.id)!.archivedAt).toBeNull();
293 // The admin archives it; the writer is offered no Undo either.
294 await api("/apps/archive", {
295 method: "POST",
296 headers: {
297 "content-type": "application/x-www-form-urlencoded",
298 origin: servers.url,
299 },
300 body: "archived=1&repo=guild%2Fcrate",
301 });
302 expect(getRepoById(app.db, crate.id)!.archivedAt).not.toBeNull();
303 expect(await (await api("/")).text()).toContain(`${control} checked`);
304 expect(await (await asBob("/")).text()).not.toContain(control);
305 }, 60_000);
306
307 test("an open pull leaves the asks when its repository is archived, and its preview returns on waking", async () => {
308 const assisted = await updateRepoSettings(app, alice, fresh(), {
309 autonomy: "assisted",
310 });
311 expect(assisted.ok).toBe(true);
312 const committed = await commitToBranch(app, alice, fresh(), {
313 branch: "tune",
314 base: fresh().defaultBranch,
315 message: "Add a tune",
316 files: [{ path: "TUNE.md", content: "la\n" }],
317 });
318 expect(committed.ok).toBe(true);
319 const opened = await openPull(app, alice, fresh(), {
320 title: "Add a tune",
321 baseBranch: fresh().defaultBranch,
322 headBranch: "tune",
323 });
324 if (!opened.ok) throw new Error(String(opened.error));
325 const pull = opened.value;
326 const env = `pull-${pull.number}`;
327 const previews = () =>
328 listRuns(app.db, repo.id, { kind: "deploy", limit: 100 }).filter(
329 (r) => r.env === env && r.state === "ok",
330 );
331 const until = async (done: () => boolean | Promise<boolean>) => {
332 const deadline = Date.now() + 60_000;
333 while (Date.now() < deadline) {
334 if (await done()) return;
335 await Bun.sleep(100);
336 }
337 throw new Error("timed out");
338 };
339 const asks = () =>
340 askLinesFor(app.db, alice).flatMap((r) => r.items).filter((i) => i.endsWith(pull.id));
341 const preview = () => viaHost("/", {}, `rest--${pull.number}`);
342 await until(() => previews().length > 0);
343 expect(asks().length).toBeGreaterThan(0);
344
345 const patch = (archived: boolean) =>
346 api("/api/v1/repos/alice/rest", {
347 method: "PATCH",
348 body: JSON.stringify({ archived }),
349 });
350 await patch(true);
351 expect(asks()).toEqual([]);
352
353 const before = previews().length;
354 await patch(false);
355 await until(() => previews().length > before);
356 await until(async () => (await preview()).status === 200);
357 expect(asks().length).toBeGreaterThan(0);
358 }, 120_000);
359 });
test/mcp.test.ts +1
@@ -168,6 +168,7 @@ describe("the forge over MCP", () => {
168168 "health",
169169 "audit",
170170 "outsiders",
171 "archive",
outdated

Indentation: two spaces short of the list around it.

171172 "probe",
172173 "following",
173174 "spawn",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs