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

Archive, part 1: an admin archives or wakes one repository from Settings and the API, and its page says "archived on <date>" #2299

Closed opened this
Closed without merging

scout/forge:scout/1998-archive-part-1-an-admin-archives-or-wake → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +221 −3
README.md +13
@@ -353,6 +353,19 @@ says how the rule is set, with `by` it plans unless `dryRun: false`); in the
353353 terminal with `R` in the repository's workspace, which cycles me → decider →
354354 decider_tell.
355355
356 ### Archive a repository
357
358 An owner puts a finished repository away without deleting it. Set it in the
359 repository's Settings → Archive (the button reads Archive, or Wake once it is
360 archived); over the API with `PATCH /api/v1/repos/<owner>/<name>`
361 `{"archived": true | false}` (admin token; anyone else who can read it gets
362 403). The repository JSON carries `archivedAt`, null while it is live;
363 archiving twice keeps the first date. The repository page says "archived on
364 <date>" to everyone, with a Wake button for admins. Links, `git clone` and
365 push keep working: archiving is a label, not a lock. MCP is unchanged in this
366 part. The terminal hands Settings over to the web, as it does for every
367 setting.
368
356369 ## On your machine
357370
358371 The forge holds the truth; `forge` keeps a copy of the parts you work on, the
scripts/gate.ts +1
@@ -27,6 +27,7 @@ export type Exclusion = {
2727 };
2828
2929 export const GATE: readonly string[] = [
30 "test/repo-archive.test.ts",
3031 "test/domain-drill.test.ts",
3132 "test/conflicts.test.ts",
3233 "test/lands-once.test.ts",
src/actions/repos.ts +3 −1
@@ -267,7 +267,7 @@ export async function updateRepoSettings(
267267 if (!moved.ok) return err("unknown_branch");
268268 }
269269 const updated = writeSettings(app.db, repo, settings);
270 const changed = (
270 const changed: string[] = (
271271 [
272272 "visibility",
273273 "description",
@@ -280,6 +280,8 @@ export async function updateRepoSettings(
280280 "plansNeedNod",
281281 ] as const
282282 ).filter((k) => settings[k] !== undefined && settings[k] !== repo[k]);
283 if (settings.archived !== undefined && settings.archived !== (repo.archivedAt !== null))
284 changed.push("archived");
283285 app.bus.append({
284286 kind: "repo.settings_updated",
285287 repoId: repo.id,
src/core/migrations/20261016000000-archive-a-repository.ts added +5
@@ -0,0 +1,5 @@
1 // A repository put away without deleting it (#1998): when it was archived,
2 // or NULL while it is live.
3 export default `
4 ALTER TABLE repo ADD COLUMN archived_at TEXT;
5 `;
src/core/repos.ts +12 −1
@@ -130,6 +130,8 @@ export interface Repo {
130130 * read only by the base's writers and crew. Null for every other one.
131131 */
132132 readonly sealedFor: string | null;
133 /** When an admin archived it (ISO time), or null while it is live. */
134 readonly archivedAt: string | null;
133135 /** The origin this mirrors, or null for a native repo. */
134136 readonly origin: RepoOrigin | null;
135137 /**
@@ -169,6 +171,7 @@ interface RepoRow {
169171 direction_issue_id: string | null;
170172 fork_parent_id: string | null;
171173 sealed_for: string | null;
174 archived_at: string | null;
172175 origin_id: string | null;
173176 origin_kind: "github" | "forgejo" | "gitea" | null;
174177 origin_full_name: string | null;
@@ -208,6 +211,7 @@ function toRepo(row: RepoRow): Repo {
208211 directionIssueId: row.direction_issue_id,
209212 forkParentId: row.fork_parent_id,
210213 sealedFor: row.sealed_for,
214 archivedAt: row.archived_at,
211215 origin:
212216 row.origin_id !== null && row.origin_kind !== null
213217 ? {
@@ -1041,6 +1045,8 @@ export interface RepoSettings {
10411045 crewOutsiders?: boolean;
10421046 decisionsBy?: DecisionsBy;
10431047 plansNeedNod?: boolean;
1048 /** Put the repository away (true) or wake it (false). */
1049 archived?: boolean;
10441050 }
10451051
10461052 /** Update the mutable repo fields, leaving unspecified ones untouched. */
@@ -1054,7 +1060,7 @@ export function updateRepoSettings(
10541060 default_branch = ?4, require_review = ?5, require_checks = ?7,
10551061 autonomy = ?8, autonomy_direction = ?9, autonomy_ceiling_usd = ?10,
10561062 autonomy_slots = ?11, autonomy_by = ?12, crew_outsiders = ?13, decisions_by = ?14,
1057 plans_need_nod = ?15
1063 plans_need_nod = ?15, archived_at = ?16
10581064 WHERE id = ?6`,
10591065 ).run(
10601066 settings.visibility ?? repo.visibility,
@@ -1072,6 +1078,11 @@ export function updateRepoSettings(
10721078 (settings.crewOutsiders ?? repo.crewOutsiders) ? 1 : 0,
10731079 settings.decisionsBy ?? repo.decisionsBy,
10741080 (settings.plansNeedNod ?? repo.plansNeedNod) ? 1 : 0,
1081 settings.archived === undefined
1082 ? repo.archivedAt
1083 : settings.archived
1084 ? (repo.archivedAt ?? new Date().toISOString())
1085 : null,
10751086 );
10761087 return getRepoById(db, repo.id)!;
10771088 }
src/http/api.ts +9
@@ -1817,6 +1817,12 @@ export function apiRoutes(router: Router<Handler>): void {
18171817 const repo = loadRepo(ctx);
18181818 if (!repo) return notFound();
18191819 const input = await body(ctx.request);
1820 // Archiving is an admin's act, and a reader who is not one is told so.
1821 if (
1822 typeof input.archived === "boolean" &&
1823 !canAdmin(ctx.app.db, repo, ctx.auth.user)
1824 )
1825 return json({ error: "forbidden" }, 403);
18201826 if (input.decisionsBy !== undefined && !isDecisionsBy(input.decisionsBy))
18211827 return apiError(
18221828 "bad_decisions_by",
@@ -1856,6 +1862,9 @@ export function apiRoutes(router: Router<Handler>): void {
18561862 ...(typeof input.plansNeedNod === "boolean"
18571863 ? { plansNeedNod: input.plansNeedNod }
18581864 : {}),
1865 ...(typeof input.archived === "boolean"
1866 ? { archived: input.archived }
1867 : {}),
18591868 });
18601869 if (!updated.ok) return respondAccess(updated.error, 422);
18611870 return json(repoJson(ctx, updated.value));
src/http/server.ts +2
@@ -337,6 +337,7 @@ import {
337337 settingsPage,
338338 settingsUpdate,
339339 waveCut,
340 archiveSet,
340341 webhookCreate,
341342 webhookDelete,
342343 } from "../web/pages/settings.ts";
@@ -1169,6 +1170,7 @@ export function buildRouter(): Router<Handler> {
11691170 router.add("GET", "/:owner/:name/settings", settingsPage);
11701171 router.add("POST", "/:owner/:name/settings", settingsUpdate);
11711172 router.add("POST", "/:owner/:name/settings/wave", waveCut);
1173 router.add("POST", "/:owner/:name/settings/archive", archiveSet);
11721174 router.add("GET", "/:owner/:name/settings/app", appSettingsPage);
11731175 router.add("POST", "/:owner/:name/settings/app", appSettingsUpdate);
11741176 router.add("POST", "/:owner/:name/settings/app/disable", appDisable);
src/web/chrome.ts +13
@@ -342,6 +342,19 @@ export function scopeHeader(
342342 <span class="mono">${scope.upstream}</span>
343343 </p>`,
344344 )}
345 ${when(
346 repo?.archivedAt != null,
347 () =>
348 html`<p class="repo-lineage archived">
349 ${icon("clock", 16)}archived on ${repo!.archivedAt!.slice(0, 10)}
350 ${admin
351 ? html`<form method="post" action="${base}/settings/archive" class="inline">
352 <input type="hidden" name="archived" value="0" />
353 ${btn("Wake", { size: "sm" })}
354 </form>`
355 : null}
356 </p>`,
357 )}
345358 ${studio ? studioOriginNote(repo) : whereRow(ctx, scope)}
346359 ${tabs(items, "Repository")}
347360 </header>`;
src/web/pages/settings.ts +41 −1
@@ -320,12 +320,29 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
320320 </form>`,
321321 { head: html`${icon("rocket")}<h2>Cut a wave</h2>` },
322322 );
323 const archived = repo.archivedAt !== null;
324 const archive = card(
325 html`<form method="post" action="${base}/settings/archive">
326 <input type="hidden" name="archived" value="${archived ? "0" : "1"}" />
327 <p class="muted">
328 ${archived
329 ? html`Archived on ${repo.archivedAt!.slice(0, 10)}. Waking it
330 removes the label; nothing else changed while it was away.`
331 : html`Puts the repository away without deleting it. Its page says
332 when it was archived; links, clone and push keep working.`}
333 </p>
334 <div class="form-actions">
335 ${btn(archived ? "Wake" : "Archive", { variant: "primary" })}
336 </div>
337 </form>`,
338 { head: html`${icon("alert")}<h2>Archive</h2>` },
339 );
323340 return settingsPageResponse(
324341 ctx,
325342 repo,
326343 "general",
327344 "Settings",
328 html`${lead}<div class="mt">${body}</div><div class="mt">${wave}</div>${secrets
345 html`${lead}<div class="mt">${body}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${secrets
329346 ? html`<div class="mt">${secrets}</div>`
330347 : null}`,
331348 );
@@ -381,6 +398,29 @@ export async function settingsUpdate(ctx: Ctx): Promise<Response> {
381398 return flashTo(ctx, `${base}/settings`, flash);
382399 }
383400
401 /** POST /:owner/:name/settings/archive — archive the repository, or wake it. */
402 export async function archiveSet(ctx: Ctx): Promise<Response> {
403 const gate = await adminForm(ctx);
404 if (gate instanceof Response) return gate;
405 const { repo, form } = gate;
406 const want = field(form, "archived");
407 if (want !== "1" && want !== "0")
408 return flashTo(ctx, `${repoBase(repo)}/settings`, {
409 tone: "danger",
410 message: "Say whether to archive or wake it.",
411 });
412 const set = await updateRepoSettings(ctx.app, ctx.auth.user, repo, {
413 archived: want === "1",
414 });
415 return flashTo(
416 ctx,
417 `${repoBase(repo)}/settings`,
418 set.ok
419 ? { message: want === "1" ? "Archived." : "Awake again." }
420 : { tone: "danger", message: "That could not be saved." },
421 );
422 }
423
384424 /** POST /:owner/:name/settings/wave — open the draft of the next wave. */
385425 export async function waveCut(ctx: Ctx): Promise<Response> {
386426 const gate = await adminForm(ctx);
test/repo-archive.test.ts added +122
@@ -0,0 +1,122 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { listEvents } from "../src/core/events.ts";
7 import { getRepo } from "../src/core/repos.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9
10 describe("archive and wake a repository", () => {
11 let dataDir: string;
12 let app: App;
13 let servers: Servers;
14 let base: string;
15 const cookies: Record<string, string> = {};
16
17 const signup = async (username: string) => {
18 const res = await fetch(`${base}/signup`, {
19 method: "POST",
20 body: new URLSearchParams({ username, email: `${username}@f.dev`, password: "archive-password" }),
21 redirect: "manual",
22 });
23 return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
24 };
25 const patch = (who: string, archived: boolean) =>
26 fetch(`${base}/api/v1/repos/olive/proj`, {
27 method: "PATCH",
28 headers: { cookie: cookies[who]!, "content-type": "application/json", origin: base },
29 body: JSON.stringify({ archived }),
30 });
31 const read = async () =>
32 (await (await fetch(`${base}/api/v1/repos/olive/proj`, { headers: { cookie: cookies.olive! } })).json()) as {
33 archivedAt: string | null;
34 };
35 const form = (who: string, archived: string, headers: Record<string, string> = {}) =>
36 fetch(`${base}/olive/proj/settings/archive`, {
37 method: "POST",
38 headers: { cookie: cookies[who]!, ...headers },
39 body: new URLSearchParams({ archived }),
40 redirect: "manual",
41 });
42
43 beforeAll(async () => {
44 dataDir = await mkdtemp(join(tmpdir(), "forge-archive-"));
45 app = createApp({ dataDir, port: 0 });
46 servers = await serve(app);
47 base = servers.url;
48 cookies.olive = await signup("olive");
49 cookies.stranger = await signup("stranger");
50 await fetch(`${base}/new`, {
51 method: "POST",
52 headers: { cookie: cookies.olive! },
53 body: new URLSearchParams({ name: "proj", visibility: "public", description: "x" }),
54 redirect: "manual",
55 });
56 });
57 afterAll(async () => {
58 servers.stop();
59 app.close();
60 await rm(dataDir, { recursive: true, force: true });
61 });
62
63 test("a live repository carries archivedAt null", async () => {
64 expect((await read()).archivedAt).toBeNull();
65 });
66
67 test("a non-admin gets a 403 and nothing changes", async () => {
68 expect((await patch("stranger", true)).status).toBe(403);
69 expect(getRepo(app.db, "olive", "proj")!.archivedAt).toBeNull();
70 });
71
72 test("a cross-origin form POST is refused", async () => {
73 expect((await form("olive", "1", { origin: "http://evil.example" })).status).toBe(403);
74 expect(getRepo(app.db, "olive", "proj")!.archivedAt).toBeNull();
75 });
76
77 test("archive then wake round-trips through the API, and the page says so", async () => {
78 const archived = await patch("olive", true);
79 expect(archived.status).toBe(200);
80 const stamp = ((await archived.json()) as { archivedAt: string }).archivedAt;
81 expect(stamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);
82 // Archiving again keeps the first date.
83 expect(((await (await patch("olive", true)).json()) as { archivedAt: string }).archivedAt).toBe(stamp);
84
85 const html = await (await fetch(`${base}/olive/proj`, { headers: { cookie: cookies.olive! } })).text();
86 expect(html).toContain(`archived on ${stamp.slice(0, 10)}`);
87 expect(html).toContain('action="/olive/proj/settings/archive"');
88 // A stranger sees the line but no Wake button.
89 const seen = await (await fetch(`${base}/olive/proj`, { headers: { cookie: cookies.stranger! } })).text();
90 expect(seen).toContain(`archived on ${stamp.slice(0, 10)}`);
91 expect(seen).not.toContain("/settings/archive");
92
93 expect((await (await patch("olive", false)).json() as { archivedAt: string | null }).archivedAt).toBeNull();
94 const woke = await (await fetch(`${base}/olive/proj`, { headers: { cookie: cookies.olive! } })).text();
95 expect(woke).not.toContain("archived on");
96 });
97
98 test("the Settings form archives and wakes for an admin only", async () => {
99 expect([403, 404]).toContain((await form("stranger", "1")).status);
100 expect(getRepo(app.db, "olive", "proj")!.archivedAt).toBeNull();
101 expect((await form("olive", "1")).status).toBe(303);
102 expect(getRepo(app.db, "olive", "proj")!.archivedAt).not.toBeNull();
103 expect((await form("olive", "0")).status).toBe(303);
104 expect(getRepo(app.db, "olive", "proj")!.archivedAt).toBeNull();
105 });
106
107 test("the record says archived changed, and not when nothing did", async () => {
108 const repoId = getRepo(app.db, "olive", "proj")!.id;
109 const changed = () =>
110 listEvents(app.db, { repoId, kind: "repo.settings_updated" }).map(
111 (e) => e.payload.changed as string[],
112 );
113 // Newest first: what a call added is the head of the list.
114 let before = changed().length;
115 expect((await patch("olive", false)).status).toBe(200);
116 expect(changed().slice(0, changed().length - before).flat()).not.toContain("archived");
117 before = changed().length;
118 expect((await patch("olive", true)).status).toBe(200);
119 expect(changed().slice(0, changed().length - before).flat()).toContain("archived");
120 expect((await patch("olive", false)).status).toBe(200);
121 });
122 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs