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

An admin marks a repository as a template for new forges, and the mark is listed in one place #12498

Merged opened this

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

Merged

scout/forge:scout/12431-an-admin-marks-a-repository-as-a-templat → main 12 commits fork 6 threads · 6 unresolved

  • Merged. scout/12431-an-admin-marks-a-repository-as-a-templat was merged into main as 870e51b.

Review

Sign in to review this change.
20 files changed +474 −8
docs/MCP.md +1 −1
@@ -185,7 +185,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
185185 | `releases` | — | Kept releases, newest first | 298 |
186186 | `repo` | `open`, `add`, `remove`, `close` | One repository you can read, as GET /api/v1/repos/:owner/:name | 383 |
187187 | `repo_labels` | — | Repo labels: list (default), create, update, remove (admin token) | 351 |
188 | `repo_settings` | — | Read, change, rename (name) or move (newOwner) a repo: PATCH /api/v1/repos/:owner/:name (admin); mirrorPacks mirrors the packs' upstreams | 484 |
188 | `repo_settings` | — | Read, change, rename (name) or move (newOwner) a repo: PATCH /api/v1/repos/:owner/:name (admin); mirrorPacks mirrors the packs' upstreams | 514 |
189189 | `reports` | `accept`, `dismiss` | Outsiders' reports; `id`+`action`: accept or dismiss | 355 |
190190 | `restore_drill` | — | Drill-restore the newest snapshot | 216 |
191191 | `returns` | — | What crew tokens bought in `days` (1–90, default 7): dollars, runs, landed, cost/change | 284 |
docs/features/README.md +1
@@ -33,6 +33,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
3333 - [Pixel art: the crew's faces](pixel.md)
3434 - [Plans on the home](home-plans.md)
3535 - [Returning visitors](returning-visitors.md)
36 - [Template mark](repo-template.md)
3637 - [The explorer's sorts](explore.md)
3738 - [The feed pages by cursor](feed-cursor.md)
3839 - [The fork tree](fork-tree.md)
docs/features/repo-template.md added +11
@@ -0,0 +1,11 @@
1 # Template mark
2
3 An admin of a repository marks it as a template for new forges (#12431). This is the mark alone; starting a forge from it comes later.
4
5 - Page: Settings › App › "New forges may start from this repository." (its own form; the flash names the mark only when it changed).
outdated

Page and API and MCP are listed but no terminal screen exists: both doors are required. Add a src/tui/ screen and list it here.

6 - Terminal: the palette's "Template" screen while a repository you administer is open (`src/tui/screens/template.ts`); `t` marks or clears it, and the write is a `repo.settings_updated` event an open settings page follows.
7 - API: `PATCH /api/v1/repos/:owner/:name` with `{ "template": true|false }` (422 `bad_template`, "template is true or false", for anything else; the MCP tool answers the same code and words).
8 - MCP: `repo_settings` with `{ repo, template }`; the answer carries `template` and `says`.
9 - List: `GET /api/v1/templates` (`limit`, `cursor`), only repositories the reader may see, by the same rule as the repository list.
10
11 Only a person who administers the repository sets it; an agent is refused as `not_found`. Stored as `repo.is_template`; the change is in the `repo.settings_updated` event.
src/actions/repos.ts +2
@@ -373,6 +373,7 @@ const AUDITED = [
373373 "crewOutsiders",
374374 "decisionsBy",
375375 "plansNeedNod",
376 "template",
376377 "autonomySlots",
377378 "plannerSlots",
378379 "reviewerSlots",
@@ -416,6 +417,7 @@ export async function updateRepoSettings(
416417 (settings.crewOutsiders !== undefined ||
417418 settings.decisionsBy !== undefined ||
418419 settings.plansNeedNod !== undefined ||
420 settings.template !== undefined ||
419421 settings.archived !== undefined) &&
420422 admin.value.kind === "agent"
421423 )
src/contract/openapi/routes/getApiV1Templates.ts added +4
@@ -0,0 +1,4 @@
1 import { type Route, limitTo } from "../shared.ts";
2 import { LIST_LIMIT_MAX } from "../../../core/issues.ts";
3
4 export const route: Route = { method: "get", path: "/api/v1/templates", summary: "List the repositories an admin marked as templates for new forges, only those the viewer can see; answers { items, next_cursor }", auth: false, role: "anonymous", query: { limit: limitTo(LIST_LIMIT_MAX), cursor: "string" }, refusals: { invalid_limit: "limit is not a whole number from 1 to 200 (422)", invalid_cursor: "cursor is not the next_cursor of a previous page (422)" } };
src/contract/openapi/routes/index.ts +1
@@ -206,6 +206,7 @@ export { route as getApiV1TelemetryHome } from "./getApiV1TelemetryHome.ts";
206206 export { route as getApiV1TelemetryRoutes } from "./getApiV1TelemetryRoutes.ts";
207207 export { route as getApiV1TelemetrySources } from "./getApiV1TelemetrySources.ts";
208208 export { route as getApiV1TelemetrySystem } from "./getApiV1TelemetrySystem.ts";
209 export { route as getApiV1Templates } from "./getApiV1Templates.ts";
209210 export { route as getApiV1Tokens } from "./getApiV1Tokens.ts";
210211 export { route as getApiV1Usage } from "./getApiV1Usage.ts";
211212 export { route as getApiV1User } from "./getApiV1User.ts";
src/contract/openapi/routes/patchApiV1ReposOwnerName.ts +2
@@ -21,6 +21,7 @@ export const route: Route = {
2121 crewOutsiders: "boolean",
2222 decisionsBy: "string",
2323 plansNeedNod: "boolean",
24 template: "boolean",
2425 },
2526 refusals: {
2627 invalid_name: "422: a name is letters, digits, dots, dashes and underscores",
@@ -29,6 +30,7 @@ export const route: Route = {
2930 bad_archived: "422: archived is true or false",
3031 bad_decisions_by: "422: decisionsBy is me, decider or decider_tell",
3132 bad_plans_need_nod: "422: plansNeedNod is true or false",
33 bad_template: "422: template is true or false",
3234 bad_show_provenance: "422: showProvenance is true or false",
3335 no_provenance: `422: ${FAMILY_WORDS.no_provenance}`,
3436 forbidden: "403: only an admin archives or wakes",
src/contract/tags.ts +1
@@ -29,6 +29,7 @@ const ALIAS: Readonly<Record<string, string>> = {
2929 transfer: "repos",
3030 atlas: "repos",
3131 tags: "repos",
32 templates: "repos",
3233 branches: "repos",
3334 commits: "repos",
3435 contents: "repos",
src/core/migration-pins/20261114130000-repo-template.pin added +1
@@ -0,0 +1,1 @@
1 1dc23b89f6a0ac1a733d48f63df24d8e2777c28f7951fb3906b1120949fec3d0
src/core/migrations/20261114130000-repo-template.ts added +5
@@ -0,0 +1,5 @@
1 // A repository an admin marks as a template for new forges (#12431): one flag beside the
2 // repository's other settings, off for every row that exists. Additive.
3 export default `
4 ALTER TABLE repo ADD COLUMN is_template INTEGER NOT NULL DEFAULT 0;
5 `;
src/core/repos.ts +12 −2
@@ -166,6 +166,8 @@ export interface Repo {
166166 readonly decisionsBy: DecisionsBy;
167167 /** "Plans need a nod": a plan is stored as a proposal, not opened. */
168168 readonly plansNeedNod: boolean;
169 /** An admin's mark: a new forge may start from this repository (#12431). */
170 readonly template: boolean;
169171 /** The issue the planner is given, when the map has run dry. */
170172 readonly directionIssueId: string | null;
171173 /** The repo this was forked from, or null. */
@@ -217,6 +219,7 @@ interface RepoRow {
217219 crew_outsiders: number;
218220 decisions_by: string;
219221 plans_need_nod: number;
222 is_template: number;
220223 direction_issue_id: string | null;
221224 fork_parent_id: string | null;
222225 sealed_for: string | null;
@@ -263,6 +266,7 @@ function toRepo(row: RepoRow): Repo {
263266 crewOutsiders: row.crew_outsiders === 1,
264267 decisionsBy: isDecisionsBy(row.decisions_by) ? row.decisions_by : "me",
265268 plansNeedNod: row.plans_need_nod === 1,
269 template: row.is_template === 1,
266270 directionIssueId: row.direction_issue_id,
267271 forkParentId: row.fork_parent_id,
268272 sealedFor: row.sealed_for,
@@ -859,6 +863,8 @@ export interface ListReposOptions {
859863 archivedOnly?: boolean;
860864 /** Only this owner's repositories (a username, any case). */
861865 owner?: string;
866 /** Only repositories an admin marked as a template for new forges (#12431). */
867 templatesOnly?: boolean;
862868 /**
863869 * Leave out what an unclaimed start owns (`core/starts.ts`): a listing the
864870 * forge offers strangers (explore, llms.txt, the sitemap) names it only once
@@ -901,6 +907,7 @@ function visibleClause(
901907 }
902908 if (options.withoutArchived === true) where += " AND repo.archived_at IS NULL";
903909 if (options.archivedOnly === true) where += " AND repo.archived_at IS NOT NULL";
910 if (options.templatesOnly === true) where += " AND repo.is_template = 1";
904911 if (options.withoutUnclaimed === true)
905912 where += " AND NOT EXISTS (SELECT 1 FROM start_account WHERE start_account.user_id = repo.owner_id AND start_account.claimed_at IS NULL)";
906913 params.push(pageLimit(options.limit));
@@ -957,7 +964,7 @@ const SHOWN = [
957964 "repo.default_branch", "repo.protect_default", "repo.require_review", "repo.require_checks",
958965 "repo.landing", "repo.autonomy", "repo.autonomy_direction", "repo.autonomy_slots",
959966 "repo.planner_slots", "repo.reviewer_slots", "repo.polish_share", "repo.autonomy_by",
960 "repo.crew_outsiders", "repo.decisions_by", "repo.plans_need_nod", "repo.direction_issue_id",
967 "repo.crew_outsiders", "repo.decisions_by", "repo.plans_need_nod", "repo.is_template", "repo.direction_issue_id",
961968 "repo.fork_parent_id", "repo.sealed_for", "repo.archived_at", "repo.origin_id",
962969 "repo.origin_full_name", "repo.origin_html_url", "repo.last_fetch_at", "repo.fetch_error",
963970 "repo.origin_detached_at",
@@ -1377,6 +1384,8 @@ export interface RepoSettings {
13771384 /** Archive (true) or wake (false); the time is stamped here. */
13781385 archived?: boolean;
13791386 plansNeedNod?: boolean;
1387 /** Mark (true) or unmark (false) as a template for new forges. */
1388 template?: boolean;
13801389 }
13811390
13821391 /** The repositories still awake: what Yours lists before anyone types a filter. */
@@ -1401,7 +1410,7 @@ export function updateRepoSettings(
14011410 autonomy = ?8, autonomy_direction = ?9,
14021411 autonomy_slots = ?10, autonomy_by = ?11, crew_outsiders = ?12, decisions_by = ?13,
14031412 plans_need_nod = ?14, planner_slots = ?15, reviewer_slots = ?16, polish_share = ?17,
1404 landing = ?18
1413 landing = ?18, is_template = ?19
14051414 WHERE id = ?6`,
14061415 ).run(
14071416 settings.visibility ?? repo.visibility,
@@ -1422,6 +1431,7 @@ export function updateRepoSettings(
14221431 settings.reviewerSlots ?? repo.reviewerSlots,
14231432 settings.polishShare ?? repo.polishShare,
14241433 settings.landing ?? repo.landing,
1434 (settings.template ?? repo.template) ? 1 : 0,
14251435 );
14261436 forgetListings(db);
14271437 return getRepoById(db, repo.id)!;
src/core/template_words.ts added +5
@@ -0,0 +1,5 @@
1 /** The one sentence a page and the MCP say after marking or unmarking a template (#12431). */
2 export const templateSaid = (on: boolean): string =>
3 on
4 ? "Marked as a template: new forges may start from it."
5 : "No longer a template.";
src/http/api.ts +16
@@ -1623,6 +1623,18 @@ export function apiRoutes(router: Router<Handler>): void {
16231623 return timePhase(ctx.request, "render", () => json(paged(items, query.limit, (r) => r.id), 200, headers));
16241624 });
16251625
1626 // The repositories marked as templates for new forges (#12431): the same
1627 // visibility the repository list and page use, so a private one never shows.
1628 router.add("GET", "/api/v1/templates", (ctx) => {
1629 const query = repoQuery(ctx);
1630 if (query instanceof Response) return query;
1631 const items = listReposVisibleTo(ctx.app.db, ctx.auth.user, { ...query, templatesOnly: true });
1632 return json(paged(items, query.limit, (r) => r.id), 200, {
1633 "cache-control": "private, no-cache",
1634 vary: "authorization, cookie",
1635 });
1636 });
1637
16261638 router.add("POST", "/api/v1/repos", async (ctx) => {
16271639 const denied = requireScope(ctx, "rw");
16281640 if (denied) return denied;
@@ -1689,6 +1701,8 @@ export function apiRoutes(router: Router<Handler>): void {
16891701 );
16901702 if (input.plansNeedNod !== undefined && typeof input.plansNeedNod !== "boolean")
16911703 return apiError("bad_plans_need_nod", 422, "plansNeedNod is true or false");
1704 if (input.template !== undefined && typeof input.template !== "boolean")
1705 return apiError("bad_template", 422, "template is true or false");
16921706 if (input.showProvenance !== undefined) {
16931707 if (typeof input.showProvenance !== "boolean")
16941708 return apiError("bad_show_provenance", 422, "showProvenance is true or false");
@@ -1750,6 +1764,8 @@ export function apiRoutes(router: Router<Handler>): void {
17501764 ...(typeof input.archived === "boolean"
17511765 ? { archived: input.archived }
17521766 : {}),
1767 // A template for new forges (#12431): an admin's, never an agent's.
1768 ...(typeof input.template === "boolean" ? { template: input.template } : {}),
17531769 // Whether a plan waits for a nod: an admin's, never an agent's.
17541770 ...(typeof input.plansNeedNod === "boolean"
17551771 ? { plansNeedNod: input.plansNeedNod }
src/http/mcp/tools/repo_settings.ts +8 −2
@@ -4,11 +4,12 @@ import { mirrorPacks, reportWords } from "../../../packs/mirror.ts";
44 import { rejectedMarkedSentence } from "../../../packs/marked.ts";
55 import { setPackRepos } from "../../../packs/set.ts";
66 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
7 import { templateSaid } from "../../../core/template_words.ts";
78 import { VISIBILITY_WORDS } from "../../../core/arg_words.ts";
89
910 export const tool: Tool = {
1011 name: "repo_settings",
11 doc: "`{ packRepos: [\"packs/games\", …] }` (admin) sets the repositories /packs lists, as Settings › Packs does (public repos with a pack.json at the root; at most 20; an empty list lists none), and answers `{ repos, problems }` with the ones left out and why; it shows on /packs at once; a word that is not `owner/name` is `invalid`. `{ mirrorPacks: true }` (admin) brings each https source in a marked pack repo's pack.json in once as a read-only `packs/<app>` that follows its upstream, and answers `{ made, kept, failed, says }`; running it again makes nothing new. `{ repo, name }` (admin) renames the repository as `PATCH /api/v1/repos/:owner/:name` with `name` does: its pulls, issues, forks, app and tokens stay, its old web and git address redirect to the new one (a push there is refused naming it), with the codes `name_taken`, `same_name`, `invalid_name`, `move_failed`; give it alone; answers `{ repo, description, visibility }` at the new path. `{ repo, description?, visibility?, newOwner? }` (admin): `newOwner` moves the repository to that account or org as `POST /api/v1/repos/:owner/:name/transfer` does, with its codes and sentences (`name_taken`, `same_owner`, `move_failed`, `forbidden_owner`, `unknown_owner`) and answers `{ repo, description, visibility }` at the new path, and cannot be combined with the others; otherwise change a repository's description and visibility as `PATCH /api/v1/repos/:owner/:name` does, for the same callers (a repository admin); answers `{ repo, description, visibility }` (with none to change it only reads); a visibility other than public or private is `invalid`",
12 doc: "`{ packRepos: [\"packs/games\", …] }` (admin) sets the repositories /packs lists, as Settings › Packs does (public repos with a pack.json at the root; at most 20; an empty list lists none), and answers `{ repos, problems }` with the ones left out and why; it shows on /packs at once; a word that is not `owner/name` is `invalid`. `{ mirrorPacks: true }` (admin) brings each https source in a marked pack repo's pack.json in once as a read-only `packs/<app>` that follows its upstream, and answers `{ made, kept, failed, says }`; running it again makes nothing new. `{ repo, name }` (admin) renames the repository as `PATCH /api/v1/repos/:owner/:name` with `name` does: its pulls, issues, forks, app and tokens stay, its old web and git address redirect to the new one (a push there is refused naming it), with the codes `name_taken`, `same_name`, `invalid_name`, `move_failed`; give it alone; answers `{ repo, description, visibility }` at the new path. `{ repo, description?, visibility?, newOwner? }` (admin): `newOwner` moves the repository to that account or org as `POST /api/v1/repos/:owner/:name/transfer` does, with its codes and sentences (`name_taken`, `same_owner`, `move_failed`, `forbidden_owner`, `unknown_owner`) and answers `{ repo, description, visibility }` at the new path, and cannot be combined with the others; otherwise change a repository's description and visibility as `PATCH /api/v1/repos/:owner/:name` does, for the same callers (a repository admin); answers `{ repo, description, visibility }` (with none to change it only reads); a visibility other than public or private is `invalid`. `template` (boolean, admin, a person's never an agent's) marks or unmarks it a template for new forges and answers `template` and `says`",
1213 description:
1314 "Read, change, rename (name) or move (newOwner) a repo: PATCH /api/v1/repos/:owner/:name (admin); mirrorPacks mirrors the packs' upstreams.",
1415 inputSchema: {
@@ -17,6 +18,7 @@ export const tool: Tool = {
1718 repo: REPO_ARG,
1819 description: { type: "string", maxLength: 2000 },
1920 visibility: { type: "string", enum: ["public", "private"] },
21 template: { type: "boolean" },
2022 newOwner: { type: "string", maxLength: 64 },
2123 name: { type: "string", maxLength: 100 },
2224 mirrorPacks: { type: "boolean" },
@@ -40,7 +42,9 @@ export const tool: Tool = {
4042 }
4143 const repo = repoArg(ctx, user, args);
4244 if (isAnswer(repo)) return repo;
43 const { description, visibility, newOwner, name } = args;
45 const { description, visibility, newOwner, name, template } = args;
46 if (template !== undefined && typeof template !== "boolean")
47 return bad("bad_template", "template is true or false");
outdated

The API answers bad_template (422) for this; the MCP says 'invalid'. Use the same code and words.

4448 if (name !== undefined) {
4549 if (typeof name !== "string" || name.length === 0 || name.length > 100)
4650 return bad("invalid_name", TRANSFER_SAID.invalid_name);
@@ -80,6 +84,7 @@ export const tool: Tool = {
8084 const updated = await updateRepoSettings(ctx.app, user, repo, {
8185 ...(visibility !== undefined ? { visibility } : {}),
8286 ...(description !== undefined ? { description } : {}),
87 ...(template !== undefined ? { template } : {}),
8388 });
8489 if (!updated.ok)
8590 return bad(updated.error === "not_found" ? "not_found" : "forbidden", updated.error);
@@ -87,6 +92,7 @@ export const tool: Tool = {
8792 repo: `${updated.value.ownerName}/${updated.value.name}`,
8893 description: updated.value.description,
8994 visibility: updated.value.visibility,
95 ...(template !== undefined ? { template: updated.value.template, says: templateSaid(template) } : {}),
9096 });
9197 },
9298 };
src/http/route_marks.ts +1
@@ -89,6 +89,7 @@ export const HEADS: Readonly<Record<string, Mark | "mixed">> = {
8989 "/api/v1/telemetry": "open",
9090 "/api/v1/thoughts": "open",
9191 "/api/v1/timers": "open",
92 "/api/v1/templates": "open",
9293 "/api/v1/tokens": "open",
9394 "/api/v1/usage": "open",
9495 "/api/v1/user": "open",
src/tui/screens/template.ts added +66
@@ -0,0 +1,66 @@
1 /**
2 * The template mark, in the terminal (#12431): the App pane's toggle on the
3 * settings page, from the same action (`updateRepoSettings`) and the same gate,
4 * a repository's admins. `t` marks or unmarks. The write is a
5 * `repo.settings_updated` event on the bus, so an open settings page redraws,
6 * and this screen follows a write made there.
7 */
8
9 import { updateRepoSettings } from "../../actions/repos.ts";
10 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
11 import { templateSaid } from "../../core/template_words.ts";
12 import type { Ctx, Screen } from "../app/app.ts";
13 import { binding } from "../app/keys.ts";
14 import type { Command } from "../app/palette.ts";
15 import type { Session } from "../session.ts";
16 import { style } from "../term/style.ts";
17 import { truncate } from "../term/width.ts";
18 import { live } from "./common.ts";
19
20 /** The toggle's gate: an admin of the repository. */
21 export const mayMarkTemplate = (f: Session, repo: Repo): boolean => f.user !== undefined && canAdmin(f.db, repo, f.user);
22
23 export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
24 const now = (): Repo => getRepoById(f.db, repo.id) ?? repo;
25 return {
26 title: `${repo.ownerName}/${repo.name} — Template`,
27 keys: [binding(["t"], "mark or unmark as a template")],
28 async load(signal) {
29 live(f, signal, { repoId: repo.id, kinds: ["repo.settings_updated"] }, () => ctx.invalidate());
30 },
31 render(area, s) {
32 const c = ctx.theme.c;
33 const on = now().template;
34 const said = !mayMarkTemplate(f, repo)
35 ? "An admin of this repository marks it a template."
36 : on
37 ? "New forges may start from this repository. t clears it."
38 : "Not a template. t lets new forges start from this repository.";
39 s.text(area.x, area.y, truncate(said, area.w), style(c.mutedFg, c.bg), area.x + area.w);
40 },
41 key(e) {
42 if (e.ctrl || e.alt || e.key !== "t") return false;
43 const set = mayMarkTemplate(f, repo)
44 ? updateRepoSettings(f.app, f.user, now(), { template: !now().template })
45 : undefined;
46 void Promise.resolve(set).then((r) => {
47 ctx.toast(r?.ok ? templateSaid(r.value.template) : "An admin of this repository marks it a template.", r?.ok ? undefined : "danger");
48 ctx.invalidate();
49 });
50 return true;
51 },
52 };
53 }
54
55 /** The palette's command while a repository the viewer administers is open. */
56 export function templateCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
57 if (repo === undefined || !mayMarkTemplate(f, repo)) return [];
58 return [
59 {
60 id: "template",
61 title: `${repo.ownerName}/${repo.name} — Template`,
62 hint: "let new forges start from this repository",
63 run: () => ctx.push(templateScreen(f, ctx, repo)),
64 },
65 ];
66 }
src/tui/screens/workspace.ts +2
@@ -173,6 +173,7 @@ import { autonomyCommands } from "./autonomy.ts";
173173 import { trafficCommands } from "./trafficview.ts";
174174 import { chaptersCommands } from "./chapters.ts";
175175 import { outsideAgentsCommands } from "./outsideagents.ts";
176 import { templateCommands } from "./template.ts";
176177 import { buildCacheCommands } from "./buildcache.ts";
177178 import { schedulesCommands } from "./schedules.ts";
178179 import { deskCommands } from "./desk.ts";
@@ -2010,6 +2011,7 @@ export function workspaceScreen(
20102011 ...schedulesCommands(f, ctx, repo),
20112012 ...deskCommands(f, ctx, repo),
20122013 ...outsideAgentsCommands(f, ctx, repo),
2014 ...templateCommands(f, ctx, repo),
20132015 ...buildCacheCommands(f, ctx, repo),
20142016 ...landCommands(f, ctx, repo),
20152017 ...shiftCommands(f, ctx, repo, () => screen),
src/web/pages/settings.ts +14 −3
@@ -8,6 +8,7 @@
88 * same-origin POST and every one of them says what happened.
99 */
1010
11 import { templateSaid } from "../../core/template_words.ts";
1112 import { POLISH_SHARE_DEFAULT, POLISH_SHARE_MAX } from "../../crew/polish_share.ts";
1213 import { appLimitWords } from "../../actions/app_limit.ts";
1314 import { showProvenance } from "../../actions/provenance.ts";
@@ -460,14 +461,16 @@ export async function settingsUpdate(ctx: Ctx): Promise<Response> {
460461 // Sent only by a form that draws the field; anything but a whole 0–50 is refused by the action.
461462 ...(form.get("polishShareShown") !== null ? { polishShare: parseShare(field(form, "polishShare")) } : {}),
462463 };
464 // The template mark has a form of its own (the App pane); no other form may clear it.
465 const mark = form.get("templateShown") !== null ? { template: form.get("template") !== null } : {};
463466 const updated = await updateRepoSettings(
464467 ctx.app,
465468 ctx.auth.user,
466469 repo,
467 card === "about" ? about : card === "gates" ? gates : { ...about, ...gates },
470 card === "template" ? mark : card === "about" ? about : card === "gates" ? gates : { ...about, ...gates },
468471 );
469472 const flash: Flash = updated.ok
470 ? { message: "Settings saved." }
473 ? { message: card === "template" && updated.value.template !== repo.template ? templateSaid(updated.value.template) : "Settings saved." }
471474 : {
472475 tone: "danger",
outdated

The template sentence is shown on every gates save (templateShown is always posted), even when nothing about the template changed. Compare against the previous value.

473476 message:
@@ -477,7 +480,7 @@ export async function settingsUpdate(ctx: Ctx): Promise<Response> {
477480 ? `Polish share is a whole number of percent, 0 to ${POLISH_SHARE_MAX}.`
478481 : "Those settings could not be saved.",
479482 };
480 return flashTo(ctx, `${base}/settings`, flash);
483 return flashTo(ctx, card === "template" ? `${base}/settings/app` : `${base}/settings`, flash);
481484 }
482485
483486 /** A return address that stays on this origin, as a path; anything else is undefined. */
@@ -813,6 +816,14 @@ function appSettingsView(
813816 </div>
814817 ${when(blocked !== undefined, () => html`<div class="mt">${blockedNote(base, blocked!)}</div>`)}
815818 ${when(egress !== undefined, () => html`<div class="mt">${appEgressView(base, egress!)}</div>`)}
819 <div class="mt">
820 <form method="post" action="${base}/settings">
821 <input type="hidden" name="card" value="template" />
822 ${toggleLine("template", "New forges may start from this repository.", repo.template,
823 "Marked repositories are listed at /api/v1/templates to whoever can read them.", "templateShown")}
824 <div class="form-actions">${btn("Save", { variant: "primary" })}</div>
825 </form>
826 </div>
816827 <div class="mt">
817828 ${card(
818829 html`<p>
test/repo-template-flag.test.ts added +320
@@ -0,0 +1,320 @@
1 /**

Missing: the page POST (set, clear, cross-origin and agent refusal), the TUI, and limit/cursor on the list.

2 * An admin marks a repository as a template for new forges (#12431): the API and
3 * the `repo_settings` MCP tool set and clear it with the same words, an agent is
4 * refused, and the list of templates holds only what the reader may see.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { addToCrew, createAgent } from "../src/actions/crew.ts";
12 import { updateRepoSettings } from "../src/actions/repos.ts";
13 import type { Agent } from "../src/core/agents.ts";
14 import { createRepo, getRepoById, type Repo } from "../src/core/repos.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { templateSaid } from "../src/core/template_words.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { createForgeApp } from "../src/tui/forge.ts";
20 import { repoScreen } from "../src/tui/screens/repo.ts";
21 import { templateCommands, templateScreen } from "../src/tui/screens/template.ts";
22 import { local } from "../src/tui/screens/where.ts";
23 import { headlessTerminal } from "../src/tui/term/terminal.ts";
24 import { listEvents } from "../src/core/events.ts";
25 import { settleApp } from "./helpers/tui.ts";
26 import { proveAll } from "./helpers/verified.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28
29 quietLogs();
30
31 let dataDir: string;
32 let app: App;
33 let servers: Servers;
34 let owner: User;
35 let stranger: User;
36 let bot: Agent;
37 let pub: Repo;
38 const tok: Record<string, string> = {};
39
40 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
41 if (!r.ok) throw new Error(JSON.stringify(r.error));
42 return r.value;
43 };
44 const marked = (r: Repo): boolean => getRepoById(app.db, r.id)!.template;
45 const patch = (token: string, repo: string, body: unknown) =>
46 fetch(`${servers.url}/api/v1/repos/maker/${repo}`, {
47 method: "PATCH",
48 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
49 body: JSON.stringify(body),
50 });
51 const listed = async (token?: string): Promise<string[]> => {
52 const res = await fetch(`${servers.url}/api/v1/templates`, {
53 headers: token === undefined ? {} : { authorization: `Bearer ${token}` },
54 });
55 expect(res.status).toBe(200);
56 return ((await res.json()) as { items: { name: string }[] }).items.map((i) => i.name).sort();
57 };
58 async function mcp(token: string, args: unknown): Promise<{ error?: string; value?: any }> {
59 const res = await fetch(`${servers.url}/mcp`, {
60 method: "POST",
61 headers: {
62 "content-type": "application/json",
63 accept: "application/json, text/event-stream",
64 authorization: `Bearer ${token}`,
65 },
66 body: JSON.stringify({
67 jsonrpc: "2.0",
68 id: 1,
69 method: "tools/call",
70 params: { name: "repo_settings", arguments: args },
71 }),
72 });
73 const body = (await res.json()) as any;
74 const text: string = body.result.content[0].text;
75 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
76 }
77
78 beforeAll(async () => {
79 dataDir = await mkdtemp(join(tmpdir(), "forge-template-"));
80 app = createApp({ dataDir, port: 0 });
81 servers = await serve(app);
82 const make = async (username: string) =>
83 ok(
84 await createUser(app.db, {
85 origin: "seed",
86 trusted: true,
87 username,
88 email: `${username}@forge.local`,
89 password: "a-good-passphrase",
90 adminIfFirst: true,
91 }),
92 );
93 const founder = await make("founder");
94 owner = await make("maker");
95 stranger = await make("stranger");
96 pub = ok(await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "starter", visibility: "public" }));
97 ok(await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "secret", visibility: "private" }));
98 bot = ok(await createAgent(app, founder, { username: "bot" }));
99 proveAll(app);
100 expect(addToCrew(app, founder, pub, "bot").ok).toBe(true);
101 for (const u of [owner, stranger, bot.user]) tok[u.username] = createToken(app.db, u.id, "admin", "admin").token;
102 }, 30_000);
103
104 afterAll(async () => {
105 servers?.stop();
106 app?.close();
107 await rm(dataDir, { recursive: true, force: true });
108 });
109
110 describe("the template mark", () => {
111 test("is off by default and listed nowhere", async () => {
112 expect(marked(pub)).toBe(false);
113 expect(await listed()).toEqual([]);
114 });
115
116 test("an agent and a stranger are refused, and nothing changes", async () => {
117 for (const who of ["bot", "stranger"]) {
118 expect((await patch(tok[who]!, "starter", { template: true })).status).toBe(404);
119 expect(marked(pub)).toBe(false);
120 }
121 const refused = await updateRepoSettings(app, bot.user, pub, { template: true });
122 expect(refused.ok).toBe(false);
123 const via = await mcp(tok["bot"]!, { repo: "maker/starter", template: true });
124 expect(via.error).toBeDefined();
125 expect(marked(pub)).toBe(false);
126 });
127
128 test("a junk value is refused at the boundary", async () => {
129 expect((await patch(tok["maker"]!, "starter", { template: "yes" })).status).toBe(422);
130 expect((await mcp(tok["maker"]!, { repo: "maker/starter", template: "yes" })).error).toBeDefined();
131 expect(marked(pub)).toBe(false);
132 });
133
134 test("the admin sets and clears it over the API, and it is listed", async () => {
135 const on = await patch(tok["maker"]!, "starter", { template: true });
136 expect(on.status).toBe(200);
137 expect(((await on.json()) as { template: boolean }).template).toBe(true);
138 expect(marked(pub)).toBe(true);
139 expect(await listed()).toEqual(["starter"]);
140 expect((await patch(tok["maker"]!, "starter", { template: false })).status).toBe(200);
141 expect(marked(pub)).toBe(false);
142 expect(await listed()).toEqual([]);
143 });
144
145 test("the MCP tool sets and clears it with a receipt in the same words", async () => {
146 const on = await mcp(tok["maker"]!, { repo: "maker/starter", template: true });
147 expect(on.value).toMatchObject({ template: true, says: templateSaid(true) });
148 expect(marked(pub)).toBe(true);
149 const off = await mcp(tok["maker"]!, { repo: "maker/starter", template: false });
150 expect(off.value).toMatchObject({ template: false, says: templateSaid(false) });
151 expect(marked(pub)).toBe(false);
152 });
153
154 test("a private template is absent from another person's list, present for its owner", async () => {
155 expect((await patch(tok["maker"]!, "secret", { template: true })).status).toBe(200);
156 expect((await patch(tok["maker"]!, "starter", { template: true })).status).toBe(200);
157 expect(await listed()).toEqual(["starter"]);
158 expect(await listed(tok["stranger"])).toEqual(["starter"]);
159 expect(await listed(tok["maker"])).toEqual(["secret", "starter"]);
160 });
161 });
162
163 describe("the same words over the API and the MCP tool", () => {
164 test("junk is bad_template in both, with one sentence", async () => {
165 const api = await patch(tok["maker"]!, "starter", { template: "yes" });
166 const said = (await api.json()) as { error: { code: string; message: string } | string; code?: string; message?: string };
167 const text = JSON.stringify(said);
168 expect(text).toContain("bad_template");
169 expect(text).toContain("template is true or false");
170 const via = await mcp(tok["maker"]!, { repo: "maker/starter", template: "yes" });
171 expect(via.error).toContain("bad_template");
172 expect(via.error).toContain("template is true or false");
173 });
174 });
175
176 describe("the list's limit and cursor", () => {
177 test("a bad limit or cursor is refused; the second page follows the first", async () => {
178 expect((await patch(tok["maker"]!, "secret", { template: true })).status).toBe(200);
179 expect((await patch(tok["maker"]!, "starter", { template: true })).status).toBe(200);
180 const get = (q: string) => fetch(`${servers.url}/api/v1/templates${q}`, { headers: { authorization: `Bearer ${tok["maker"]}` } });
181 const limit = await get("?limit=0");
182 expect(limit.status).toBe(422);
183 expect(JSON.stringify(await limit.json())).toContain("invalid_limit");
184 const cursor = await get("?cursor=not%20a%20cursor!");
185 expect(cursor.status).toBe(422);
186 expect(JSON.stringify(await cursor.json())).toContain("invalid_cursor");
187 const first = (await (await get("?limit=1")).json()) as { items: { name: string }[]; nextCursor?: string; next_cursor?: string };
188 const next = first.nextCursor ?? first.next_cursor;
189 expect(first.items.length).toBe(1);
190 expect(next).toBeDefined();
191 const second = (await (await get(`?limit=1&cursor=${encodeURIComponent(next!)}`)).json()) as { items: { name: string }[] };
192 expect(second.items.length).toBe(1);
193 expect(second.items[0]!.name).not.toBe(first.items[0]!.name);
194 expect([first.items[0]!.name, second.items[0]!.name].sort()).toEqual(["secret", "starter"]);
195 });
196 });
197
198 describe("the settings page's template form", () => {
199 const signin = async (username: string): Promise<string> => {
200 const res = await fetch(`${servers.url}/signin`, {
201 method: "POST",
202 headers: { origin: servers.url },
203 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
204 redirect: "manual",
205 });
206 return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
207 };
208 const post = (headers: Record<string, string>, fields: Record<string, string>) =>
209 fetch(`${servers.url}/maker/starter/settings`, {
210 method: "POST",
211 headers,
212 body: new URLSearchParams({ card: "template", templateShown: "1", ...fields }),
213 redirect: "manual",
214 });
215 const flashOf = async (res: Response, cookie: string): Promise<string> => {
216 const jar = [cookie, ...res.headers.getSetCookie().map((c) => c.split(";")[0]!)].join("; ");
217 return await (await fetch(new URL(res.headers.get("location")!, servers.url), { headers: { cookie: jar } })).text();
218 };
219
220 test("sets and clears; the sentence is said only when the mark changed", async () => {
221 await patch(tok["maker"]!, "starter", { template: false });
222 const cookie = await signin("maker");
223 const headers = { cookie, origin: servers.url };
224 const on = await post(headers, { template: "on" });
225 expect(on.status).toBe(303);
226 expect(marked(pub)).toBe(true);
227 expect(await flashOf(on, cookie)).toContain(templateSaid(true));
228 const again = await post(headers, { template: "on" });
229 expect(marked(pub)).toBe(true);
230 const page = await flashOf(again, cookie);
231 expect(page).toContain("Settings saved.");
232 expect(page).not.toContain(templateSaid(true));
233 const off = await post(headers, {});
234 expect(marked(pub)).toBe(false);
235 expect(await flashOf(off, cookie)).toContain(templateSaid(false));
236 });
237
238 test("a gates save never changes the mark", async () => {
239 await patch(tok["maker"]!, "starter", { template: true });
240 const cookie = await signin("maker");
241 const res = await fetch(`${servers.url}/maker/starter/settings`, {
242 method: "POST",
243 headers: { cookie, origin: servers.url },
244 body: new URLSearchParams({ card: "gates", defaultBranch: "main" }),
245 redirect: "manual",
246 });
247 expect(res.status).toBe(303);
248 expect(marked(pub)).toBe(true);
249 });
250
251 test("a cross-origin post is refused and changes nothing", async () => {
252 await patch(tok["maker"]!, "starter", { template: false });
253 const cookie = await signin("maker");
254 const res = await post({ cookie, origin: "https://evil.example" }, { template: "on" });
255 expect(res.status).toBeGreaterThanOrEqual(400);
256 expect(marked(pub)).toBe(false);
257 });
258
259 test("an agent and a stranger are refused and change nothing", async () => {
260 for (const who of ["bot", "stranger"]) {
261 const res = await post({ authorization: `Bearer ${tok[who]}`, origin: servers.url }, { template: "on" });
262 expect(res.status).not.toBe(303);
263 expect(marked(pub)).toBe(false);
264 }
265 });
266 });
267
268 describe("the template mark in the terminal", () => {
269 const KEYS: Record<string, string> = { enter: "\r" };
270 async function open(user: User) {
271 const terminal = headlessTerminal(120, 40);
272 const { app: tui, session } = createForgeApp(
273 app,
274 { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
275 { terminal, exitHooks: false },
276 );
277 tui.start();
278 tui.ctx.push(repoScreen(session, tui.ctx, local(session, pub)));
279 tui.ctx.push(templateScreen(session, tui.ctx, pub));
280 await settleApp(tui);
281 return {
282 session,
283 ctx: tui.ctx,
284 text: () => tui.screen.toText(),
285 feed: async (...keys: string[]) => {
286 for (const k of keys) {
287 terminal.feed(KEYS[k] ?? k);
288 await settleApp(tui);
289 }
290 },
291 stop: () => tui.stop?.(),
292 };
293 }
294
295 test("an admin's t marks and clears it, as the page does, and each write is an event", async () => {
296 await patch(tok["maker"]!, "starter", { template: false });
297 const h = await open(owner);
298 expect(h.text()).toContain("Not a template");
299 await h.feed("t");
300 expect(marked(pub)).toBe(true);
301 expect(h.text()).toContain("New forges may start from this repository");
302 expect(await listed()).toContain("starter");
303 await h.feed("t");
304 expect(marked(pub)).toBe(false);
305 const events = listEvents(app.db, { repoId: pub.id }).filter((e) => e.kind === "repo.settings_updated");
306 expect(events.length).toBeGreaterThanOrEqual(2);
307 h.stop();
308 });
309
310 test("it is offered in the palette to an admin and to no one else", async () => {
311 const admin = await open(owner);
312 expect(templateCommands(admin.session, admin.ctx, pub).length).toBe(1);
313 admin.stop();
314 const other = await open(stranger);
315 expect(templateCommands(other.session, other.ctx, pub)).toEqual([]);
316 await other.feed("t");
317 expect(marked(pub)).toBe(false);
318 other.stop();
319 });
320 });
test/route-timing-coverage.test.ts +1
@@ -22,6 +22,7 @@ const UNTIMED: Record<string, string> = {
2222 "/api/v1/conversations": "a person's conversation list, one indexed query; no page to phase",
2323 "/api/v1/admin/machines/:machine/disks": "an owner's per-machine disk summary, one indexed read; no page to phase",
2424 "/api/v1/repos/:owner/:name/issues/:number/estimates": "an issue's base rate from one indexed read of its history; no page to phase",
25 "/api/v1/templates": "the marked repositories, one indexed read; no page to phase",
2526 "/metrics": "Prometheus text exposition, scraped by token; not a page read",
2627 };
2728

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs