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

Archive one repository: its app spins down with data kept, it leaves the home, explorer and inbox, and one button wakes it #1748

Closed opened this
Closed without merging

scout/forge:scout/1619-archive-one-repository-its-app-spins-dow → main 6 commits fork 1 thread · 1 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
19 files changed +551 −8
docs/APPS.md +11
@@ -600,6 +600,17 @@ ping for 120 seconds is dropped. The app's own 101 response headers are
600600 not carried — a cookie an app sets on the handshake does not reach the
601601 browser.
602602
603 ## Archiving
604
605 `PATCH /api/v1/repos/:owner/:name {"archived": true}` (an admin of the
606 repository), the `archive` MCP tool, or Settings → Danger zone → Archive puts
607 a repository to rest. Its environments stop and their data stays on disk; the
608 crew takes no new runs for it and nothing deploys on a push; it leaves the
609 home, the explorer and the inbox. Its page (which says "archived on <date>"),
610 links and git keep working. `archived: false`, or the Wake button, restarts
611 production over the same data; previews come back with their pulls' next push.
612 The repository JSON carries `archivedAt`.
613
603614 ## Your own domain
604615
605616 An app can answer at a name you own — `app.example.com`, or an apex like
scripts/gate.ts +2
@@ -28,6 +28,8 @@ export const GATE: readonly string[] = [
2828 "test/accounts-retire.test.ts",
2929 "test/cloud-use.test.ts",
3030 "test/accounts.test.ts",
31 "test/archive-app.test.ts",
32 "test/archive.test.ts",
3133 "test/asks-mute.test.ts",
3234 "test/agents.test.ts",
3335 "test/app-domains.test.ts",
src/actions/repos.ts +43
@@ -21,6 +21,7 @@ import {
2121 deleteRepo as destroyRepo,
2222 forkRepo as cloneRepo,
2323 getSealedFork,
24 setArchived,
2425 updateRepoSettings as writeSettings,
2526 type CreateRepoError,
2627 type DecisionsBy,
@@ -46,6 +47,9 @@ import {
4647 type FileWrite,
4748 } from "../git/write.ts";
4849 import { err, ok, type Result } from "../kernel/result.ts";
50 import { appsRuntime } from "../apps/runtime.ts";
51 import { listActive } from "../core/runs.ts";
52 import { cancelRepoRun } from "./runs.ts";
4953 import { trackPullHead } from "../core/pulls.ts";
5054 import {
5155 requireParticipant,
@@ -327,6 +331,45 @@ export async function setCrewOutsiders(
327331 return ok({ on: updated.value.crewOutsiders, was: repo.crewOutsiders, dryRun });
328332 }
329333
334 export type ArchiveError = AccessError;
335
336 /**
337 * Archive a repository, or wake it (#1619). Archiving stops the app's
338 * environments (their data stays), cancels what the crew has queued or
339 * running and refuses it new runs; waking restarts production from the same
340 * data. Git, links and the page itself go on working either way.
341 */
342 export async function archiveRepo(
343 app: App,
344 actor: User | undefined,
345 repo: Repo,
346 archived: boolean,
347 ): Promise<Result<Repo, ArchiveError>> {
348 const admin = requireRepoAdmin(app, actor, repo);
349 if (!admin.ok) return admin;
350 if ((repo.archivedAt !== null) === archived) return ok(repo);
351 const updated = setArchived(
352 app.db,
353 repo,
354 archived ? new Date().toISOString() : null,
355 );
356 const runtime = appsRuntime(app);
357 if (archived) {
358 for (const kind of ["agent", "check", "deploy"] as const)
359 for (const run of listActive(app.db, kind))
360 if (run.repoId === repo.id) cancelRepoRun(app, admin.value, repo, run.id);
361 if (runtime !== undefined) await runtime.stopRepo(repo.id);
362 } else if (runtime !== undefined) {
363 await runtime.wakeRepo(updated);
364 }
365 app.bus.append({
366 kind: archived ? "repo.archived" : "repo.woken",
367 repoId: repo.id,
368 actorId: admin.value.id,
369 });
370 return ok(updated);
371 }
372
330373 export interface DecisionsAnswer {
331374 /** Who answers the repository's decisions, after this call. */
332375 readonly by: DecisionsBy;
src/apps/runtime.ts +18 −1
@@ -615,7 +615,12 @@ export class AppsRuntime {
615615 known.add(record.id);
616616 const repo = getRepoById(this.app.db, record.repoId);
617617 // A forge coming back does not restart a suspended owner's apps.
618 if (repo && accountActive(this.app.db, repo.ownerId))
618 // Nor an archived repository's: it sleeps until someone wakes it.
619 if (
620 repo &&
621 repo.archivedAt === null &&
622 accountActive(this.app.db, repo.ownerId)
623 )
619624 present.push({ record, repo });
620625 }
621626 for (const { record, repo } of present)
@@ -906,6 +911,8 @@ export class AppsRuntime {
906911 // A suspended or removed owner's app does not deploy.
907912 if (this.stopped || !accountActive(this.app.db, repo.ownerId))
908913 return undefined;
914 // An archived repository's app deploys nothing until it is woken (#1619).
915 if (repo.archivedAt !== null) return undefined;
909916 if (!this.mayRun(record, repo, env, commitOid)) return undefined;
910917 const state = this.envFor(record, env);
911918 state.dormant = undefined;
@@ -1900,6 +1907,16 @@ export class AppsRuntime {
19001907 removeApp(this.app.config.dataDir, state.app.id);
19011908 }
19021909
1910 /**
1911 * Bring an archived repository's production back, from the same data
1912 * (#1619). Previews come with their pulls' next push or approval.
1913 */
1914 async wakeRepo(repo: Repo): Promise<void> {
1915 const record = getAppByRepo(this.app.db, repo.id);
1916 if (record !== undefined)
1917 await this.reconcileApp(record, repo, "woken", "production");
1918 }
1919
19031920 /** Stop every environment of a repository's app; the data stays. */
19041921 async stopRepo(repoId: string): Promise<void> {
19051922 const states = [...this.envs.values()].filter(
src/checks/service.ts +1
@@ -203,6 +203,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
203203 ): Promise<Run | undefined> {
204204 // A suspended or removed owner's code is not run, not even to check it.
205205 if (stopped || !accountActive(app.db, repo.ownerId)) return undefined;
206 if (repo.archivedAt !== null) return undefined;
206207 // A pull from someone who cannot write runs nothing until a writer
207208 // approves this exact head (`core/pull_trust.ts`).
208209 if (!issueMayRun(app.db, repo, issueId, commitOid)) {
src/core/repos.ts +26 −3
@@ -128,6 +128,8 @@ export interface Repo {
128128 * read only by the base's writers and crew. Null for every other one.
129129 */
130130 readonly sealedFor: string | null;
131 /** When the repository was archived (#1619), or null while it is live. */
132 readonly archivedAt: string | null;
131133 /** The origin this mirrors, or null for a native repo. */
132134 readonly origin: RepoOrigin | null;
133135 /**
@@ -173,6 +175,7 @@ interface RepoRow {
173175 last_fetch_at: string | null;
174176 fetch_error: string;
175177 origin_detached_at: string | null;
178 archived_at: string | null;
176179 }
177180
178181 // LEFT JOIN, because the origin may have been disconnected out from under a
@@ -204,6 +207,7 @@ function toRepo(row: RepoRow): Repo {
204207 directionIssueId: row.direction_issue_id,
205208 forkParentId: row.fork_parent_id,
206209 sealedFor: row.sealed_for,
210 archivedAt: row.archived_at,
207211 origin:
208212 row.origin_id !== null && row.origin_kind !== null
209213 ? {
@@ -641,8 +645,14 @@ export interface ListReposOptions {
641645 cursor?: string;
outdated

Nothing passes includeArchived: true, so this option is dead code. Every caller of listReposVisibleTo and listReposWritableTo now hides archived repositories, including GET /api/v1/repos, search, the Apps page and the TUI dashboard. That leaves no way to find an archived repository except by its URL. Filter only on the home, the explorer and the inbox, and add at least one listing (Apps page or profile, plus ?archived=1 on the API) that passes includeArchived: true, with a test.

642646 /** Repositories that run an app first, each half newest first (not with `cursor`). */
643647 appsFirst?: boolean;
648 /** Archived repositories leave a listing unless asked for (#1619). */
649 includeArchived?: boolean;
644650 }
645651
652 /** The clause that keeps an archived repository out of a listing. */
653 const liveOnly = (options: ListReposOptions): string =>
654 options.includeArchived === true ? "" : " AND repo.archived_at IS NULL";
655
646656 // Visibility in SQL: public, owned, or owned by an org the viewer is on a
647657 // team of. Site admins see everything. The same rule canRead applies, so a
648658 // listing never shows a repo whose page would 404.
@@ -660,7 +670,7 @@ export function listReposVisibleTo(
660670 options: ListReposOptions = {},
661671 ): Repo[] {
662672 const params: (string | number)[] = [viewer?.id ?? ""];
663 let where = viewer ? VISIBLE : PUBLIC_VISIBLE;
673 let where = (viewer ? VISIBLE : PUBLIC_VISIBLE) + liveOnly(options);
664674 if (options.query !== undefined && options.query.trim() !== "") {
665675 params.push(`%${likeEscape(options.query.trim())}%`);
666676 const p = params.length;
@@ -694,7 +704,7 @@ export function listReposWritableTo(
694704 ): Repo[] {
695705 if (!viewer) return [];
696706 const params: (string | number)[] = [viewer.id];
697 let where = REPO_WRITABLE;
707 let where = REPO_WRITABLE + liveOnly(options);
698708 if (options.query !== undefined && options.query.trim() !== "") {
699709 params.push(`%${likeEscape(options.query.trim())}%`);
700710 const p = params.length;
@@ -1069,6 +1079,19 @@ export function updateRepoSettings(
10691079 return getRepoById(db, repo.id)!;
10701080 }
10711081
1082 /** Put a repository to rest, or wake it: the one column (#1619). */
1083 export function setArchived(
1084 db: Database,
1085 repo: Repo,
1086 archivedAt: string | null,
1087 ): Repo {
1088 db.query("UPDATE repo SET archived_at = ?2 WHERE id = ?1").run(
1089 repo.id,
1090 archivedAt,
1091 );
1092 return getRepoById(db, repo.id)!;
1093 }
1094
10721095 /** Repositories the crew drives on its own, assisted or autonomous. */
10731096 /** Every repository the forge holds, for the snapshot: nothing is left out. */
10741097 export function listEveryRepo(db: Database): Repo[] {
@@ -1083,7 +1106,7 @@ export function listAutonomousRepos(db: Database): Repo[] {
10831106 .query<
10841107 RepoRow,
10851108 []
1086 >(`${SELECT} WHERE repo.autonomy != 'off' ORDER BY repo.name`)
1109 >(`${SELECT} WHERE repo.autonomy != 'off' AND repo.archived_at IS NULL ORDER BY repo.name`)
10871110 .all()
10881111 .map(toRepo);
10891112 }
src/core/schema.ts +6 −1
@@ -1733,7 +1733,12 @@ export const migrations: readonly string[] = [
17331733 question INTEGER NOT NULL DEFAULT 0,
17341734 decided_by TEXT NOT NULL,
17351735 placed_at TEXT NOT NULL
1736 );
1736 );`,
1737 // 85 — archived repositories (#1619): when the repository was put to rest.
1738 // NULL is a live repository. An archived one keeps its data, git and links;
1739 // it only leaves the lists, takes no new runs, and has its app stopped.
1740 `
1741 ALTER TABLE repo ADD COLUMN archived_at TEXT;
17371742 `,
17381743 // 85 — a standing rule per repository (#1605): who answers the decisions
17391744 // it asks of its owner. \`me\` is what every repository did before.
src/crew/dispatch.ts +2
@@ -284,6 +284,8 @@ export function queueAgentRun(
284284 ): Run | undefined {
285285 // A suspended or removed owner's repositories run nothing, whoever asks.
286286 if (!accountActive(app.db, repo.ownerId)) return undefined;
287 // An archived repository takes no new runs (#1619).
288 if (repo.archivedAt !== null) return undefined;
287289 // The day's ceiling gates every run the crew starts on its own, not only
288290 // the picks: a review, a feedback run or a conflict run past the ceiling
289291 // is money the person did not agree to. A person's own assignment is not
src/design/activity.ts +2
@@ -111,6 +111,8 @@ const WORDS: Record<string, string> = {
111111 "repo.created": "created a repository",
112112 "repo.forked": "forked a repository",
113113 "repo.settings_updated": "changed repository settings",
114 "repo.archived": "archived a repository",
115 "repo.woken": "woke an archived repository",
114116 "repo.crew_outsiders": "changed who may trigger the crew",
115117 "repo.mirrored": "mirrored a repository",
116118 "repo.imported": "imported issues and pulls",
src/feed/items.ts +2
@@ -209,6 +209,8 @@ export function candidatesFor(
209209 ...asks.map((a) => a.repoId),
210210 ]);
211211 for (const r of writable) repos.set(r.id, r);
212 // An archived repository has left the home (#1619): nothing of it is a candidate.
213 for (const [id, r] of repos) if (r.archivedAt !== null) repos.delete(id);
212214
213215 const names = new Map<string, string | null>();
214216 const nameOf = (id: string | null): string | null => {
src/http/api.ts +12
@@ -128,6 +128,7 @@ import {
128128 FORKS_PER_DAY,
129129 forkRepo,
130130 privateRepoForSealed,
131 archiveRepo,
131132 updateRepoSettings,
132133 } from "../actions/repos.ts";
133134 import {
@@ -1815,6 +1816,17 @@ export function apiRoutes(router: Router<Handler>): void {
18151816 : {}),
18161817 });
18171818 if (!updated.ok) return respondAccess(updated.error, 422);
1819 // Archiving (#1619): stops the app, keeps its data, leaves the lists.
1820 if (typeof input.archived === "boolean") {
1821 const rested = await archiveRepo(
1822 ctx.app,
1823 ctx.auth.user,
1824 updated.value,
1825 input.archived,
1826 );
1827 if (!rested.ok) return respondAccess(rested.error, 422);
1828 return json(repoJson(ctx, rested.value));
1829 }
18181830 return json(repoJson(ctx, updated.value));
18191831 });
18201832
src/http/mcp.ts +44 −1
@@ -109,7 +109,11 @@ import {
109109 directionNote,
110110 OUTSIDERS_NOTE,
111111 } from "../crew/direct.ts";
112 import { setCrewOutsiders, setDecisionsBy } from "../actions/repos.ts";
112 import {
113 archiveRepo,
114 setCrewOutsiders,
115 setDecisionsBy,
116 } from "../actions/repos.ts";
113117 import { mapJson, marksFor } from "../web/pages/map.ts";
114118 import { undoFleetOp } from "../actions/fleet.ts";
115119 import { applyLimb, isLimbAction, previewLimb } from "../actions/limbs.ts";
@@ -839,6 +843,45 @@ const TOOLS: readonly Tool[] = [
839843 );
840844 },
841845 },
846 {
847 name: "archive",
848 description:
849 "Archive an app's repository, or wake it. Archived: its environments stop and their data is kept, the crew takes no new runs, and it leaves the home, the explorer and the inbox; its page, links and git still work. Without `archived`, says which way it is. With it, it plans — `dryRun` is true unless you say false — and only an admin of the app, with an admin token, does it.",
850 inputSchema: {
851 type: "object",
852 properties: {
853 repo: REPO_ARG,
854 archived: { type: "boolean" },
855 dryRun: {
856 type: "boolean",
857 description: "Plan only (the default). Send false to do it.",
858 },
859 },
860 required: ["repo"],
861 },
862 writes: true,
863 dryByDefault: true,
864 async run(ctx, user, args) {
865 const repo = repoArg(ctx, user, args);
866 if (isAnswer(repo)) return repo;
867 const was = repo.archivedAt;
868 if (typeof args["archived"] !== "boolean") return good({ archivedAt: was });
869 const dryRun = args["dryRun"] !== false;
870 if (dryRun)
871 return good({
872 archivedAt: was,
873 archived: args["archived"],
874 dryRun,
875 says: "This is the plan; nothing changed. Send dryRun: false to do it.",
876 });
877 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
878 return bad("forbidden", "archiving needs an admin token");
879 const done = await archiveRepo(ctx.app, user, repo, args["archived"]);
880 if (!done.ok)
881 return bad("forbidden", "only an admin of this app archives it");
882 return good({ archivedAt: done.value.archivedAt, dryRun });
883 },
884 },
842885 {
843886 name: "outsiders",
844887 description:
src/http/server.ts +2
@@ -321,6 +321,7 @@ import {
321321 promptSourceDelete,
322322 promptSourceRun,
323323 promptsSettingsPage,
324 repoArchive,
324325 repoDelete,
325326 settingsPage,
326327 settingsUpdate,
@@ -1193,6 +1194,7 @@ export function buildRouter(): Router<Handler> {
11931194 router.add("POST", "/:owner/:name/settings/hooks/:id/delete", webhookDelete);
11941195 router.add("GET", "/:owner/:name/settings/danger", dangerPage);
11951196 router.add("POST", "/:owner/:name/settings/delete", repoDelete);
1197 router.add("POST", "/:owner/:name/settings/archive", repoArchive);
11961198 router.add(
11971199 "POST",
11981200 "/:owner/:name/settings/origin/reconnect",
src/web/chrome.ts +17
@@ -322,6 +322,23 @@ export function scopeHeader(
322322 !options.compact && facts.description !== "",
323323 () => html`<p class="repo-desc">${facts.description}</p>`,
324324 )}
325 ${when(
326 repo?.archivedAt ?? null,
327 (at) =>
328 html`<form
329 class="repo-lineage"
330 method="post"
331 action="${base}/settings/archive"
332 >
333 ${icon("clock", 16)}archived on ${at.slice(0, 10)}
334 ${admin
335 ? html`<input type="hidden" name="archived" value="0" />${btn(
336 "Wake",
337 { size: "sm" },
338 )}`
339 : null}
340 </form>`,
341 )}
325342 ${when(
326343 parent,
327344 (p) =>
src/web/pages/settings.ts +49 −1
@@ -47,6 +47,7 @@ import {
4747 deleteRepo,
4848 deleteWebhook,
4949 updateLabel,
50 archiveRepo,
5051 updateRepoSettings,
5152 } from "../../actions/repos.ts";
5253 import { appsRuntime } from "../../apps/runtime.ts";
@@ -1680,7 +1681,54 @@ export function dangerPage(ctx: Ctx): Response {
16801681 <h2>Delete this repository</h2>`,
16811682 },
16821683 );
1683 return settingsPageResponse(ctx, repo, "danger", "Danger zone", body);
1684 const archive = card(
1685 html`<p>
1686 ${repo.archivedAt === null
1687 ? html`Archiving <strong>${full}</strong> stops its app and keeps its
1688 data. The crew takes no new runs for it, and it leaves the home,
1689 the explorer and the inbox. Its page, links and git keep working,
1690 and one button wakes it.`
1691 : html`<strong>${full}</strong> was archived on
1692 ${repo.archivedAt.slice(0, 10)}. Waking it restarts production with the
1693 same data.`}
1694 </p>
1695 <form method="post" action="${base}/settings/archive">
1696 <input
1697 type="hidden"
1698 name="archived"
1699 value="${repo.archivedAt === null ? "1" : "0"}"
1700 />
1701 <div class="form-actions">
1702 ${btn(repo.archivedAt === null ? "Archive this repository" : "Wake", {
1703 variant: "primary",
1704 })}
1705 </div>
1706 </form>`,
1707 { head: html`${icon("clock")}<h2>Archive</h2>` },
1708 );
1709 return settingsPageResponse(
1710 ctx,
1711 repo,
1712 "danger",
1713 "Danger zone",
1714 html`${archive}<div class="mt">${body}</div>`,
1715 );
1716 }
1717
1718 /** POST /:owner/:name/settings/archive — archive, or wake (`archived=0`). */
1719 export async function repoArchive(ctx: Ctx): Promise<Response> {
1720 const gate = await adminForm(ctx);
1721 if (gate instanceof Response) return gate;
1722 const { repo, form } = gate;
1723 const archived = field(form, "archived") !== "0";
1724 const done = await archiveRepo(ctx.app, ctx.auth.user, repo, archived);
1725 return flashTo(
1726 ctx,
1727 archived ? `${repoBase(repo)}/settings/danger` : repoBase(repo),
1728 done.ok
1729 ? { message: archived ? "Repository archived." : "Awake again." }
1730 : { tone: "danger", message: "That could not be done." },
1731 );
16841732 }
16851733
16861734 /**
src/web/pages/site.ts +2 −1
@@ -204,7 +204,8 @@ export function onYouCard(ctx: Ctx, user: User): Html | undefined {
204204 const silenced = new Map<string, Repo>();
205205 for (const issue of assigned) {
206206 const repo = repos.get(issue.repoId);
207 if (!repo) continue;
207 // An archived repository has left the home and the inbox (#1619).
208 if (!repo || repo.archivedAt !== null) continue;
208209 if (!visible.has(repo.id) && !canRead(db, repo, user)) continue;
209210 if (!mayView(db, repo, issue, user)) continue;
210211 if (muted.has(repo.id)) {
test/archive-app.test.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * Archiving stops a running app and keeps its data; waking restarts
3 * production over the same data (#1619). A push to an archived repository
4 * deploys nothing.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { existsSync, readFileSync, writeFileSync } from "node:fs";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { AppsRuntime } from "../src/apps/runtime.ts";
14 import { envDataDir } from "../src/apps/data.ts";
15 import { newApp } from "../src/actions/apps.ts";
16 import { archiveRepo, commitToBranch } from "../src/actions/repos.ts";
17 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
18 import { getRepoById, type Repo } from "../src/core/repos.ts";
19 import { listRuns } from "../src/core/runs.ts";
20 import { createUser, type User } from "../src/core/users.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25
26 describe("archiving a running app", () => {
27 let dataDir = "";
28 let app: App;
29 let servers: Servers;
30 let runtime: AppsRuntime;
31 let alice: User;
32 let repo: Repo;
33 let record: AppRecord;
34
35 const production = () => runtime.envStatus(record, "production")?.state;
36 const until = async (done: () => boolean, ms = 90_000) => {
37 const deadline = Date.now() + ms;
38 while (Date.now() < deadline && !done()) await Bun.sleep(100);
39 return done();
40 };
41 const dataFile = () => join(envDataDir(dataDir, record.id, "production"), "kept.txt");
42
43 beforeAll(async () => {
44 dataDir = await mkdtemp(join(tmpdir(), "forge-archive-app-"));
45 app = createApp({ dataDir, port: 0 });
46 servers = await serve(app);
47 runtime = new AppsRuntime(app, {
48 domain: "apps.test",
49 scheme: "http",
50 publicPort: servers.port,
51 forgeUrl: servers.url,
52 concurrency: 2,
53 });
54 await runtime.start();
55 const created = await createUser(app.db, {
56 trusted: true,
57 username: "alice",
58 email: "[email protected]",
59 password: "a-good-passphrase",
60 adminIfFirst: true,
61 });
62 if (!created.ok) throw new Error(created.error);
63 alice = created.value;
64 const made = await newApp(app, alice, {
65 name: "sleeper",
66 description: "Sleeps on request",
67 visibility: "public",
68 });
69 if (!made.ok) throw new Error(made.error);
70 repo = made.value.repo;
71 record = getAppByRepo(app.db, repo.id)!;
72 await until(() => production() === "running");
73 }, 120_000);
74
75 afterAll(async () => {
76 await runtime.stop();
77 servers.stop();
78 app.close();
79 await rm(dataDir, { recursive: true, force: true });
80 });
81
82 test("archiving stops production, keeps the data, and a push deploys nothing", async () => {
83 expect(production()).toBe("running");
84 writeFileSync(dataFile(), "precious");
85
86 const done = await archiveRepo(app, alice, repo, true);
87 expect(done.ok).toBe(true);
88 expect(production()).toBe("stopped");
89 expect(readFileSync(dataFile(), "utf8")).toBe("precious");
90
91 const before = listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).length;
92 const pushed = await commitToBranch(app, alice, getRepoById(app.db, repo.id)!, {
93 message: "While archived",
94 files: [{ path: "NOTE.md", content: "x\n" }],
95 });
96 expect(pushed.ok).toBe(true);
97 await Bun.sleep(500);
98 expect(listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).length).toBe(before);
99 expect(production()).toBe("stopped");
100 }, 60_000);
101
102 test("waking restarts production over the same data", async () => {
103 const done = await archiveRepo(app, alice, getRepoById(app.db, repo.id)!, false);
104 expect(done.ok).toBe(true);
105 expect(await until(() => production() === "running")).toBe(true);
106 expect(existsSync(dataFile())).toBe(true);
107 expect(readFileSync(dataFile(), "utf8")).toBe("precious");
108 }, 120_000);
109 });
test/archive.test.ts added +202
@@ -0,0 +1,202 @@
1 /**
2 * Archiving one repository (#1619): it leaves the home, the explorer and the
3 * inbox but stays reachable by link; only an admin does it, never across
4 * origins; waking brings it back; the crew takes no new run for it.
5 */
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 { explore } from "../src/actions/explore.ts";
13 import { addToCrew, createAgent } from "../src/actions/crew.ts";
14 import { assignIssue, openIssue } from "../src/actions/issues.ts";
15 import { openPull } from "../src/actions/pulls.ts";
16 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
17 import { createApp as createAppRecord } from "../src/core/apps.ts";
18 import { getIssueById } from "../src/core/issues.ts";
19 import { getRepoById, type Repo } from "../src/core/repos.ts";
20 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
21 import { createToken } from "../src/core/tokens.ts";
22 import { createUser, getUserByName, type User } from "../src/core/users.ts";
23 import { queueAgentRun } from "../src/crew/dispatch.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25 import { askLinesFor } from "../src/web/studio/asks.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27
28 quietLogs();
29
30 const PASSWORD = "a-long-archive-passphrase";
31
32 describe("archiving a repository", () => {
33 let dataDir = "";
34 let app: App;
35 let servers: Servers;
36 let alice: User;
37 let bob: User;
38 let cookie = "";
39 let bobCookie = "";
40 let adminToken = "";
41 let repo: Repo;
42
43 const headers = (c: string) => ({ cookie: `${c}; forge_mode=studio`, origin: servers.url });
44 const signIn = async (username: string) => {
45 const res = await fetch(`${servers.url}/signin`, {
46 method: "POST",
47 body: new URLSearchParams({ username, password: PASSWORD }),
48 redirect: "manual",
49 });
50 return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
51 };
52 const patch = (body: unknown, init: RequestInit = {}) =>
53 fetch(`${servers.url}/api/v1/repos/alice/rested`, {
54 method: "PATCH",
55 headers: { authorization: `Bearer ${adminToken}`, "content-type": "application/json" },
56 body: JSON.stringify(body),
57 ...init,
58 });
59 const home = async () =>
60 await fetch(`${servers.url}/`, { headers: headers(cookie) }).then((r) => r.text());
61 const exploreNames = async () =>
62 (await explore(app, alice, { kind: "all", sort: "score", text: "" })).map((r) => r.url);
63
64 beforeAll(async () => {
65 dataDir = await mkdtemp(join(tmpdir(), "forge-archive-"));
66 app = createApp({ dataDir, port: 0 });
67 servers = await serve(app);
68 for (const name of ["alice", "bob"]) {
69 const made = await createUser(app.db, {
70 trusted: true,
71 username: name,
72 email: `${name}@forge.local`,
73 password: PASSWORD,
74 adminIfFirst: name === "alice",
75 });
76 if (!made.ok) throw new Error(made.error);
77 if (name === "alice") alice = made.value;
78 else bob = made.value;
79 }
80 cookie = await signIn("alice");
81 bobCookie = await signIn("bob");
82 adminToken = createToken(app.db, alice.id, "t", "admin").token;
83 await createAgent(app, alice, { username: "bot" });
84 const made = await createRepo(app, alice, { name: "rested", visibility: "public" });
85 if (!made.ok) throw new Error(String(made.error));
86 repo = made.value;
87 await commitToBranch(app, alice, repo, {
88 message: "seed",
89 files: [{ path: "README.md", content: "# rested\n" }],
90 });
91 addToCrew(app, alice, repo, "bot");
92 expect(createAppRecord(app.db, { repoId: repo.id, slug: "rested", access: "public" }).ok).toBe(true);
93 await commitToBranch(app, alice, repo, {
94 branch: "bot/1",
95 base: "main",
96 message: "Rested work",
97 files: [{ path: "F.md", content: "1\n" }],
98 });
99 const opened = await openPull(app, getUserByName(app.db, "bot")!, repo, {
100 title: "Rested work",
101 body: "",
102 baseBranch: "main",
103 headBranch: "bot/1",
104 });
105 if (!opened.ok) throw new Error(String(opened.error));
106 const run = createRun(app.db, {
107 repoId: repo.id,
108 kind: "check",
109 issueId: opened.value.id,
110 env: `pull-${opened.value.number}`,
111 commitOid: opened.value.headOid,
112 reason: "pull",
113 });
114 claimRun(app.db, run.id);
115 finishRun(app.db, run.id, { state: "ok", summary: "ok" });
116 expect(assignIssue(app, alice, repo, getIssueById(app.db, opened.value.id)!, alice).ok).toBe(true);
117 }, 30_000);
118
119 afterAll(async () => {
120 await servers.stop();
121 await rm(dataDir, { recursive: true, force: true });
122 });
123
124 test("a live repository is on the home, the explorer and the inbox", async () => {
125 expect((await home()).includes("/alice/rested")).toBe(true);
126 expect(await exploreNames()).toContain("/alice/rested");
127 expect(askLinesFor(app.db, alice)).toHaveLength(1);
128 });
129
130 test("a non-admin and a cross-origin request are refused, and nothing changes", async () => {
131 const bobToken = createToken(app.db, bob.id, "t", "admin").token;
132 const denied = await patch({ archived: true }, {
133 headers: { authorization: `Bearer ${bobToken}`, "content-type": "application/json" },
134 });
135 expect(denied.status).toBeGreaterThanOrEqual(400);
136 const cross = await fetch(`${servers.url}/api/v1/repos/alice/rested`, {
137 method: "PATCH",
138 headers: { cookie, origin: "https://evil.example", "content-type": "application/json" },
139 body: JSON.stringify({ archived: true }),
140 });
141 expect(cross.status).toBe(403);
142 const form = (c: string, origin: string) =>
143 fetch(`${servers.url}/alice/rested/settings/archive`, {
144 method: "POST",
145 headers: { cookie: c, origin },
146 body: new URLSearchParams({ archived: "1" }),
147 redirect: "manual",
148 });
149 expect((await form(cookie, "https://evil.example")).status).toBeGreaterThanOrEqual(400);
150 expect((await form(bobCookie, servers.url)).status).toBe(404);
151 expect(getRepoById(app.db, repo.id)!.archivedAt).toBeNull();
152 });
153
154 test("archived: absent from home, explorer and inbox, present by link, with a Wake button", async () => {
155 const res = await patch({ archived: true });
156 expect(res.status).toBe(200);
157 const json = (await res.json()) as { archivedAt: string | null };
158 expect(json.archivedAt).toMatch(/^\d{4}-\d\d-\d\dT/);
159
160 expect(await home()).not.toContain("/alice/rested");
161 expect(await exploreNames()).not.toContain("/alice/rested");
162 expect(askLinesFor(app.db, alice)).toHaveLength(0);
163
164 const page = await fetch(`${servers.url}/alice/rested`, { headers: headers(cookie) });
165 expect(page.status).toBe(200);
166 const text = await page.text();
167 expect(text).toContain(`archived on ${json.archivedAt!.slice(0, 10)}`);
168 expect(text).toContain('action="/alice/rested/settings/archive"');
169 expect(text).toContain("Wake");
170 const api = await fetch(`${servers.url}/api/v1/repos/alice/rested`, {
171 headers: { authorization: `Bearer ${adminToken}` },
172 });
173 expect(((await api.json()) as { archivedAt: string }).archivedAt).toBe(json.archivedAt!);
174 // Git still answers.
175 const refs = await fetch(`${servers.url}/alice/rested.git/info/refs?service=git-upload-pack`);
176 expect(refs.status).toBe(200);
177 });
178
179 test("the crew takes no new run for it", async () => {
180 const issue = await openIssue(app, alice, repo, { title: "More", body: "" });
181 if (!issue.ok) throw new Error(String(issue.error));
182 const bot = getUserByName(app.db, "bot")!;
183 const archived = getRepoById(app.db, repo.id)!;
184 expect(
185 queueAgentRun(app, archived, issue.value, { user: bot } as never, "assigned"),
186 ).toBeUndefined();
187 });
188
189 test("waking brings it back everywhere", async () => {
190 const res = await fetch(`${servers.url}/alice/rested/settings/archive`, {
191 method: "POST",
192 headers: headers(cookie),
193 body: new URLSearchParams({ archived: "0" }),
194 redirect: "manual",
195 });
196 expect(res.status).toBe(303);
197 expect(getRepoById(app.db, repo.id)!.archivedAt).toBeNull();
198 expect(await home()).toContain("/alice/rested");
199 expect(await exploreNames()).toContain("/alice/rested");
200 expect(askLinesFor(app.db, alice)).toHaveLength(1);
201 });
202 });
test/mcp.test.ts +1
@@ -174,6 +174,7 @@ describe("the forge over MCP", () => {
174174 "stop",
175175 "health",
176176 "audit",
177 "archive",
177178 "outsiders",
178179 "decisions_by",
179180 "probe",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs