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

Registry: updates arrive as pulls (#6009) #17127

Merged opened this

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

Merged

torque/forge:torque/17039-registry-updates-arrive-as-pulls-6009 → main 0 commits fork 1 thread · 1 unresolved

  • Merged. torque/17039-registry-updates-arrive-as-pulls-6009 was merged into main as 6d41254.

Review

Sign in to review this change.
17 files changed +497 −11
docs/features/app-registry.md +22
@@ -18,3 +18,25 @@ registry's newer version against that note (#17038, a slice of #6009).
1818
1919 An item's name is lower case letters, digits and dashes (up to 48); a version is up to 32 letters,
2020 digits, dots, dashes, plus signs and underscores. An app holds at most 200 items.
21
22 ## Updates arrive as pulls (#17039)
23
24 Each item has a `version` in the registry (`meta.version` in `/r/<name>.json`). When an app holds
25 an item at another version, it is *behind*, and one pull brings it up to date: a branch
26 `registry/<item>-<version>` that writes the item's files whole at their targets. Nothing lands on
27 the default branch until a person merges it.
28
29 - **API:** `GET …/app/registry/updates` lists `{ behind: [{ item, held, latest }] }` for a reader;
30 `POST …/app/registry/updates` opens a pull for each (an admin of the repository, admin-scope
31 token) and answers `{ updates: [{ item, to, state, pull? }] }`, where `state` is `opened`,
32 `already` (that branch has a pull), `merged` (the pull was merged, so the note moved to the new
33 version) or `refused` (with `why`).
34 - **MCP:** `app_registry` with `action: "behind"` or `"update"`.
35 - **Terminal:** the Registry items screen shows `version 0 → 1 available`; the admin presses `u`.
36 - **On its own:** the `registry-updates` maintenance duty makes the same offer hourly for every
37 app, as the person who noted the install.
38
39 An offer made twice finds the first pull, and a pull the crew closed is not offered again until the
40 registry's version moves on. The forge does not keep the text an app installed, so it cannot merge
41 the app's own edits into the update: they show in the diff as lines the update would take away.
42 Security fixes do not jump the queue yet.
docs/features/component-registry.md +1 −1
@@ -12,4 +12,4 @@ The source is copied into the app, which owns it. Items: `tokens` (colours and r
1212
1313 From a terminal: `curl <this forge>/r/registry.json`.
1414
15 Not yet: private items, recording which app has which version, update pulls, the gallery, MCP install.
15 Which app holds which version, and the update pulls, are in `app-registry.md`. Not yet: private items, the gallery, MCP install.
src/actions/registry_updates.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * Registry updates arrive as pulls (#17039, a slice of #6009): when an item's version in the
3 * registry is not the one an app holds, the app gets one pull that writes the item's files onto a
4 * branch of its own. One gate for the API, the MCP and the terminal; the maintenance duty's sweep
5 * (`maintain/registry_updates.ts`) offers through `offerBehind`. A reader sees what is behind;
6 * opening the pulls is the repository's admin's, as noting an install is.
7 *
8 * One branch per item and version (`registry/<item>-<version>`), so an offer made twice finds the
9 * first: it is reported, never doubled, and a pull the crew closed is not offered again until the
10 * registry moves on. A merged one moves the app's note to the new version.
11 */
12
13 import type { App } from "../app.ts";
14 import { installedItems, recordInstalled } from "../core/app_registry.ts";
15 import { pullForBranch } from "../core/pulls.ts";
16 import type { Repo } from "../core/repos.ts";
17 import type { User } from "../core/users.ts";
18 import { ok, type Result } from "../kernel/result.ts";
19 import { behindItems, updateBody, updateBranch, updateTitle, type Behind } from "../registry/updates.ts";
20 import { requireReader, requireRepoAdmin } from "./access.ts";
21 import { editFiles } from "./contents.ts";
22
23 export interface BehindRow {
24 readonly item: string;
25 readonly held: string;
26 readonly latest: string;
27 }
28
29 /**
30 * What happened to one item: a pull opened, one already there, the note moved on a merge, or why
31 * not.
32 */
33 export type UpdateOutcome =
34 | { item: string; to: string; state: "opened"; pull: number }
35 | { item: string; to: string; state: "already"; pull: number }
36 | { item: string; to: string; state: "merged" }
37 | { item: string; to: string; state: "refused"; why: string };
38
39 const rowOf = (b: Behind): BehindRow => ({ item: b.item.name, held: b.held, latest: b.item.meta.version });
40
41 /** The installed items that are behind the registry; any reader of the repository. */
42 export function registryBehind(app: App, actor: User | undefined, repo: Repo): Result<BehindRow[], "not_found"> {
43 const gate = requireReader(app, actor, repo);
44 if (!gate.ok) return gate;
45 return ok(behindItems(installedItems(app.db, repo.id)).map(rowOf));
46 }
47
48 /** One pull for one behind item, written as `writer`. */
49 export async function offerBehind(app: App, writer: User, repo: Repo, b: Behind): Promise<UpdateOutcome> {
50 const to = b.item.meta.version;
51 const branch = updateBranch(b.item);
52 const there = pullForBranch(app.db, repo.id, branch);
53 if (there !== undefined && there.mergedAt !== null) {
54 recordInstalled(app.db, repo.id, b.item.name, to, writer.id);
55 return { item: b.item.name, to, state: "merged" };
56 }
57 if (there !== undefined) return { item: b.item.name, to, state: "already", pull: there.number };
58 const done = await editFiles(app, writer, repo, {
59 newBranch: branch,
60 message: updateTitle(b),
61 files: b.item.files.map((f) => ({ path: f.target, content: f.content })),
62 openPull: { title: updateTitle(b), body: updateBody(b) },
63 });
64 if (done.ok && done.value.pull !== undefined) return { item: b.item.name, to, state: "opened", pull: done.value.pull.number };
65 const why = done.ok ? "the pull did not open" : typeof done.error === "string" ? done.error : done.error.kind;
66 return { item: b.item.name, to, state: "refused", why };
67 }
68
69 /** Open an update pull for every item of the app that is behind; the repository's admin only. */
70 export async function offerRegistryUpdates(app: App, actor: User | undefined, repo: Repo): Promise<Result<UpdateOutcome[], "not_found">> {
71 const gate = requireRepoAdmin(app, actor, repo);
72 if (!gate.ok) return gate;
73 const out: UpdateOutcome[] = [];
74 for (const b of behindItems(installedItems(app.db, repo.id))) out.push(await offerBehind(app, gate.value, repo, b));
75 return ok(out);
76 }
src/contract/openapi/routes/getApiV1ReposOwnerNameAppRegistryUpdates.ts added +11
@@ -0,0 +1,11 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: `${REPO}/app/registry/updates`,
6 summary: "List the registry items an app holds behind the registry",
7 detail: "List the installed registry items whose version is behind the registry's (anyone who reads the repository); answers { behind: [...] }",
8 auth: false,
9 role: "anonymous",
10 refuses: [404],
11 };
src/contract/openapi/routes/index.ts +2
@@ -158,6 +158,7 @@ export { route as getApiV1ReposOwnerNameAppNotes } from "./getApiV1ReposOwnerNam
158158 export { route as getApiV1ReposOwnerNameAppProductionOpen } from "./getApiV1ReposOwnerNameAppProductionOpen.ts";
159159 export { route as getApiV1ReposOwnerNameAppPulls } from "./getApiV1ReposOwnerNameAppPulls.ts";
160160 export { route as getApiV1ReposOwnerNameAppRegistry } from "./getApiV1ReposOwnerNameAppRegistry.ts";
161 export { route as getApiV1ReposOwnerNameAppRegistryUpdates } from "./getApiV1ReposOwnerNameAppRegistryUpdates.ts";
161162 export { route as getApiV1ReposOwnerNameBranches } from "./getApiV1ReposOwnerNameBranches.ts";
162163 export { route as getApiV1ReposOwnerNameBuilds } from "./getApiV1ReposOwnerNameBuilds.ts";
163164 export { route as getApiV1ReposOwnerNameBuildsLabelCart } from "./getApiV1ReposOwnerNameBuildsLabelCart.ts";
@@ -393,6 +394,7 @@ export { route as postApiV1ReposOwnerNameAppNotesIdBan } from "./postApiV1ReposO
393394 export { route as postApiV1ReposOwnerNameAppNotesIdHide } from "./postApiV1ReposOwnerNameAppNotesIdHide.ts";
394395 export { route as postApiV1ReposOwnerNameAppNotesIdUnban } from "./postApiV1ReposOwnerNameAppNotesIdUnban.ts";
395396 export { route as postApiV1ReposOwnerNameAppPull } from "./postApiV1ReposOwnerNameAppPull.ts";
397 export { route as postApiV1ReposOwnerNameAppRegistryUpdates } from "./postApiV1ReposOwnerNameAppRegistryUpdates.ts";
396398 export { route as postApiV1ReposOwnerNameAtlas } from "./postApiV1ReposOwnerNameAtlas.ts";
397399 export { route as postApiV1ReposOwnerNameBranches } from "./postApiV1ReposOwnerNameBranches.ts";
398400 export { route as postApiV1ReposOwnerNameBuilds } from "./postApiV1ReposOwnerNameBuilds.ts";
src/contract/openapi/routes/postApiV1ReposOwnerNameAppRegistryUpdates.ts added +11
@@ -0,0 +1,11 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/app/registry/updates`,
6 summary: "Open one pull for each registry item an app holds behind the registry",
7 detail: "Open one pull per installed item that is behind the registry, none twice (admin scope; admin of the repository); answers { updates: [...] }",
8 auth: true,
9 role: "member",
10 refuses: [401, 404],
11 };
src/core/app_registry.ts +5
@@ -38,3 +38,8 @@ export function recordInstalled(db: Database, repoId: string, item: string, vers
3838 export function forgetInstalled(db: Database, repoId: string, item: string): boolean {
3939 return db.query("DELETE FROM app_registry_item WHERE repo_id = ?1 AND item = ?2").run(repoId, item).changes > 0;
4040 }
41
42 /** The repositories that hold at least one item, for the sweep that offers updates. */
43 export function reposWithItems(db: Database): string[] {
44 return db.query<{ repo_id: string }, []>("SELECT DISTINCT repo_id FROM app_registry_item").all().map((r) => r.repo_id);
45 }
src/generated/duties.ts +1
@@ -26,6 +26,7 @@ export const DUTY_MODULES: readonly (readonly [string, () => { duty?: unknown }]
2626 ["pinned_lifetimes.ts", () => require("../maintain/duties/pinned_lifetimes.ts")],
2727 ["preview_dirs.ts", () => require("../maintain/duties/preview_dirs.ts")],
2828 ["red_apps.ts", () => require("../maintain/duties/red_apps.ts")],
29 ["registry_updates.ts", () => require("../maintain/duties/registry_updates.ts")],
2930 ["rule_watcher.ts", () => require("../maintain/duties/rule_watcher.ts")],
3031 ["slow_tests.ts", () => require("../maintain/duties/slow_tests.ts")],
3132 ["stale_branches.ts", () => require("../maintain/duties/stale_branches.ts")],
src/http/api/app_registry.ts +19 −1
@@ -2,10 +2,12 @@
22 * What an app has installed from the component registry (#17038), over the API:
33 * `GET …/app/registry` lists each item and its version, `PUT …/app/registry/:item` with
44 * `{ version }` notes an install and `DELETE …/app/registry/:item` its removal. The rules live in
5 * `actions/app_registry.ts`.
5 * `actions/app_registry.ts`. `GET …/app/registry/updates` lists what is behind the registry and
6 * `POST` opens a pull for each (#17039, `actions/registry_updates.ts`).
67 */
78
89 import { noteInstalled, noteRemoved, registryItems } from "../../actions/app_registry.ts";
10 import { offerRegistryUpdates, registryBehind } from "../../actions/registry_updates.ts";
911 import { loadRepo } from "../api.ts";
1012 import type { Handler } from "../context.ts";
1113 import { apiError, body, json, notFound, requireScope } from "../respond.ts";
@@ -21,6 +23,22 @@ export function appRegistryRoutes(router: Router<Handler>): void {
2123 return got.ok ? view(got.value) : notFound();
2224 });
2325
26 router.add("GET", "/api/v1/repos/:owner/:name/app/registry/updates", (ctx) => {
27 const repo = loadRepo(ctx);
28 if (!repo) return notFound();
29 const got = registryBehind(ctx.app, ctx.auth.user, repo);
30 return got.ok ? json({ behind: got.value }) : notFound();
31 });
32
33 router.add("POST", "/api/v1/repos/:owner/:name/app/registry/updates", async (ctx) => {
34 const denied = requireScope(ctx, "admin");
35 if (denied) return denied;
36 const repo = loadRepo(ctx);
37 if (!repo) return notFound();
38 const done = await offerRegistryUpdates(ctx.app, ctx.auth.user, repo);
39 return done.ok ? json({ updates: done.value }) : notFound();
40 });
41
2442 router.add("PUT", "/api/v1/repos/:owner/:name/app/registry/:item", async (ctx) => {
2543 const denied = requireScope(ctx, "admin");
2644 if (denied) return denied;
src/http/mcp/tools/app_registry.ts +16 −7
@@ -1,31 +1,40 @@
11 import { noteInstalled, noteRemoved, registryItems } from "../../../actions/app_registry.ts";
2 import { offerRegistryUpdates, registryBehind } from "../../../actions/registry_updates.ts";
23 import { scopeAllows } from "../../../core/tokens.ts";
34 import { bad, good, isAnswer, REPO_ARG, repoArg, type Tool } from "../shared.ts";
45
56 export const tool: Tool = {
67 name: "app_registry",
7 doc: "`{ repo, action, item?, version? }`: `list` the registry items an app has installed with their versions, `install` notes an item at a version, `remove` forgets it; noting needs an admin of the repository with an admin-scope token",
8 doc: "`{ repo, action, item?, version? }`: `list` the registry items an app has installed with their versions, `install` notes an item at a version, `remove` forgets it, `behind` lists the items older than the registry's, `update` opens a pull for each; noting needs an admin of the repository with an admin-scope token",
89 description: "What an app has installed from the component registry: list, note an install or a removal. Admin to write.",
910 inputSchema: {
1011 type: "object",
1112 properties: {
1213 repo: REPO_ARG,
13 action: { type: "string", enum: ["list", "install", "remove"] },
14 action: { type: "string", enum: ["list", "install", "remove", "behind", "update"] },
1415 item: { type: "string" },
1516 version: { type: "string" },
1617 },
1718 required: ["repo", "action"],
1819 },
1920 writes: true,
20 readsWhen: (args) => args["action"] === "list",
21 heldNotWhen: (args) => args["action"] === "list",
22 run(ctx, user, args) {
21 readsWhen: (args) => args["action"] === "list" || args["action"] === "behind",
22 heldNotWhen: (args) => args["action"] === "list" || args["action"] === "behind",
23 async run(ctx, user, args) {
2324 const action = args["action"];
24 if (action !== "list" && !scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "noting an install needs an admin-scope token");
25 if (action !== "list" && action !== "behind" && !scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "noting an install needs an admin-scope token");
2526 const repo = repoArg(ctx, user, args);
2627 if (isAnswer(repo)) return repo;
2728 const item = typeof args["item"] === "string" ? args["item"] : "";
2829 const version = typeof args["version"] === "string" ? args["version"] : "";
30 if (action === "behind") {
31 const got = registryBehind(ctx.app, user, repo);
32 return got.ok ? good({ behind: got.value }) : bad("not_found", "no such app or repository (owner/name)");
33 }
34 if (action === "update") {
35 const got = await offerRegistryUpdates(ctx.app, user, repo);
36 return got.ok ? good({ updates: got.value }) : bad("not_found", "no such app or repository (owner/name)");
37 }
2938 const done =
3039 action === "list"
3140 ? registryItems(ctx.app, user, repo)
@@ -34,7 +43,7 @@ export const tool: Tool = {
3443 : action === "remove"
3544 ? noteRemoved(ctx.app, user, repo, item)
3645 : undefined;
37 if (done === undefined) return bad("invalid", "`action` is list, install or remove");
46 if (done === undefined) return bad("invalid", "`action` is list, install, remove, behind or update");
3847 if (done.ok) return good({ items: done.value });
3948 return done.error === "not_found" ? bad("not_found", "no such app or repository (owner/name)") : bad("invalid", done.error.message);
4049 },
src/maintain/duties/registry_updates.ts added +22
@@ -0,0 +1,22 @@
1 /**
2 * Registry updates (#17039): when an item of the component registry changes, each app that holds a
3 * copy at an older version is offered one pull (`sweepRegistryUpdates`). Idempotent: an item and
4 * version has one branch, so a pull already opened, merged or closed is not made again.
5 */
6
7 import { sweepRegistryUpdates } from "../registry_updates.ts";
8 import type { Duty } from "../duty.ts";
9
10 export const duty: Duty = {
11 name: "registry-updates",
12 intervalMs: 3_600_000,
13 budget: { runsPerDay: 30, dollarsPerDay: 1, reason: "hourly is 24 a day; the rest is room for a catch-up, and it spends no money" },
14 async run({ app }) {
15 if (app === undefined) return { findings: [], actions: [] };
16 const swept = await sweepRegistryUpdates(app);
17 const actions = swept
18 .filter((s) => s.outcome.state === "opened" || s.outcome.state === "merged")
19 .map((s) => `${s.repo}: ${s.outcome.item} ${s.outcome.state === "opened" ? `pull #${s.outcome.pull}` : "merged, note moved"}`);
20 return { findings: [], actions };
21 },
22 };
src/maintain/registry_updates.ts added +25
@@ -0,0 +1,25 @@
1 /**
2 * The sweep behind the `registry-updates` duty (#17039): every app's behind items, offered as the
3 * one who installed each. One who can no longer write, or is gone, is told so in the outcome.
4 */
5
6 import { offerBehind, type UpdateOutcome } from "../actions/registry_updates.ts";
7 import type { App } from "../app.ts";
8 import { installedItems, reposWithItems } from "../core/app_registry.ts";
9 import { getRepoById } from "../core/repos.ts";
10 import { getUserById } from "../core/users.ts";
11 import { behindItems } from "../registry/updates.ts";
12
13 export async function sweepRegistryUpdates(app: App): Promise<{ repo: string; outcome: UpdateOutcome }[]> {
14 const out: { repo: string; outcome: UpdateOutcome }[] = [];
15 for (const id of reposWithItems(app.db)) {
16 const repo = getRepoById(app.db, id);
17 if (repo === undefined) continue;
18 for (const b of behindItems(installedItems(app.db, id))) {
19 const writer = getUserById(app.db, b.installedBy);
20 const outcome = writer === undefined ? ({ item: b.item.name, to: b.item.meta.version, state: "refused", why: "installer is gone" } as const) : await offerBehind(app, writer, repo, b);
21 out.push({ repo: `${repo.ownerName}/${repo.name}`, outcome });
22 }
23 }
24 return out;
25 }
src/registry/items.ts +8
@@ -22,6 +22,11 @@ export interface RegistryItem {
2222 title: string;
2323 description: string;
2424 registryDependencies?: string[];
25 /**
26 * shadcn's free-form `meta`: `version` is the forge's, bumped whenever the item's files change
27 * (#17039).
28 */
29 meta: { version: string };
2530 cssVars?: { light: Record<string, string>; dark: Record<string, string> };
2631 files: RegistryFile[];
2732 }
@@ -103,6 +108,7 @@ export const ITEMS: readonly RegistryItem[] = [
103108 type: "registry:style",
104109 title: "Forge design tokens",
105110 description: "The forge's colours and radius as CSS variables, light and dark.",
111 meta: { version: "1" },
106112 cssVars: {
107113 light: { "forge-bg": "#ffffff", "forge-fg": "#14171a", "forge-brand": "#e5531b" },
108114 dark: { "forge-bg": "#101316", "forge-fg": "#eef1f3", "forge-brand": "#ff7a45" },
@@ -115,6 +121,7 @@ export const ITEMS: readonly RegistryItem[] = [
115121 type: "registry:ui",
116122 title: "Button",
117123 description: "A button or link-button, primary or plain, with escaped text.",
124 meta: { version: "1" },
118125 registryDependencies: ["tokens"],
119126 files: [file("ui/button.ts", BUTTON_TS), file("ui/button.css", BUTTON_CSS, "registry:style")],
120127 },
@@ -124,6 +131,7 @@ export const ITEMS: readonly RegistryItem[] = [
124131 type: "registry:block",
125132 title: "Empty state",
126133 description: "Says what the page is and the one thing to do first.",
134 meta: { version: "1" },
127135 registryDependencies: ["tokens", "button"],
128136 files: [file("ui/empty-state.ts", EMPTY_TS), file("ui/empty-state.css", EMPTY_CSS, "registry:style")],
129137 },
src/registry/updates.ts added +58
@@ -0,0 +1,58 @@
1 /**
2 * What an update to a registry item is (#17039, a slice of #6009): which installed items are behind
3 * the registry, the branch and the files that carry the newer source into an app, and the words of
4 * the pull. Plain data in, plain data out; `actions/registry_updates.ts` opens the pulls.
5 *
6 * An update is the item's files written whole at their targets. The forge keeps no copy of the
7 * version an app installed, so it cannot three-way merge the app's own edits: they show in the
8 * pull's diff as lines the update would take away, for the crew to keep or drop.
9 */
10
11 import type { InstalledItem } from "../core/app_registry.ts";
12 import { ITEMS, type RegistryItem } from "./items.ts";
13
14 export interface Behind {
15 readonly item: RegistryItem;
16 /** The version the app holds. */
17 readonly held: string;
18 readonly installedBy: string;
19 }
20
21 /**
22 * The installed items whose registry version is not the one held; an item the registry no longer
23 * has is left alone.
24 */
25 export function behindItems(installed: readonly InstalledItem[], items: readonly RegistryItem[] = ITEMS): Behind[] {
26 const out: Behind[] = [];
27 for (const row of installed) {
28 const item = items.find((i) => i.name === row.item);
29 if (item !== undefined && item.meta.version !== row.version) out.push({ item, held: row.version, installedBy: row.installedBy });
30 }
31 return out;
32 }
33
34 /**
35 * The branch an item's update to a version lives on: one per item and version, so a second offer
36 * finds the first.
37 */
38 export function updateBranch(item: RegistryItem): string {
39 return `registry/${item.name}-${item.meta.version.replace(/[^0-9A-Za-z.-]/g, "-").replace(/\.+$/, "")}`;
40 }
41
42 /** The commit's and the pull's title. */
43 export function updateTitle(b: Behind): string {
44 return `Registry: ${b.item.name} ${b.held} → ${b.item.meta.version}`;
45 }
46
47 export function updateBody(b: Behind): string {
48 const paths = b.item.files.map((f) => `- \`${f.target}\``).join("\n");
49 return [
50 `The registry's \`${b.item.name}\` is at version ${b.item.meta.version}; this app holds ${b.held}.`,
51 "",
52 "This pull writes the item's files whole:",
53 paths,
54 "",
55 "Edits the app made to those files show in the diff as lines the update takes away: keep them by editing the pull, or drop them.",
56 "Merging it moves the app's note of the item to the new version.",
57 ].join("\n");
58 }
src/tui/screens/appregistry.ts +19 −2
@@ -2,9 +2,11 @@
22 * What an app has installed from the component registry in the terminal (#17038): each item and the
33 * version the app holds, read through `registryItems`; `i` notes an install and `x` forgets one,
44 * through `noteInstalled` and `noteRemoved`, the same gate and words as the API and the MCP. A
5 * `u` opens a pull for each item behind the registry (`offerRegistryUpdates`, #17039). A
56 * write from another door reaches an open screen by the `app.registry_*` events.
67 */
78
9 import { offerRegistryUpdates, registryBehind, type UpdateOutcome } from "../../actions/registry_updates.ts";
810 import { noteInstalled, noteRemoved, registryItems } from "../../actions/app_registry.ts";
911 import type { InstalledItem } from "../../core/app_registry.ts";
1012 import { getAppByRepo } from "../../core/apps.ts";
@@ -36,11 +38,14 @@ export function appRegistryScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
3638 const state = new ListState();
3739 let rows: InstalledItem[] = [];
3840 let readable = false;
41 let latest = new Map<string, string>();
3942 let note = "";
4043 const reload = (): void => {
4144 const got = registryItems(f.app, f.user, repo);
4245 readable = got.ok;
4346 rows = got.ok ? got.value : [];
47 const behind = registryBehind(f.app, f.user, repo);
48 latest = new Map((behind.ok ? behind.value : []).map((b) => [b.item, b.latest]));
4449 state.clamp(rows.length);
4550 ctx.invalidate();
4651 };
@@ -84,11 +89,19 @@ export function appRegistryScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
8489 });
8590 },
8691 });
92 const wording = (o: UpdateOutcome): string =>
93 o.state === "opened" ? `${o.item}: pull #${o.pull} opened` : o.state === "already" ? `${o.item}: pull #${o.pull} is already open` : o.state === "merged" ? `${o.item}: merged, now at ${o.to}` : `${o.item}: ${o.why}`;
94 const update = (): void => {
95 runAsync(ctx, async () => {
96 const done = await offerRegistryUpdates(f.app, f.user, repo);
97 say(!done.ok ? refused : done.value.length === 0 ? "Everything is at the registry's version." : done.value.map(wording).join(" · "));
98 });
99 };
87100 const screen: Screen = {
88101 title: "Registry items",
89102 get keys() {
90103 return admin
91 ? [binding(["i"], "note an install"), binding(["x"], "forget the item"), binding(["j", "k"], "move cursor")]
104 ? [binding(["i"], "note an install"), binding(["x"], "forget the item"), binding(["u"], "open update pulls"), binding(["j", "k"], "move cursor")]
92105 : [binding(["j", "k"], "move cursor")];
93106 },
94107 async load(signal) {
@@ -100,7 +113,7 @@ export function appRegistryScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
100113 const said = wrap(text, Math.max(1, area.w)).slice(0, 3);
101114 const [head, list] = split(area, "v", [len(said.length), fill(1)]);
102115 said.forEach((line, i) => s.text(head!.x, head!.y + i, line, style(c.mutedFg, c.bg), head!.x + head!.w));
103 const lines: ListRow[] = rows.map((r) => ({ title: r.item, meta: `version ${r.version} · ${r.installedAt.slice(0, 10)}` }));
116 const lines: ListRow[] = rows.map((r) => ({ title: r.item, meta: `version ${r.version}${latest.has(r.item) ? ` → ${latest.get(r.item)} available` : ""} · ${r.installedAt.slice(0, 10)}` }));
104117 drawList(s, list!, c, state, lines);
105118 },
106119 key(e) {
@@ -110,6 +123,10 @@ export function appRegistryScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
110123 ctx.push(install());
111124 return true;
112125 }
126 if (e.key === "u") {
127 update();
128 return true;
129 }
113130 const row = rows[state.index];
114131 if (e.key === "x" && row !== undefined) {
115132 ctx.push(forget(row.item));
test/registry-updates.test.ts added +200
@@ -0,0 +1,200 @@
1 /**
2 * Registry updates arrive as pulls (#17039): which items are behind, the pull one offer opens, the
3 * second offer that finds it, the merge that moves the note, the gate, the sweep's installer, and
4 * the API, MCP and terminal doors.
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 { newApp } from "../src/actions/apps.ts";
11 import { fileAt } from "../src/actions/contents.ts";
12 import { offerRegistryUpdates, registryBehind } from "../src/actions/registry_updates.ts";
13 import { sweepRegistryUpdates } from "../src/maintain/registry_updates.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { installedItems, recordInstalled, type InstalledItem } from "../src/core/app_registry.ts";
16 import { pullForBranch } from "../src/core/pulls.ts";
17 import type { Repo } from "../src/core/repos.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { ITEMS, type RegistryItem } from "../src/registry/items.ts";
22 import { behindItems, updateBranch, updateTitle } from "../src/registry/updates.ts";
23 import { createForgeApp } from "../src/tui/forge.ts";
24 import { appRegistryScreen } from "../src/tui/screens/appregistry.ts";
25 import { headlessTerminal } from "../src/tui/term/terminal.ts";
26 import { seedAdmin } from "./helpers/admin.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28 import { pollUntil } from "./helpers/poll.ts";
29 import { settleApp } from "./helpers/tui.ts";
30
31 quietLogs();
32
33 const held = (item: string, version: string): InstalledItem => ({ item, version, installedBy: "u", installedAt: "2026-12-01T00:00:00.000Z" });
34
35 describe("what is behind", () => {
36 test("an item at another version than the registry's is behind; the same one, and one the registry lacks, are not", () => {
37 const button = ITEMS.find((i) => i.name === "button")!;
38 const v = button.meta.version;
39 const got = behindItems([held("button", "0"), held("tokens", ITEMS.find((i) => i.name === "tokens")!.meta.version), held("gone-item", "1")]);
40 expect(got.map((b) => [b.item.name, b.held])).toEqual([["button", "0"]]);
41 expect(updateTitle(got[0]!)).toBe(`Registry: button 0 → ${v}`);
42 });
43
44 test("the branch is one per item and version, and a version's odd characters cannot make a bad ref", () => {
45 const item: RegistryItem = { ...ITEMS[0]!, name: "tokens", meta: { version: "2_0+rc..." } };
46 expect(updateBranch(item)).toBe("registry/tokens-2-0-rc");
47 expect(updateBranch({ ...item, meta: { version: "3" } })).toBe("registry/tokens-3");
48 });
49 });
50
51 describe("the pulls", () => {
52 let dir = "";
53 let app: App;
54 let servers: Servers;
55 let alice: User;
56 let bob: User;
57 let repo: Repo;
58 let admin = "";
59 let ro = "";
60
61 beforeAll(async () => {
62 dir = await mkdtemp(join(tmpdir(), "forge-registry-updates-"));
63 app = createApp({ dataDir: dir, port: 0 });
64 servers = await serve(app);
65 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" });
66 if (!a.ok) throw new Error(a.error);
67 alice = a.value;
68 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
69 if (!b.ok) throw new Error(b.error);
70 bob = b.value;
71 const made = await newApp(app, alice, { name: "ledger" });
72 if (!made.ok) throw new Error(made.error);
73 repo = made.value.repo;
74 admin = createToken(app.db, alice.id, "t", "admin").token;
75 ro = createToken(app.db, alice.id, "t", "ro").token;
76 });
77 afterAll(async () => {
78 servers.stop();
79 app.close();
80 await rm(dir, { recursive: true, force: true });
81 });
82
83 const button = ITEMS.find((i) => i.name === "button")!;
84 const tokens = ITEMS.find((i) => i.name === "tokens")!;
85
86 test("a reader sees what is behind; a stranger is told not_found", () => {
87 recordInstalled(app.db, repo.id, "button", "0", alice.id);
88 recordInstalled(app.db, repo.id, "tokens", tokens.meta.version, alice.id);
89 const got = registryBehind(app, alice, repo);
90 expect(got.ok && got.value).toEqual([{ item: "button", held: "0", latest: button.meta.version }]);
91 const stranger = registryBehind(app, bob, repo);
92 expect(stranger.ok ? "ok" : stranger.error).toBe("not_found");
93 });
94
95 test("an admin's offer opens one pull that writes the item's files; a non-admin's opens none", async () => {
96 const refused = await offerRegistryUpdates(app, bob, repo);
97 expect(refused.ok).toBe(false);
98 expect(pullForBranch(app.db, repo.id, updateBranch(button))).toBeUndefined();
99
100 const done = await offerRegistryUpdates(app, alice, repo);
101 expect(done.ok).toBe(true);
102 const outcome = done.ok ? done.value : [];
103 expect(outcome).toHaveLength(1);
104 expect(outcome[0]).toMatchObject({ item: "button", state: "opened" });
105 const pull = pullForBranch(app.db, repo.id, updateBranch(button))!;
106 expect(pull.title).toBe(updateTitle({ item: button, held: "0", installedBy: alice.id }));
107 expect(pull.body).toContain("ui/button.ts");
108 for (const f of button.files) expect((await fileAt(app, repo, updateBranch(button), f.target))?.blob).toBeString();
109 // The default branch is untouched: the update waits for a person.
110 expect((await fileAt(app, repo, repo.defaultBranch, "ui/button.ts"))?.blob).toBeNull();
111 });
112
113 test("offering again finds the pull; a merge of it moves the note and the item is no longer behind", async () => {
114 const again = await offerRegistryUpdates(app, alice, repo);
115 const pull = pullForBranch(app.db, repo.id, updateBranch(button))!;
116 expect(again.ok && again.value).toEqual([{ item: "button", to: button.meta.version, state: "already", pull: pull.number }]);
117
118 app.db.query("UPDATE pull SET merged_at = ?1 WHERE issue_id = ?2").run(new Date().toISOString(), pull.id);
119 const merged = await offerRegistryUpdates(app, alice, repo);
120 expect(merged.ok && merged.value).toEqual([{ item: "button", to: button.meta.version, state: "merged" }]);
121 expect(installedItems(app.db, repo.id).find((i) => i.item === "button")?.version).toBe(button.meta.version);
122 const left = await offerRegistryUpdates(app, alice, repo);
123 expect(left.ok && left.value).toEqual([]);
124 });
125
126 test("the sweep offers every app's behind item as the one who installed it, and tell one whose installer is gone", async () => {
127 const other = await newApp(app, alice, { name: "notes" });
128 if (!other.ok) throw new Error(other.error);
129 recordInstalled(app.db, other.value.repo.id, "tokens", "0", alice.id);
130 const swept = await sweepRegistryUpdates(app);
131 expect(swept).toHaveLength(1);
132 expect(swept[0]).toMatchObject({ repo: "alice/notes", outcome: { item: "tokens", state: "opened" } });
133 const pull = pullForBranch(app.db, other.value.repo.id, updateBranch(tokens))!;
134 expect(pull.authorId).toBe(alice.id);
135 expect(await sweepRegistryUpdates(app)).toMatchObject([{ outcome: { state: "already" } }]);
136 recordInstalled(app.db, other.value.repo.id, "empty-state", "0", "nobody");
137 expect((await sweepRegistryUpdates(app)).map((s) => s.outcome.state).sort()).toEqual(["already", "refused"]);
138 app.db.query("DELETE FROM app_registry_item WHERE repo_id = ?1").run(other.value.repo.id);
139 });
140
141 const api = (token: string, method: string): Promise<Response> =>
142 fetch(`${servers.url}/api/v1/repos/alice/ledger/app/registry/updates`, { method, headers: { authorization: `Bearer ${token}` } });
143
144 test("the API lists what is behind and opens the pulls only for an admin-scope token", async () => {
145 app.db.query("DELETE FROM app_registry_item WHERE repo_id = ?1").run(repo.id);
146 recordInstalled(app.db, repo.id, "empty-state", "0", alice.id);
147 const list = await api(ro, "GET");
148 expect(list.status).toBe(200);
149 expect(((await list.json()) as any).behind).toEqual([{ item: "empty-state", held: "0", latest: "1" }]);
150 expect((await api(ro, "POST")).status).toBe(403);
151 expect(pullForBranch(app.db, repo.id, updateBranch(ITEMS.find((i) => i.name === "empty-state")!))).toBeUndefined();
152 const post = await api(admin, "POST");
153 expect(post.status).toBe(200);
154 expect(((await post.json()) as any).updates[0]).toMatchObject({ item: "empty-state", state: "opened" });
155 });
156
157 const rpc = async (token: string, args: Record<string, unknown>): Promise<{ error: boolean; body: any }> => {
158 const res = await fetch(`${servers.url}/mcp`, {
159 method: "POST",
160 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
161 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "app_registry", arguments: { repo: "alice/ledger", ...args } } }),
162 });
163 const out: any = await res.json();
164 const text = String(out.result.content[0].text);
165 let body: unknown = text;
166 try { body = JSON.parse(text); } catch { /* words */ }
167 return { error: out.result.isError === true, body };
168 };
169
170 test("the MCP tool's behind is a read and update needs an admin-scope token", async () => {
171 app.db.query("DELETE FROM app_registry_item WHERE repo_id = ?1").run(repo.id);
172 recordInstalled(app.db, repo.id, "tokens", "0", alice.id);
173 const read = await rpc(ro, { action: "behind" });
174 expect(read.error).toBe(false);
175 expect(read.body.behind.map((b: { item: string }) => b.item)).toEqual(["tokens"]);
176 expect((await rpc(ro, { action: "update" })).error).toBe(true);
177 const done = await rpc(admin, { action: "update" });
178 expect(done.error).toBe(false);
179 expect(done.body.updates[0]).toMatchObject({ item: "tokens", state: "opened" });
180 });
181
182 test("the terminal shows the newer version and u opens the pulls", async () => {
183 recordInstalled(app.db, repo.id, "button", "0", alice.id);
184 const terminal = headlessTerminal(140, 30);
185 const { app: tui, session } = createForgeApp(
186 app,
187 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice },
188 { terminal, exitHooks: false },
189 );
190 tui.start();
191 tui.ctx.push(appRegistryScreen(session, tui.ctx, repo));
192 await settleApp(tui);
193 expect(tui.screen.toText()).toContain(`version 0 → ${button.meta.version} available`);

Minor: this test only passes because an earlier test marked the button pull as merged. Give it its own setup so it does not depend on test order.

194 // The button's pull was merged above, so its branch is found and the note moves.
195 terminal.feed("u");
196 await pollUntil(() => tui.screen.toText().includes("merged, now at"), "the screen says the update", 5000);
197 tui.stop?.();
198 expect(installedItems(app.db, repo.id).find((i) => i.item === "button")?.version).toBe(button.meta.version);
199 });
200 });
test/route-timing-coverage.test.ts +1
@@ -28,6 +28,7 @@ const UNTIMED: Record<string, string> = {
2828 "/api/v1/repos/:owner/:name/drop": "an app's drop listing, one indexed read and a directory scan; no page to phase",
2929 "/api/v1/repos/:owner/:name/crew-devices": "a repository admin's device list, one indexed read; no page to phase",
3030 "/api/v1/repos/:owner/:name/app/registry": "an app's installed registry items, one indexed read; no page to phase",
31 "/api/v1/repos/:owner/:name/app/registry/updates": "an app's items behind the registry, one indexed read and a catalogue compare; no page to phase",
3132 "/api/v1/admin/plans": "an admin's plans with the measured median, two indexed reads; no page to phase",
3233 "/metrics": "Prometheus text exposition, scraped by token; not a page read",
3334 };

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs