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 #1742

Closed opened this
Closed without merging

scout/forge:scout/1619-archive-one-repository-its-app-spins-dow → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +546 −7
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
@@ -27,6 +27,8 @@ export type Exclusion = {
2727 export const GATE: readonly string[] = [
2828 "test/accounts-retire.test.ts",
2929 "test/accounts.test.ts",
30 "test/archive-app.test.ts",
31 "test/archive.test.ts",
3032 "test/asks-mute.test.ts",
3133 "test/agents.test.ts",
3234 "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 ForkRepoError,
@@ -45,6 +46,9 @@ import {
4546 type FileWrite,
4647 } from "../git/write.ts";
4748 import { err, ok, type Result } from "../kernel/result.ts";
49 import { appsRuntime } from "../apps/runtime.ts";
50 import { listActive } from "../core/runs.ts";
51 import { cancelRepoRun } from "./runs.ts";
4852 import { trackPullHead } from "../core/pulls.ts";
4953 import {
5054 requireParticipant,
@@ -321,6 +325,45 @@ export async function setCrewOutsiders(
321325 return ok({ on: updated.value.crewOutsiders, was: repo.crewOutsiders, dryRun });
322326 }
323327
328 export type ArchiveError = AccessError;
329
330 /**
331 * Archive a repository, or wake it (#1619). Archiving stops the app's
332 * environments (their data stays), cancels what the crew has queued or
333 * running and refuses it new runs; waking restarts production from the same
334 * data. Git, links and the page itself go on working either way.
335 */
336 export async function archiveRepo(
337 app: App,
338 actor: User | undefined,
339 repo: Repo,
340 archived: boolean,
341 ): Promise<Result<Repo, ArchiveError>> {
342 const admin = requireRepoAdmin(app, actor, repo);
343 if (!admin.ok) return admin;
344 if ((repo.archivedAt !== null) === archived) return ok(repo);
345 const updated = setArchived(
346 app.db,
347 repo,
348 archived ? new Date().toISOString() : null,
349 );
350 const runtime = appsRuntime(app);
351 if (archived) {
352 for (const kind of ["agent", "check", "deploy"] as const)
353 for (const run of listActive(app.db, kind))
354 if (run.repoId === repo.id) cancelRepoRun(app, admin.value, repo, run.id);
355 if (runtime !== undefined) await runtime.stopRepo(repo.id);
356 } else if (runtime !== undefined) {
357 await runtime.wakeRepo(updated);
358 }
359 app.bus.append({
360 kind: archived ? "repo.archived" : "repo.woken",
361 repoId: repo.id,
362 actorId: admin.value.id,
363 });
364 return ok(updated);
365 }
366
324367 export async function deleteRepo(
325368 app: App,
326369 actor: User | undefined,
src/apps/runtime.ts +18 −1
@@ -614,7 +614,12 @@ export class AppsRuntime {
614614 known.add(record.id);
615615 const repo = getRepoById(this.app.db, record.repoId);
616616 // A forge coming back does not restart a suspended owner's apps.
617 if (repo && accountActive(this.app.db, repo.ownerId))
617 // Nor an archived repository's: it sleeps until someone wakes it.
618 if (
619 repo &&
620 repo.archivedAt === null &&
621 accountActive(this.app.db, repo.ownerId)
622 )
618623 present.push({ record, repo });
619624 }
620625 for (const { record, repo } of present)
@@ -905,6 +910,8 @@ export class AppsRuntime {
905910 // A suspended or removed owner's app does not deploy.
906911 if (this.stopped || !accountActive(this.app.db, repo.ownerId))
907912 return undefined;
913 // An archived repository's app deploys nothing until it is woken (#1619).
914 if (repo.archivedAt !== null) return undefined;
908915 if (!this.mayRun(record, repo, env, commitOid)) return undefined;
909916 const state = this.envFor(record, env);
910917 state.dormant = undefined;
@@ -1883,6 +1890,16 @@ export class AppsRuntime {
18831890 removeApp(this.app.config.dataDir, state.app.id);
18841891 }
18851892
1893 /**
1894 * Bring an archived repository's production back, from the same data
1895 * (#1619). Previews come with their pulls' next push or approval.
1896 */
1897 async wakeRepo(repo: Repo): Promise<void> {
1898 const record = getAppByRepo(this.app.db, repo.id);
1899 if (record !== undefined)
1900 await this.reconcileApp(record, repo, "woken", "production");
1901 }
1902
18861903 /** Stop every environment of a repository's app; the data stays. */
18871904 async stopRepo(repoId: string): Promise<void> {
18881905 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
@@ -126,6 +126,8 @@ export interface Repo {
126126 * read only by the base's writers and crew. Null for every other one.
127127 */
128128 readonly sealedFor: string | null;
129 /** When the repository was archived (#1619), or null while it is live. */
130 readonly archivedAt: string | null;
129131 /** The origin this mirrors, or null for a native repo. */
130132 readonly origin: RepoOrigin | null;
131133 /**
@@ -170,6 +172,7 @@ interface RepoRow {
170172 last_fetch_at: string | null;
171173 fetch_error: string;
172174 origin_detached_at: string | null;
175 archived_at: string | null;
173176 }
174177
175178 // LEFT JOIN, because the origin may have been disconnected out from under a
@@ -200,6 +203,7 @@ function toRepo(row: RepoRow): Repo {
200203 directionIssueId: row.direction_issue_id,
201204 forkParentId: row.fork_parent_id,
202205 sealedFor: row.sealed_for,
206 archivedAt: row.archived_at,
203207 origin:
204208 row.origin_id !== null && row.origin_kind !== null
205209 ? {
@@ -637,8 +641,14 @@ export interface ListReposOptions {
637641 cursor?: string;
638642 /** Repositories that run an app first, each half newest first (not with `cursor`). */
639643 appsFirst?: boolean;
644 /** Archived repositories leave a listing unless asked for (#1619). */
645 includeArchived?: boolean;
640646 }
641647
648 /** The clause that keeps an archived repository out of a listing. */
649 const liveOnly = (options: ListReposOptions): string =>
650 options.includeArchived === true ? "" : " AND repo.archived_at IS NULL";
651
642652 // Visibility in SQL: public, owned, or owned by an org the viewer is on a
643653 // team of. Site admins see everything. The same rule canRead applies, so a
644654 // listing never shows a repo whose page would 404.
@@ -656,7 +666,7 @@ export function listReposVisibleTo(
656666 options: ListReposOptions = {},
657667 ): Repo[] {
658668 const params: (string | number)[] = [viewer?.id ?? ""];
659 let where = viewer ? VISIBLE : PUBLIC_VISIBLE;
669 let where = (viewer ? VISIBLE : PUBLIC_VISIBLE) + liveOnly(options);
660670 if (options.query !== undefined && options.query.trim() !== "") {
661671 params.push(`%${likeEscape(options.query.trim())}%`);
662672 const p = params.length;
@@ -690,7 +700,7 @@ export function listReposWritableTo(
690700 ): Repo[] {
691701 if (!viewer) return [];
692702 const params: (string | number)[] = [viewer.id];
693 let where = REPO_WRITABLE;
703 let where = REPO_WRITABLE + liveOnly(options);
694704 if (options.query !== undefined && options.query.trim() !== "") {
695705 params.push(`%${likeEscape(options.query.trim())}%`);
696706 const p = params.length;
@@ -1057,6 +1067,19 @@ export function updateRepoSettings(
10571067 return getRepoById(db, repo.id)!;
10581068 }
10591069
1070 /** Put a repository to rest, or wake it: the one column (#1619). */
1071 export function setArchived(
1072 db: Database,
1073 repo: Repo,
1074 archivedAt: string | null,
1075 ): Repo {
1076 db.query("UPDATE repo SET archived_at = ?2 WHERE id = ?1").run(
1077 repo.id,
1078 archivedAt,
1079 );
1080 return getRepoById(db, repo.id)!;
1081 }
1082
10601083 /** Repositories the crew drives on its own, assisted or autonomous. */
10611084 /** Every repository the forge holds, for the snapshot: nothing is left out. */
10621085 export function listEveryRepo(db: Database): Repo[] {
@@ -1071,7 +1094,7 @@ export function listAutonomousRepos(db: Database): Repo[] {
10711094 .query<
10721095 RepoRow,
10731096 []
1074 >(`${SELECT} WHERE repo.autonomy != 'off' ORDER BY repo.name`)
1097 >(`${SELECT} WHERE repo.autonomy != 'off' AND repo.archived_at IS NULL ORDER BY repo.name`)
10751098 .all()
10761099 .map(toRepo);
10771100 }
src/core/schema.ts +6
@@ -1721,6 +1721,12 @@ export const migrations: readonly string[] = [
17211721 );
17221722 CREATE INDEX release_created ON release(created_at);
17231723 `,
1724 // 84 — archived repositories (#1619): when the repository was put to rest.
1725 // NULL is a live repository. An archived one keeps its data, git and links;
1726 // it only leaves the lists, takes no new runs, and has its app stopped.
1727 `
1728 ALTER TABLE repo ADD COLUMN archived_at TEXT;
1729 `,
17241730 ];
17251731
17261732 /**
src/crew/dispatch.ts +2
@@ -264,6 +264,8 @@ export function queueAgentRun(
264264 ): Run | undefined {
265265 // A suspended or removed owner's repositories run nothing, whoever asks.
266266 if (!accountActive(app.db, repo.ownerId)) return undefined;
267 // An archived repository takes no new runs (#1619).
268 if (repo.archivedAt !== null) return undefined;
267269 // The day's ceiling gates every run the crew starts on its own, not only
268270 // the picks: a review, a feedback run or a conflict run past the ceiling
269271 // 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
@@ -124,6 +124,7 @@ import {
124124 FORKS_PER_DAY,
125125 forkRepo,
126126 privateRepoForSealed,
127 archiveRepo,
127128 updateRepoSettings,
128129 } from "../actions/repos.ts";
129130 import {
@@ -1755,6 +1756,17 @@ export function apiRoutes(router: Router<Handler>): void {
17551756 : {}),
17561757 });
17571758 if (!updated.ok) return respondAccess(updated.error, 422);
1759 // Archiving (#1619): stops the app, keeps its data, leaves the lists.
1760 if (typeof input.archived === "boolean") {
1761 const rested = await archiveRepo(
1762 ctx.app,
1763 ctx.auth.user,
1764 updated.value,
1765 input.archived,
1766 );
1767 if (!rested.ok) return respondAccess(rested.error, 422);
1768 return json(repoJson(ctx, rested.value));
1769 }
17581770 return json(repoJson(ctx, updated.value));
17591771 });
17601772
src/http/mcp.ts +40 −1
@@ -97,7 +97,7 @@ import {
9797 directionNote,
9898 OUTSIDERS_NOTE,
9999 } from "../crew/direct.ts";
100 import { setCrewOutsiders } from "../actions/repos.ts";
100 import { archiveRepo, setCrewOutsiders } from "../actions/repos.ts";
101101 import { mapJson, marksFor } from "../web/pages/map.ts";
102102 import { undoFleetOp } from "../actions/fleet.ts";
103103 import { applyLimb, isLimbAction, previewLimb } from "../actions/limbs.ts";
@@ -773,6 +773,45 @@ const TOOLS: readonly Tool[] = [
773773 );
774774 },
775775 },
776 {
777 name: "archive",
778 description:
779 "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.",
780 inputSchema: {
781 type: "object",
782 properties: {
783 repo: REPO_ARG,
784 archived: { type: "boolean" },
785 dryRun: {
786 type: "boolean",
787 description: "Plan only (the default). Send false to do it.",
788 },
789 },
790 required: ["repo"],
791 },
792 writes: true,
793 dryByDefault: true,
794 async run(ctx, user, args) {
795 const repo = repoArg(ctx, user, args);
796 if (isAnswer(repo)) return repo;
797 const was = repo.archivedAt;
798 if (typeof args["archived"] !== "boolean") return good({ archivedAt: was });
799 const dryRun = args["dryRun"] !== false;
800 if (dryRun)
801 return good({
802 archivedAt: was,
803 archived: args["archived"],
804 dryRun,
805 says: "This is the plan; nothing changed. Send dryRun: false to do it.",
806 });
807 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
808 return bad("forbidden", "archiving needs an admin token");
809 const done = await archiveRepo(ctx.app, user, repo, args["archived"]);
810 if (!done.ok)
811 return bad("forbidden", "only an admin of this app archives it");
812 return good({ archivedAt: done.value.archivedAt, dryRun });
813 },
814 },
776815 {
777816 name: "outsiders",
778817 description:
src/http/server.ts +2
@@ -313,6 +313,7 @@ import {
313313 promptSourceDelete,
314314 promptSourceRun,
315315 promptsSettingsPage,
316 repoArchive,
316317 repoDelete,
317318 settingsPage,
318319 settingsUpdate,
@@ -1160,6 +1161,7 @@ export function buildRouter(): Router<Handler> {
11601161 router.add("POST", "/:owner/:name/settings/hooks/:id/delete", webhookDelete);
11611162 router.add("GET", "/:owner/:name/settings/danger", dangerPage);
11621163 router.add("POST", "/:owner/:name/settings/delete", repoDelete);
1164 router.add("POST", "/:owner/:name/settings/archive", repoArchive);
11631165 router.add(
11641166 "POST",
11651167 "/:owner/:name/settings/origin/reconnect",
src/web/chrome.ts +17
@@ -321,6 +321,23 @@ export function scopeHeader(
321321 !options.compact && facts.description !== "",
322322 () => html`<p class="repo-desc">${facts.description}</p>`,
323323 )}
324 ${when(
325 repo?.archivedAt ?? null,
326 (at) =>
327 html`<form
328 class="repo-lineage"
329 method="post"
330 action="${base}/settings/archive"
331 >
332 ${icon("clock", 16)}archived on ${at.slice(0, 10)}
333 ${admin
334 ? html`<input type="hidden" name="archived" value="0" />${btn(
335 "Wake",
336 { size: "sm" },
337 )}`
338 : null}
339 </form>`,
340 )}
324341 ${when(
325342 parent,
326343 (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 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs