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

A deployed forge runs its own forge repository, which follows the forge it was deployed from #16371

Merged opened this

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

Merged

sold/own-forge-repo → main 0 commits

  • Merged. sold/own-forge-repo was merged into main as 2efce93.

Review

Sign in to review this change.
30 files changed +922 −89
docs/features/pinned-forge.md +14 −2
@@ -4,7 +4,7 @@ row: A pinned forge
44 ---
55 # A pinned forge (#8697)
66
7 A pinned forge is a forge the owner put on their own cloud. It has **no crew** and **no automatic release**. Its version and config change only through one explicit `Update`, recorded with who and when; `Rollback` is one action to the previous version. It is served on its own name over HTTPS, and its first admin is whoever holds the one-time claim link the deploy shows (#16217).
7 A pinned forge is a forge the owner put on their own cloud. The forge that deployed it gives it **no crew** and **no automatic release**: on its machine it runs and updates its own code (see "Its own code"). Its recorded version and config change only through one explicit `Update`, recorded with who and when; `Rollback` is one action to the previous version. It is served on its own name over HTTPS, and its first admin is whoever holds the one-time claim link the deploy shows (#16217).
88
99 ## Doors (forge admin, admin-scope token)
1010
@@ -14,7 +14,19 @@ A pinned forge is a forge the owner put on their own cloud. It has **no crew** a
1414 - Web list: `/pinned` (forge admin; 404 otherwise) is server-rendered, with actions; one block of plain rows per forge: name, app, version, address (a link), health (the state), when the last check ran (the newest `pinned.check` event; `never checked` before the first), and the last change with who and when, from the same `pinnedForges` read as the API (`src/web/pages/pinned.ts`). The intro links `/deploy-to`; an empty list says so. A person can update, roll back and check a forge from `/pinned`, as the terminal's `u`, `r` and `c` do: each row has four buttons (Update, Roll back, Check, New claim link), and each goes through the confirm page before it runs (Update also asks for the version). The row also shows the DNS record and when the claim link runs out. They post to `POST /pinned/:name/:act` (`act` is `update`, `rollback`, `check` or `claim`; admin only, same-origin, 404 for non-admins and unknown acts); the result, or the sentence that refuses it, is shown as a flash on `/pinned` (`src/http/pinned_routes.ts`).
1515 - MCP: `pinned_forge` with `verb` `list`, `deploy`, `claim`, `update`, `rollback` (and `check`) — the same words and the same checks (`src/actions/pinned.ts`).
1616
17 A deploy names a cloud account (Settings → Cloud accounts, **writes allowed**), the app (`owner/name`), a git `source` (https), a `version` (a 40-character commit id or a tag like `v1.2.3` — never a branch, so nothing moves under it) and a `host`: the DNS name the forge is served on.
17 A deploy names a cloud account (Settings → Cloud accounts, **writes allowed**), the app (`owner/name`), a git `source` (https), a `version` (a 40-character commit id or a tag like `v1.2.3` — never a branch, so nothing moves under it) and a `host`: the DNS name the forge is served on. Left empty, `source` is this forge's own repository at its public address (`<FORGE_URL>/<forgeRepo>.git`, which must be public) and `version` the commit this forge runs (`FORGE_COMMIT`); either refusal says which is missing (`ownCode` in `src/actions/pinned.ts`).
18
19 ## Its own code (#16361)
20
21 The machine boots the source at the version from `/opt/forge`, and from then on runs its own repository. Its boot sets `FORGE_REPO=forge/forge`, `FORGE_UPSTREAM` (the source), `FORGE_COMMIT` (the version, when it is a commit), `FORGE_RELEASE_KEEPER=swap` and `FORGE_SELF_SWAP=1`; none of them is a setting a deploy may name. At first boot, before any claim, the checkout's history and tags become `forge/forge` (a reserved organisation with nobody in it yet), its main at the commit the machine runs. That repository is the forge's source, its crew is seated on it, and it follows `FORGE_UPSTREAM`'s `main` with take-updates (`src/spawn/own_forge.ts`). A restart finds it and changes nothing.
22
23 At the claim the repository moves to the new admin's own account (`<admin>/forge`, the old path a redirect), and the forge's source names it there. The release keeper swaps in what lands on its main, so a merge there, or an update taken from the forge it was deployed from, updates the forge on its machine. A forge deployed from that one follows it in turn. The boot also installs Claude Code (`npm install -g @anthropic-ai/claude-code`) for the owner's crew; when that fails the forge starts without it.
24
25 An update that conflicts with a change made here opens one issue naming the files, and a builder takes it only when **Crew resolves upstream conflicts** is on. That is a setting of every repository that follows an address (`crew_resolves` on `repo_upstream`), off by default whatever the repository's autonomy, on its Follow upstream card with the words: "When an update from <upstream> and a change made here touch the same lines, the crew merges them for you. Off: the update waits, and an issue names the files for you to decide in the code." On the forks screen an admin presses `r` to turn it on or off (`setCrewResolving` in `src/actions/upstream_follow.ts`).
26
27 On `/deploy-to`, Source and Version are optional; left empty, they are this forge's own code.
28
29 Not yet: a launcher on the machine that brings back the last good tree when a swap fails at boot, a release that waits for a green check, and a private source (the machine reads it without a credential).
1830
1931 ## The name and HTTPS (#16217)
2032
scripts/pinned-canary.ts +7 −4
@@ -1,5 +1,5 @@
11 /**
2 * `bun scripts/pinned-canary.ts <forge url> --account <name> --host <dns name> --app <owner/name> --source <https git url>
2 * `bun scripts/pinned-canary.ts <forge url> --account <name> --host <dns name> --app <owner/name> [--source <https git url>]
33 * --version <40-hex or vX.Y.Z> --next <second version> [--name <pinned name>] [--budget <seconds>] [--keep]`
44 *
55 * The canary for pinned forges (#8746): one real Deploy, Update and Rollback
@@ -51,7 +51,7 @@ export async function canary(
5151 const steps: Step[] = [];
5252 const t0 = now();
5353 const plan: Array<[string, string, unknown, string]> = [
54 ["deploy", "/api/v1/admin/pinned", { name: o.name, host: o.host, target: "digitalocean", account: o.account, app: o.app, source: o.source, version: o.version }, o.version],
54 ["deploy", "/api/v1/admin/pinned", { name: o.name, host: o.host, target: "digitalocean", account: o.account, app: o.app, version: o.version, ...(o.source ? { source: o.source } : {}) }, o.version],
5555 ["update", `/api/v1/admin/pinned/${o.name}/update`, { version: o.next }, o.next],
5656 ["rollback", `/api/v1/admin/pinned/${o.name}/rollback`, {}, o.version],
5757 ];
@@ -82,6 +82,8 @@ export function invalid(o: { version: string; next: string; source: string }): s
8282 if (!VERSION.test(o.version)) return "--version is a 40-character commit id or a tag like v1.2.3";
8383 if (!VERSION.test(o.next)) return "--next is a 40-character commit id or a tag like v1.2.3";
8484 if (o.version === o.next) return "--next must differ from --version, or the Update changes nothing";
85 // No --source: the forge deploys its own forge repository at the commit it runs (#16361).
86 if (o.source === "" || o.source === undefined) return undefined;
8587 try {
8688 if (new URL(o.source).protocol !== "https:") return "--source must be https";
8789 } catch {
@@ -142,9 +144,10 @@ if (import.meta.main) {
142144 };
143145 const base = args[0];
144146 const token = process.env.FORGE_TOKEN;
145 const [account, host, app, source, version, next] = ["--account", "--host", "--app", "--source", "--version", "--next"].map(flag);
147 const [account, host, app, sourceGiven, version, next] = ["--account", "--host", "--app", "--source", "--version", "--next"].map(flag);
148 const source = sourceGiven ?? "";
146149 const budget = Number(flag("--budget") ?? 600);
147 if (!base?.startsWith("http") || !token || !account || !host || !app || !source || !version || !next || !(budget > 0)) {
150 if (!base?.startsWith("http") || !token || !account || !host || !app || !version || !next || !(budget > 0)) {
148151 console.error("usage: FORGE_TOKEN=<admin token> bun scripts/pinned-canary.ts <forge url> --account <n> --host <dns name> --app <owner/name> --source <https url> --version <v> --next <v2> [--name <n>] [--budget <s>] [--keep]");
149152 process.exit(2);
150153 }
src/actions/first_admin.ts +4
@@ -30,6 +30,7 @@ import { bucketOf } from "../http/peer.ts";
3030 import { err, ok, type Result } from "../kernel/result.ts";
3131 import { limitValue } from "../settings/limits.ts";
3232 import { handOver, spawnedOrg } from "../spawn/claim.ts";
33 import { moveOwnForge } from "../spawn/own_forge.ts";
3334 import { EMAIL_TAKEN_MESSAGE, EMAIL_WANTED, INVALID_USERNAME_MESSAGE, NAME_RESERVED, USERNAME_TAKEN } from "./signup_words.ts";
3435
3536 const USERNAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,38}$/;
@@ -166,6 +167,9 @@ export async function redeemFirstAdmin<T>(
166167 }
167168 const spawned = await spawnedOrg(app);
168169 if (spawned !== undefined) handOver(app.db, spawned, made.value.id);
170 // A deployed forge's own code becomes the new admin's, under their name (#16361).
171 const own = await moveOwnForge(app, made.value);
172 if (!own.ok) app.log.warn("the forge's own repository stayed where it was", { why: own.error });
169173 app.bus.append({
170174 kind: "user.created",
171175 actorId: made.value.id,
src/actions/pinned.ts +35 −5
@@ -43,6 +43,9 @@ import {
4343 dnsOf, dropDns, dropPinned, keepDns, markClaimed, markReached, recordChange, setClaim, setHost, setRemote, urlOf, validHost, validSource, validVersion, unconfirmedRefusal, type Change, type Pinned,
4444 } from "../core/pinned.ts";
4545 import { resolveSecrets } from "../core/secret_store.ts";
46 import { getRepo } from "../core/repos.ts";
47 import { running } from "../kernel/version.ts";
48 import { forgeSource } from "../settings/forge_source.ts";
4649 import { DOMAIN_WORDS, getBaseDomain, parseBaseDomain, setBaseDomain } from "../settings/pinned_domain.ts";
4750 import { PAID_PLACEMENT_WORDS, getPaidPlacement, paidPlacementWord, parsePaidPlacement, setPaidPlacement } from "../settings/paid_placement.ts";
4851 import type { User } from "../core/users.ts";
@@ -259,7 +262,7 @@ async function unwriteDns(app: App, who: Who, name: string): Promise<"none" | "r
259262 const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: runOf(who, "dns") })[secret];
260263 if (token === undefined) continue;
261264 const f = gatedFetch(app.db, { provider: a.provider, account: a.name }, "pinned:dns", net.fetch);
262 if ((await deleteARecord(f, token, kept.zone, kept.record)) === "refused") continue;
265 if ((await deleteARecord(f, token, kept.zone, kept.record, kept.host)) === "refused") continue;
263266 dropDns(app.db, p.id);
264267 return "removed";
265268 }
@@ -325,8 +328,33 @@ async function readAddress(app: App, who: Who, name: string): Promise<Result<str
325328 return ok(seen.value.address);
326329 }
327330
331 /**
332 * What a deploy runs when it names no source or version (#16361): this forge's own code, its
333 * repository's public address here and the commit this process runs, so the new forge follows
334 * this one. Public read only: a private repository needs a credential the machine has not got.
335 */
336 export function ownCode(app: App, asked: { source?: string; version?: string }): Result<{ source: string; version: string }, string> {
337 let source = (asked.source ?? "").trim();
338 let version = (asked.version ?? "").trim();
339 if (source === "") {
340 const base = (app.config.url ?? "").replace(/\/+$/, "");
341 const named = forgeSource(app.db, app.config.forgeRepo);
342 const [owner = "", name = ""] = (named ?? "").split("/");
343 const repo = named === undefined ? undefined : getRepo(app.db, owner, name);
344 if (base === "" || repo === undefined) return err("Name a source: this forge has no public address (FORGE_URL) or no repository of its own code.");
345 if (repo.visibility !== "public") return err(`Name a source: ${repo.ownerName}/${repo.name} is private, and a deployed forge reads its code without a credential.`);
346 source = `${base}/${repo.ownerName}/${repo.name}.git`;
347 }
348 if (version === "") {
349 const commit = running().commit;
350 if (commit === null || !/^[0-9a-f]{40}$/.test(commit)) return err("Name a version: this forge does not know the full commit it runs (FORGE_COMMIT).");
351 version = commit;
352 }
353 return ok({ source, version });
354 }
355
328356 export type DeployInput = {
329 name: string; host: string; target: string; account: string; app: string; source: string; version: string; place?: string | undefined; config?: unknown;
357 name: string; host: string; target: string; account: string; app: string; source?: string; version?: string; place?: string | undefined; config?: unknown;
330358 /** The plan whose default place is chosen when none is asked for; small when absent. */
331359 plan?: PlanName | undefined;
332360 };
@@ -345,8 +373,10 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
345373 const host = hostFor(app, input.name, input.host);
346374 if (!host.ok) return host;
347375 if (!APP.test(input.app)) return err("Name the app as owner/name.");
348 if (!validSource(input.source)) return err("The source is an https git address.");
349 if (!validVersion(input.version)) return err("A version is a full 40-character commit id or a tag like v1.2.3.");
376 const code = ownCode(app, input);
377 if (!code.ok) return code;
378 if (!validSource(code.value.source)) return err("The source is an https git address.");
379 if (!validVersion(code.value.version)) return err("A version is a full 40-character commit id or a tag like v1.2.3.");
350380 const config = checkConfig(input.config);
351381 if (!config.ok) return config;
352382 // A first deploy that failed before any droplet exists may be tried again: its row goes,
@@ -370,7 +400,7 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
370400 if (old) dropPinned(app.db, old.name);
371401 const claim = newClaim();
372402 const { place: _asked, plan: _plan, ...rest } = input;
373 const p = insertPinned(app.db, { ...rest, target: t.id, config: config.value, host: host.value, claimHash: claim.hash, claimExpires: claim.expires, datacenter: at.value.datacenter, size: at.value.size }, who.by);
403 const p = insertPinned(app.db, { ...rest, ...code.value, target: t.id, config: config.value, host: host.value, claimHash: claim.hash, claimExpires: claim.expires, datacenter: at.value.datacenter, size: at.value.size }, who.by);
374404 app.bus.append({ kind: "pinned.deployed", actorId: who.id, payload: { name: p.name, target: p.target, version: p.version, ...orderOf(who) } });
375405 if (old?.volume) setRemote(app.db, p.name, { volume: old.volume });
376406 const made = await create(
src/actions/upstream_follow.ts +41 −6
@@ -10,7 +10,7 @@
1010 * that is not at the fetched head was planted by someone: the check fails
1111 * and leaves it alone. A conflicting merge is noted as "conflict" and
1212 * starts one converge run for the crew (`convergeConflict`), once per
13 * fetched head, and none when the repository's autonomy is off.
13 * fetched head, and none unless the owner said the crew resolves conflicts.
1414 *
1515 * The fetch is the mirror's: the host is vetted and the vetted address
1616 * pinned (`vettedEnv`), https and http only. A connected origin's token goes
@@ -38,12 +38,14 @@ import { pullForBranch, retargetPull } from "../core/pulls.ts";
3838 import { canAdmin, canWrite, forkParentFor, getRepoById, type Repo } from "../core/repos.ts";
3939 import { storageStale } from "../core/storage.ts";
4040 import {
41 crewResolves,
4142 getFollow,
4243 followAad,
4344 listFollowing,
4445 inheritsPending,
4546 noteCheck,
4647 putFollow,
48 setCrewResolves,
4749 severFollow,
4850 upstreamUrl,
4951 type FollowCheck,
@@ -251,7 +253,7 @@ const conflictTitle = (tip: string): string => `${UPSTREAM_TITLE}conflict at ${t
251253 /**
252254 * A conflicting head goes to the crew once: one issue titled by the head,
253255 * whether open or closed, and one converge run for a builder. A second
254 * check of the same head finds the issue and starts nothing; autonomy off
256 * check of the same head finds the issue and starts nothing; the setting off
255257 * leaves the conflict noted on the row alone.
256258 */
257259 export interface ConflictHandled {
@@ -271,13 +273,15 @@ export function convergeConflict(
271273 tip: string,
272274 files: readonly string[],
273275 source?: { readonly id: string; readonly host: string; readonly account: string; readonly via: readonly string[] },
274 /** A person asked: the crew is started whatever the repository's autonomy. */
276 /** A person asked: the crew is started whatever the repository's setting. */
275277 asked = false,
276278 ): ConflictHandled | undefined {
277279 // The setting as it is now, not as the caller read it before the fetch.
278280 const repo = getRepoById(app.db, checked.id);
279281 if (repo === undefined) return undefined;
280 const crewed = repo.autonomy !== "off" || asked;
282 // The owner's word on the follow (#16361), off by default: autonomy alone never hands a
283 // conflict to the crew.
284 const crewed = crewResolves(app.db, repo.id) || asked;
281285 // A source with a conflict still open waits for the crew: a moving head is not asked again.
282286 if (source !== undefined && openConflictOf(app.db, source.id)) return undefined;
283287 const title = conflictTitle(tip);
@@ -823,7 +827,14 @@ export function setFollowUpstream(
823827 app: App,
824828 actor: User | undefined,
825829 repo: Repo,
826 input: { readonly url: string; readonly branch: string; readonly enabled: boolean; readonly mode?: FollowTaking },
830 input: {
831 readonly url: string;
832 readonly branch: string;
833 readonly enabled: boolean;
834 readonly mode?: FollowTaking;
835 /** Whether the crew resolves conflicting updates; absent keeps the row's. */
836 readonly crewResolves?: boolean;
837 },
827838 ): Result<UpstreamFollow, FollowError> {
828839 if (actor === undefined || !canAdmin(app.db, repo, actor)) return err("not_found");
829840 const was = getFollow(app.db, repo.id);
@@ -844,11 +855,12 @@ export function setFollowUpstream(
844855 originId: was?.url === url ? was.originId : "",
845856 ...(input.mode === undefined ? {} : { mode: input.mode }),
846857 });
858 if (input.crewResolves !== undefined) setCrewResolves(app.db, repo.id, input.crewResolves);
847859 app.bus.append({
848860 kind: "repo.upstream_follow",
849861 repoId: repo.id,
850862 actorId: actor.id,
851 payload: { enabled: saved.enabled, branch: saved.branch },
863 payload: { enabled: saved.enabled, branch: saved.branch, crewResolves: crewResolves(app.db, repo.id) },
852864 });
853865 // The readers' event: on or off, and nothing that says where.
854866 app.bus.append({
@@ -857,6 +869,29 @@ export function setFollowUpstream(
857869 actorId: actor.id,
858870 payload: { enabled: saved.enabled },
859871 });
872 return ok(getFollow(app.db, repo.id) ?? saved);
873 }
874
875 /** The words beside the control, with the upstream named (#16361). */
876 export const crewResolvesWords = (upstream: string): string =>
877 `When an update from ${upstream} and a change made here touch the same lines, the crew merges them for you. Off: the update waits, and an issue names the files for you to decide in the code.`;
878
879 /** Turn the crew's resolving of upstream conflicts on or off, for every door. Admins only. */
880 export function setCrewResolving(
881 app: App,
882 actor: User | undefined,
883 repo: Repo,
884 on: boolean,
885 ): Result<UpstreamFollow, "not_found" | "not_following"> {
886 if (actor === undefined || !canAdmin(app.db, repo, actor)) return err("not_found");
887 if (!setCrewResolves(app.db, repo.id, on)) return err("not_following");
888 const saved = getFollow(app.db, repo.id)!;
889 app.bus.append({
890 kind: "repo.upstream_follow",
891 repoId: repo.id,
892 actorId: actor.id,
893 payload: { enabled: saved.enabled, branch: saved.branch, crewResolves: on },
894 });
860895 return ok(saved);
861896 }
862897
src/cloud/harden.ts +4
@@ -66,6 +66,8 @@ packages:
6666 - curl
6767 - unzip
6868 - ca-certificates
69 - nodejs
70 - npm
6971 `;
7072 }
7173
@@ -98,6 +100,8 @@ RequiresMountsFor=${dir}
98100 User=${FORGE_USER}
99101 Group=${FORGE_USER}
100102 EnvironmentFile=/etc/forge/env
103 # The apps the forge starts are run by Bun: it is found on the unit's own path.
104 Environment=PATH=${BUN_HOME}/bin:/usr/local/bin:/usr/bin:/bin
101105 WorkingDirectory=${CHECKOUT}
102106 ExecStartPre=+/bin/sh -c 'mkdir -p ${dir} && find ${dir} -xdev -path ${proxyStore(dir)} -prune -o ! -user ${FORGE_USER} -exec chown -h ${FORGE_USER}:${FORGE_USER} {} +'
103107 ExecStart=${BUN_HOME}/bin/bun run src/main.ts
src/cloud/machine.ts +16 −3
@@ -20,7 +20,8 @@
2020
2121 import type { Fetch } from "./providers.ts";
2222 import { firstAdminSeed, readSeed } from "../core/first_admin.ts";
23 import { BOOT_NAMES, portOf, validHost, type Pinned } from "../core/pinned.ts";
23 import { BOOT_NAMES, portOf, validHost, validSource, type Pinned } from "../core/pinned.ts";
24 import { OWN_FORGE_REPO } from "../spawn/own_forge.ts";
2425 import { BUN_HOME, CHECKOUT, hardenEarly, hardenFiles, hardenHead, hardenLate, mount, proxyStore, serviceUnit } from "./harden.ts";
2526
2627 /**
@@ -42,6 +43,12 @@ export type Booted = Pick<Pinned, "name" | "source" | "version" | "config" | "ho
4243 * else, takes the claim's sha256 and deadline as its first-admin seed, and is told its crew runs
4344 * in the sandbox or not at all. The hash is all there is of the claim: the link is never handed
4445 * to this function.
46 *
47 * It also runs its own code (#16361): at first boot the checkout becomes its own repository
48 * (`FORGE_REPO`, `spawn/own_forge.ts`) following the source it was deployed from
49 * (`FORGE_UPSTREAM`), and the release keeper swaps in whatever lands on that repository's main.
50 * `FORGE_COMMIT` says which commit it runs, when the version is one, so a forge deployed from
51 * this one starts from that commit by default.
4552 */
4653 export function servedEnv(p: Booted): Record<string, string> {
4754 if (!validHost(p.host)) throw new Error("this forge has no name to be served on");
@@ -58,6 +65,11 @@ export function servedEnv(p: Booted): Record<string, string> {
5865 // The crew's shells run in the sandbox the machine was given (`harden.ts`), or not at all.
5966 FORGE_CREW_SANDBOX: "require",
6067 ...(seed === "" ? {} : { FORGE_FIRST_ADMIN_SEED: seed }),
68 ...(validSource(p.source) ? { FORGE_UPSTREAM: p.source } : {}),
69 ...(/^[0-9a-f]{40}$/.test(p.version) ? { FORGE_COMMIT: p.version } : {}),
70 FORGE_REPO: OWN_FORGE_REPO,
71 FORGE_RELEASE_KEEPER: "swap",
72 FORGE_SELF_SWAP: "1",
6173 };
6274 }
6375
@@ -70,7 +82,7 @@ export function servedEnv(p: Booted): Record<string, string> {
7082 * name a few Updates would otherwise spend.
7183 */
7284 export const proxyConfig = (p: Booted, dataDir: string): string =>
73 `{\n\tstorage file_system ${proxyStore(dataDir)}\n}\n${p.host} {\n\treverse_proxy 127.0.0.1:${portOf(p)}\n}\n`;
85 `{\n\tstorage file_system ${proxyStore(dataDir)}\n\ton_demand_tls {\n\t\task http://127.0.0.1:${portOf(p)}/__forge/domains/ask\n\t}\n}\n${p.host} {\n\treverse_proxy 127.0.0.1:${portOf(p)}\n}\n*.${p.host} {\n\ttls {\n\t\ton_demand\n\t}\n\treverse_proxy 127.0.0.1:${portOf(p)}\n}\n`;
7486
7587 /**
7688 * The proxy's `write_files` entries. Its config is written where the package reads it, before
@@ -127,9 +139,10 @@ ${hardenFiles()}
127139 runcmd:
128140 ${hardenEarly()}
129141 - curl -fsSL https://bun.sh/install | BUN_INSTALL=${BUN_HOME} bash -s "bun-v${BUN_VERSION}"
130 - git clone ${p.source} ${CHECKOUT}
142 - for try in 1 2 3 4 5; do git clone ${p.source} ${CHECKOUT} && break; rm -rf ${CHECKOUT}; sleep 15; done
131143 - git -C ${CHECKOUT} checkout --detach ${p.version}
132144 ${hardenLate()}
145 - npm install -g @anthropic-ai/claude-code || logger -t forge-boot crew not installed, the forge starts without it
133146 - systemctl enable --now forge.service
134147 ${proxyCommands(dataDir)}
135148 `;
src/cloud/providers.ts +33 −17
@@ -138,9 +138,16 @@ async function cloudflare(f: Fetch, token: string, method: string, path: string,
138138 * Delete the record a forge wrote (`upsertARecord` returned its zone and id): "deleted", "gone" when
139139 * Cloudflare no longer has it, or "refused" (a token that cannot edit the zone, any other answer).
140140 */
141 export async function deleteARecord(f: Fetch, token: string, zone: string, record: string): Promise<"deleted" | "gone" | "refused"> {
141 export async function deleteARecord(f: Fetch, token: string, zone: string, record: string, host?: string): Promise<"deleted" | "gone" | "refused"> {
142142 if (!CF_ID.test(zone) || !CF_ID.test(record)) return "refused";
143143 try {
144 // The apps' wildcard record that `upsertARecord` wrote beside it goes first, found by name; one that cannot be removed does not hold the forge's own.
145 if (host !== undefined) {
146 const found = await cloudflare(f, token, "GET", `/zones/${zone}/dns_records?name=${encodeURIComponent(`*.${host}`)}&per_page=20`);
147 for (const row of found.status === 200 ? (found.body?.result ?? []) : []) {
148 if (row?.type === "A" && CF_ID.test(String(row.id))) await cloudflare(f, token, "DELETE", `/zones/${zone}/dns_records/${row.id}`);
149 }
150 }
144151 const r = await cloudflare(f, token, "DELETE", `/zones/${zone}/dns_records/${record}`);
145152 return r.status === 200 ? "deleted" : r.status === 404 ? "gone" : "refused";
146153 } catch {
@@ -148,6 +155,27 @@ export async function deleteARecord(f: Fetch, token: string, zone: string, recor
148155 }
149156 }
150157
158 /** One A record `name` -> `address` in `zone`: found by name and updated, or made; see `upsertARecord`. */
159 async function putARecord(f: Fetch, token: string, zone: { id: string; name: string }, name: string, address: string): Promise<DnsWrite> {
160 const none = (why: string): DnsWrite => ({ done: "none", why });
161 const found = await cloudflare(f, token, "GET", `/zones/${zone.id}/dns_records?name=${encodeURIComponent(name)}&per_page=20`);
162 if (found.status !== 200) return none(`Cloudflare answered ${found.status} listing the records of ${zone.name}`);
163 const rows: any[] = found.body?.result ?? [];
164 if (rows.some((r) => r?.type === "CNAME")) return none(`${name} has a CNAME record, which cannot sit beside an address record`);
165 const mine = rows.find((r) => r?.type === "A");
166 const want = { content: address, ttl: 60, proxied: false };
167 if (mine !== undefined && CF_ID.test(String(mine.id))) {
168 if (mine.content === address && mine.proxied === false && mine.ttl === 60) return { done: "unchanged", zone: zone.id, record: String(mine.id) };
169 const r = await cloudflare(f, token, "PATCH", `/zones/${zone.id}/dns_records/${mine.id}`, want);
170 if (r.status === 401 || r.status === 403) return none(`the token cannot edit DNS records in ${zone.name}`);
171 return r.status === 200 ? { done: "updated", zone: zone.id, record: String(mine.id) } : none(`Cloudflare answered ${r.status} updating ${name}`);
172 }
173 const r = await cloudflare(f, token, "POST", `/zones/${zone.id}/dns_records`, { type: "A", name, ...want, comment: "a pinned forge, written by the forge that deployed it" });
174 if (r.status === 401 || r.status === 403) return none(`the token cannot edit DNS records in ${zone.name}`);
175 const made = String(r.body?.result?.id ?? "");
176 return (r.status === 200 || r.status === 201) && CF_ID.test(made) ? { done: "created", zone: zone.id, record: made } : none(`Cloudflare answered ${r.status} making ${name}`);
177 }
178
151179 /**
152180 * Make `host` an A record for `address` in the Cloudflare zone that holds it: DNS only (never
153181 * proxied, so the forge's own certificate is issued), a one-minute TTL. The record is found by
@@ -169,22 +197,10 @@ export async function upsertARecord(f: Fetch, token: string, host: string, addre
169197 if (hit?.name === name && CF_ID.test(String(hit.id))) zone = { id: String(hit.id), name };
170198 }
171199 if (zone === undefined) return none(`no zone this token can see holds ${host}`);
172 const found = await cloudflare(f, token, "GET", `/zones/${zone.id}/dns_records?name=${encodeURIComponent(host)}&per_page=20`);
173 if (found.status !== 200) return none(`Cloudflare answered ${found.status} listing the records of ${zone.name}`);
174 const rows: any[] = found.body?.result ?? [];
175 if (rows.some((r) => r?.type === "CNAME")) return none(`${host} has a CNAME record, which cannot sit beside an address record`);
176 const mine = rows.find((r) => r?.type === "A");
177 const want = { content: address, ttl: 60, proxied: false };
178 if (mine !== undefined && CF_ID.test(String(mine.id))) {
179 if (mine.content === address && mine.proxied === false && mine.ttl === 60) return { done: "unchanged", zone: zone.id, record: String(mine.id) };
180 const r = await cloudflare(f, token, "PATCH", `/zones/${zone.id}/dns_records/${mine.id}`, want);
181 if (r.status === 401 || r.status === 403) return none(`the token cannot edit DNS records in ${zone.name}`);
182 return r.status === 200 ? { done: "updated", zone: zone.id, record: String(mine.id) } : none(`Cloudflare answered ${r.status} updating ${host}`);
183 }
184 const r = await cloudflare(f, token, "POST", `/zones/${zone.id}/dns_records`, { type: "A", name: host, ...want, comment: "a pinned forge, written by the forge that deployed it" });
185 if (r.status === 401 || r.status === 403) return none(`the token cannot edit DNS records in ${zone.name}`);
186 const made = String(r.body?.result?.id ?? "");
187 return (r.status === 200 || r.status === 201) && CF_ID.test(made) ? { done: "created", zone: zone.id, record: made } : none(`Cloudflare answered ${r.status} making ${host}`);
200 const own = await putARecord(f, token, zone, host, address);
201 // The apps' names, `*.<host>`, go to the same address: best effort, since the forge's own record is the one that must be kept.
202 if (own.done !== "none") await putARecord(f, token, zone, `*.${host}`, address).catch(() => undefined);
203 return own;
188204 } catch (e) {
189205 return none(`Cloudflare could not be reached: ${e instanceof Error ? e.message.slice(0, 100) : "failed"}`);
190206 }
src/core/migration-pins/20261124200000-follow-crew-resolves.pin added +1
@@ -0,0 +1,1 @@
1 34b8f52112f4f1c486937ea8227c6850fe0069913076fe8c4d70a27c75c36cbb
src/core/migrations/20261124200000-follow-crew-resolves.ts added +6
@@ -0,0 +1,6 @@
1 // Whether the crew resolves a followed upstream's conflicts (#16361): off unless the repository's
2 // admin turns it on. Off, a conflict opens one issue naming the files and waits for a person.
3 // Additive; every row starts off.
4 export default `
5 ALTER TABLE repo_upstream ADD COLUMN crew_resolves INTEGER NOT NULL DEFAULT 0;
6 `;
src/core/orgs.ts +9 −6
@@ -47,12 +47,14 @@ export type CreateOrgError = "invalid_name" | "name_taken" | "name_reserved";
4747 * Create an org and its Owners team, with `founderId` as the first owner.
4848 * An org shares the account namespace, so it is held to the reserved-name
4949 * rule here, where orgs are made (#720); `allowReserved` is a seed's named
50 * opt-out (a spawned forge's own org), never a default.
50 * opt-out (a spawned forge's own org), never a default. A `null` founder leaves
51 * the Owners team empty: a deployed forge's own org, made at first boot before
52 * any person exists, held by the site's admins (`spawn/own_forge.ts`).
5153 */
5254 export function createOrg(
5355 db: Database,
5456 name: string,
55 founderId: string,
57 founderId: string | null,
5658 options: { allowReserved?: boolean } = {},
5759 ): Result<User, CreateOrgError> {
5860 if (!isSafeName(name)) return err("invalid_name");
@@ -72,10 +74,11 @@ export function createOrg(
7274 db.query(
7375 "INSERT INTO team (id, org_id, name, permission) VALUES (?1, ?2, ?3, 'admin')",
7476 ).run(teamId, orgId, OWNERS_TEAM);
75 db.query("INSERT INTO team_member (team_id, user_id) VALUES (?1, ?2)").run(
76 teamId,
77 founderId,
78 );
77 if (founderId !== null)
78 db.query("INSERT INTO team_member (team_id, user_id) VALUES (?1, ?2)").run(
79 teamId,
80 founderId,
81 );
7982 });
8083 create();
8184 return ok(getUserById(db, orgId)!);
src/core/pinned.ts +6 −2
@@ -86,9 +86,13 @@ const KEY = /^[A-Z][A-Z0-9_]{0,63}$/;
8686 const VALUE = /^[A-Za-z0-9 _.,:\/@+=-]{0,512}$/;
8787 /**
8888 * What the boot config sets itself (`servedEnv` and the data directory, `cloud/machine.ts`): the
89 * forge's name, its listeners, who may say the client's address, its claim, its sandbox, its data.
89 * forge's name, its listeners, who may say the client's address, its claim, its sandbox, its data,
90 * and its own code: the repository it runs, what that follows, the commit, its release keeper.
9091 */
91 export const BOOT_NAMES: readonly string[] = ["FORGE_URL", "FORGE_HOST", "FORGE_BIND", "FORGE_TRUSTED_PROXIES", "FORGE_SSH_PORT", "FORGE_FIRST_ADMIN_SEED", "FORGE_CREW_SANDBOX", "FORGE_DATA", "FORGE_APP_DATA"];
92 export const BOOT_NAMES: readonly string[] = [
93 "FORGE_URL", "FORGE_HOST", "FORGE_BIND", "FORGE_TRUSTED_PROXIES", "FORGE_SSH_PORT", "FORGE_FIRST_ADMIN_SEED", "FORGE_CREW_SANDBOX", "FORGE_DATA", "FORGE_APP_DATA",
94 "FORGE_REPO", "FORGE_UPSTREAM", "FORGE_COMMIT", "FORGE_RELEASE_KEEPER", "FORGE_SELF_SWAP",
95 ];
9296 const SECRETISH = /SECRET|TOKEN|PASSWORD|PASSWD|PASSPHRASE|PRIVATE|CREDENTIAL|COOKIE|AUTH(?!OR)|API_?KEY|ACCESS_?KEY|(?:^|_)KEYS?(?:_|$)/;
9397 // A name that steers the dynamic loader, the runtime, the path or the shell of the process it is
9498 // set for is never a setting: it is the unit's environment, and a forge that runs as itself must
src/core/upstream_follow.ts +16
@@ -45,6 +45,11 @@ export interface UpstreamFollow {
4545 readonly ahead: number;
4646 /** When the owner severed the link; null while it was never severed. A repair never links it again. */
4747 readonly severedAt: string | null;
48 /**
49 * Whether the crew merges a conflicting update for the owner (#16361). Off by default: the
50 * update waits, and one issue names the files for a person to decide.
51 */
52 readonly crewResolves: boolean;
4853 }
4954
5055 /** What a follow's sealed credential is sealed against: this repository's row, so it opens nowhere else. */
@@ -94,6 +99,7 @@ interface Row {
9499 credential_enc: string;
95100 severed_at: string | null;
96101 ahead: number;
102 crew_resolves: number;
97103 }
98104
99105 const fromRow = (r: Row): UpstreamFollow => ({
@@ -116,6 +122,7 @@ const fromRow = (r: Row): UpstreamFollow => ({
116122 credentialEnc: r.credential_enc,
117123 severedAt: r.severed_at,
118124 ahead: r.ahead,
125 crewResolves: r.crew_resolves === 1,
119126 });
120127
121128 export function getFollow(db: Database, repoId: string): UpstreamFollow | undefined {
@@ -206,6 +213,15 @@ export function putFollow(
206213 */
207214 export const inheritsPending = (f: UpstreamFollow): boolean => f.pendingId !== null && f.tip === "";
208215
216 /** Whether the crew resolves the repository's upstream conflicts; false when it follows nothing. */
217 export const crewResolves = (db: Database, repoId: string): boolean =>
218 db.query<{ v: number }, [string]>("SELECT crew_resolves AS v FROM repo_upstream WHERE repo_id = ?1").get(repoId)?.v === 1;
219
220 /** Turn the crew's conflict resolving on or off; false when the repository follows nothing. */
221 export function setCrewResolves(db: Database, repoId: string, on: boolean): boolean {
222 return db.query("UPDATE repo_upstream SET crew_resolves = ?2 WHERE repo_id = ?1").run(repoId, on ? 1 : 0).changes > 0;
223 }
224
209225 /** Choose what the forge does with new upstream commits from now on; false when the repository follows nothing. */
210226 export function setFollowTaking(db: Database, repoId: string, mode: FollowTaking): boolean {
211227 return db.query("UPDATE repo_upstream SET mode = ?2 WHERE repo_id = ?1").run(repoId, mode).changes > 0;
src/http/server.ts +10 −1
@@ -688,6 +688,7 @@ import {
688688 isWebSocketHandshake,
689689 proxyApp,
690690 resolveAppHost,
691 resolveAppHostname,
691692 unknownApp,
692693 } from "../apps/proxy.ts";
693694
@@ -1240,8 +1241,16 @@ export function buildRouter(): Router<Handler> {
12401241 // Literal, above /:owner.
12411242 router.add("GET", "/__forge/domains/ask", (ctx) => {
12421243 const host = ctx.url.searchParams.get("domain") ?? "";
1244 // A verified custom domain, or an app of this forge shown at `<app>.<apps domain>`.
1245 const runtime = appsRuntime(ctx.app);
1246 const asApp =
1247 host !== "" && runtime !== undefined
1248 ? resolveAppHostname(ctx.app, runtime.options.domain, host.toLowerCase().replace(/\.$/, ""))
1249 : undefined;
12431250 const known =
1244 host !== "" && getVerifiedDomain(ctx.app.db, host) !== undefined;
1251 host !== "" &&
1252 (getVerifiedDomain(ctx.app.db, host) !== undefined ||
1253 (asApp !== undefined && asApp !== "unknown"));
12451254 return new Response(null, {
12461255 status: known ? 200 : 404,
12471256 headers: { "cache-control": "no-store" },
src/keeper/wire.ts +17 −11
@@ -18,7 +18,7 @@ import { join } from "node:path";
1818 import type { App } from "../app.ts";
1919 import { originPush } from "../actions/branches.ts";
2020 import { serviceAccount } from "../cluster/jobs.ts";
21 import { getRepo, type Repo } from "../core/repos.ts";
21 import { getRepo, getRepoById, type Repo } from "../core/repos.ts";
2222 import { createSession, destroySession } from "../core/sessions.ts";
2323 import { getUserById, type User } from "../core/users.ts";
2424 import { gatesInFlight } from "../checks/queue.ts";
@@ -111,7 +111,12 @@ export function keeperPorts(app: App, input: { forgeUrl: string; deployment: str
111111 // The reason never carries the repository's name: it is noted at boot and may reach a
112112 // public issue (#11924).
113113 if (repo === undefined) return "FORGE_REPO names no repository on this forge";
114 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
114 // Read on each step, not once: a repository moved to its owner at the claim (#16361) keeps
115 // its id, and its directory follows its path.
116 const dir = (): string => {
117 const now = getRepoById(app.db, repo.id) ?? repo;
118 return repoDir(app.reposRoot, now.ownerName, now.name);
119 };
115120 const deployer =
116121 input.swap === true
117122 ? swapper({
@@ -121,7 +126,7 @@ export function keeperPorts(app: App, input: { forgeUrl: string; deployment: str
121126 version: () => running().version,
122127 commit: () => running().commit,
123128 env: process.env,
124 checkout: (sha) => checkoutRelease(app.config.dataDir, dir, sha),
129 checkout: (sha) => checkoutRelease(app.config.dataDir, dir(), sha),
125130 preflight: (tree) => preflightRelease(tree, app.config.dataDir),
126131 drain: () => handover.drain?.(),
127132 timed: switched(app.db, runningAgentRuns),
@@ -130,7 +135,7 @@ export function keeperPorts(app: App, input: { forgeUrl: string; deployment: str
130135 })
131136 : kubeDeployer({ credentials: serviceAccount(), deployment: input.deployment, container: input.container });
132137 const probeHeaders = ownProbeHeaders(app.config.dataDir);
133 const at = (version: string) => runGit(["rev-parse", "--verify", "--quiet", `refs/tags/v${version}^{commit}`], { cwd: dir });
138 const at = (version: string) => runGit(["rev-parse", "--verify", "--quiet", `refs/tags/v${version}^{commit}`], { cwd: dir() });
134139 return {
135140 ...(input.swap === true ? { minIntervalMs: SWAP_INTERVAL_MS } : {}),
136141 db: app.db,
@@ -141,11 +146,11 @@ export function keeperPorts(app: App, input: { forgeUrl: string; deployment: str
141146 bootStallMs: () => bootStall.worst(),
142147 writePauseMs: () => writePause(),
143148 async main() {
144 const head = await runGit(["rev-parse", "--verify", "--quiet", `refs/heads/${repo.defaultBranch}^{commit}`], { cwd: dir });
149 const head = await runGit(["rev-parse", "--verify", "--quiet", `refs/heads/${repo.defaultBranch}^{commit}`], { cwd: dir() });
145150 return head.ok && OID.test(head.value) ? head.value : undefined;
146151 },
147152 async newest() {
148 const tags = await readTags(dir);
153 const tags = await readTags(dir());
149154 if (!tags.ok) return undefined;
150155 const top = [...tags.value].filter((t) => VERSION.test(t.version)).sort((a, b) => compareVersions(b.version, a.version))[0];
151156 if (top === undefined) return undefined;
@@ -167,18 +172,18 @@ export function keeperPorts(app: App, input: { forgeUrl: string; deployment: str
167172 // from at the earliest.
168173 const record = JSON.stringify(recordFor(version, migrationFiles, NUMBERED));
169174 const made = await runGit(["tag", "--annotate", "--file=-", `v${version}`, sha], {
170 cwd: dir,
175 cwd: dir(),
171176 stdin: `${record}\n`,
172177 env: { GIT_COMMITTER_NAME: "release keeper", GIT_COMMITTER_EMAIL: "[email protected]" },
173178 });
174179 if (!made.ok) return made.error.stderr || "git refused the tag";
175 const tagOid = await runGit(["rev-parse", `refs/tags/v${version}`], { cwd: dir });
180 const tagOid = await runGit(["rev-parse", `refs/tags/v${version}`], { cwd: dir() });
176181 const owner = getUserById(app.db, repo.ownerId);
177182 // A swap needs no origin: the tag is the forge's own record of the release.
178183 if (!tagOid.ok || owner === undefined || input.swap === true) return undefined;
179184 // A tag the origin did not take is taken back here too: the keeper drops the cut, and a
180185 // tag left behind would be the newest, never live, and stall the cadence.
181 const untag = async (why: string) => (await runGit(["tag", "--delete", `v${version}`], { cwd: dir }), why);
186 const untag = async (why: string) => (await runGit(["tag", "--delete", `v${version}`], { cwd: dir() }), why);
182187 const push = await originPush(app, owner, repo);
183188 if (!push.ok) return untag(`the origin refused v${version}: ${push.error}`);
184189 if (push.value === undefined) return undefined;
@@ -195,13 +200,14 @@ export function keeperPorts(app: App, input: { forgeUrl: string; deployment: str
195200 get: timedGet(input.forgeUrl, (asAdmin) => (asAdmin ? cookie : probeHeaders)),
196201 now: () => Date.now(),
197202 sleep: (ms) => Bun.sleep(ms),
198 pages: loadPages(repo),
203 // The repository where it is now: the probe takes no redirect.
204 pages: loadPages(getRepoById(app.db, repo.id) ?? repo),
199205 onProbe,
200206 });
201207 if (!loaded.ok) return loaded;
202208 // A 200 is not proof a person can use the page: look at a phone (#11855).
203209 const look = probeCentre(input.forgeUrl, session === undefined ? undefined : { name: "forge_session", value: session.token });
204 return phoneGate(loaded, phonePages(repo), look);
210 return phoneGate(loaded, phonePages(getRepoById(app.db, repo.id) ?? repo), look);
205211 } finally {
206212 if (session !== undefined) destroySession(app.db, session.token);
207213 }
src/main.ts +5
@@ -163,6 +163,7 @@ import { noteWritePause } from "./keeper/pause.ts";
163163 import { closeStaleSessions } from "./machines/shell.ts";
164164 import { setOwnHost } from "./kernel/own_host.ts";
165165 import { seedFirstAdmin } from "./core/first_admin.ts";
166 import { ownForgeAtBoot } from "./spawn/own_forge.ts";
166167
167168 // `forge hook <name>` re-enters here from a git hook stub. It relays to the
168169 // running forge over its socket and exits — it must never boot a server.
@@ -420,6 +421,10 @@ if (!readOnly) {
420421 process.exit(1);
421422 }
422423 if (seeded === "seeded") app.log.info("first-admin code seeded by the forge that deployed this one");
424 // Its own repository, following the forge it was deployed from (#16361), before any claim.
425 const own = await ownForgeAtBoot(app, process.env);
426 if (!own.ok) app.log.warn("the forge's own repository was not made", { why: own.error });
427 else if (own.value === "made") app.log.info("the forge's own repository was made from its checkout");
423428 }
424429
425430 // A statement that holds the thread past 200 ms names its caller (#6957).
src/spawn/forge_code.ts +22 −14
@@ -82,24 +82,32 @@ export async function forkForgeCode(
8282 if (!made.ok) return err(`could not make the child's forge repo: ${made.error}`);
8383 repo = made.value;
8484 }
85 // The history packed straight into the child first:
86 // the fetch below then has nothing to send (#12171).
87 await seedHistory(repoDir(app.reposRoot, o, n), repoDir(child.reposRoot, orgName, FORGE_CODE_NAME));
88 const fetched = await runGit(
89 [
90 "fetch",
91 "--no-write-fetch-head",
92 repoDir(app.reposRoot, o, n),
93 "+refs/heads/*:refs/heads/*",
94 "+refs/tags/*:refs/tags/*",
95 ],
96 { cwd: repoDir(child.reposRoot, orgName, FORGE_CODE_NAME), timeoutMs: 600_000 },
97 );
98 if (!fetched.ok) return err(`could not copy the forge's code: ${fetched.error.stderr}`);
85 const copied = await copyForgeCode(repoDir(app.reposRoot, o, n), repoDir(child.reposRoot, orgName, FORGE_CODE_NAME));
86 if (!copied.ok) return copied;
9987 const born = await chainForChild(app, `${o}/${n}`);
10088 return ok({ upstream: `${o}/${n}`, mode, tip: born?.tip ?? "", chain: born?.chain ?? [] });
10189 }
10290
91 /**
92 * Copy a forge's code, every head and tag with the history behind them, into the bare
93 * repository at `to`. `from` is a repository's directory on this machine (its history is packed
94 * straight in first, so the fetch has nothing to send, #12171) or an https address. `heads` is
95 * the branch refspec: every head by default; a deployed forge takes the checkout's `HEAD` as its
96 * main (`spawn/own_forge.ts`).
97 */
98 export async function copyForgeCode(
99 from: string,
100 to: string,
101 heads = "+refs/heads/*:refs/heads/*",
102 ): Promise<Result<void, string>> {
103 if (!from.startsWith("https://")) await seedHistory(from, to);
104 const fetched = await runGit(["fetch", "--no-write-fetch-head", from, heads, "+refs/tags/*:refs/tags/*"], {
105 cwd: to,
106 timeoutMs: 600_000,
107 });
108 return fetched.ok ? ok(undefined) : err(`could not copy the forge's code: ${fetched.error.stderr}`);
109 }
110
103111 /**
104112 * Make the fork the child's own source: its `forgeRepo` names it (an admin's
105113 * earlier choice stands) and every crew member is seated on it, with the
src/spawn/own_forge.ts added +181
@@ -0,0 +1,181 @@
1 /**
2 * A deployed forge runs its own repository (#16361). The machine boots the
3 * deployer's code from the checkout at `/opt/forge` (`cloud/machine.ts`); at
4 * first boot, before anyone claims it, that checkout's history and tags
5 * become `forge/forge` here, the forge's own source (`FORGE_REPO`), following
6 * the repository it was deployed from (`FORGE_UPSTREAM`) with take-updates.
7 * The release keeper (`FORGE_RELEASE_KEEPER=swap`) runs whatever lands on its
8 * main, so the forge updates itself when its upstream moves or its owner
9 * merges, and a forge deployed from this one follows it in turn.
10 *
11 * At the claim the repository moves to the new admin's own account
12 * (`moveOwnForge`): the forge's code is theirs, under their name, and the
13 * old path is a redirect. The setting `forgeRepo` and this process's config
14 * name the new path, so the follow (keyed by the repository's id) and the
15 * keeper (which reads the path on each step) carry on.
16 *
17 * Every step is idempotent: a restart finds what it made and changes nothing.
18 */
19
20 import { join } from "node:path";
21 import type { App } from "../app.ts";
22 import { createOrg, getOrg } from "../core/orgs.ts";
23 import { createRepo, getRepo, type Repo } from "../core/repos.ts";
24 import { transferRepo } from "../core/transfer.ts";
25 import { getFollow, putFollow, upstreamUrl } from "../core/upstream_follow.ts";
26 import type { User } from "../core/users.ts";
27 import { runGit } from "../git/env.ts";
28 import { repoDir } from "../git/repos.ts";
29 import { err, ok, type Result } from "../kernel/result.ts";
30 import { setForgeSource, storedForgeSource } from "../settings/forge_source.ts";
31 import {
32 adoptForgeCode,
33 copyForgeCode,
34 FORGE_CODE_NAME,
35 } from "./forge_code.ts";
36
37 /** The reserved organisation a deployed forge's code waits in until a person claims the forge. */
38 export const OWN_FORGE_ORG = "forge";
39 /** `owner/name` of that repository: what the deploy sets as `FORGE_REPO`. */
40 export const OWN_FORGE_REPO = `${OWN_FORGE_ORG}/${FORGE_CODE_NAME}`;
41 /** The follow's `via`: the link the deploy made, which the claim moves. */
42 export const DEPLOYER_VIA = "deployer";
43
44 /** The tree this process runs from: the machine's checkout. */
45 const OWN_TREE = join(import.meta.dir, "..", "..");
46
47 export type OwnForge = "off" | "made" | "kept";
48
49 /**
50 * Make the forge's own repository at first boot, when the deploy named an upstream; once made
51 * (or once a person named another source) it is left as it is. Sets this process's `forgeRepo`
52 * to the repository the setting names, so a forge claimed and restarted reads its moved path.
53 */
54 export async function ownForgeAtBoot(
55 app: App,
56 env: Readonly<Record<string, string | undefined>>,
57 tree: string = OWN_TREE,
58 ): Promise<Result<OwnForge, string>> {
59 const raw = (env["FORGE_UPSTREAM"] ?? "").trim();
60 if (raw === "") return ok("off");
61 const url = upstreamUrl(raw);
62 if (url === undefined || !url.startsWith("https://"))
63 return err("FORGE_UPSTREAM is not an https address without credentials");
64 const stored = storedForgeSource(app.db);
65 // Claimed and moved, or a person named another source: theirs, as it is.
66 if (stored !== undefined && stored !== OWN_FORGE_REPO) {
67 app.config.forgeRepo = stored;
68 return ok("kept");
69 }
70 let made = false;
71 let org = getOrg(app.db, OWN_FORGE_ORG);
72 if (org === undefined) {
73 // Before any person exists: an Owners team with nobody on it, held by the site's admins.
74 const created = createOrg(app.db, OWN_FORGE_ORG, null, {
75 allowReserved: true,
76 });
77 if (!created.ok)
78 return err(
79 `could not make the ${OWN_FORGE_ORG} organisation: ${created.error}`,
80 );
81 org = created.value;
82 made = true;
83 }
84 let repo = getRepo(app.db, OWN_FORGE_ORG, FORGE_CODE_NAME);
85 if (repo === undefined) {
86 const created = await createRepo(app.db, app.reposRoot, {
87 ownerId: org.id,
88 name: FORGE_CODE_NAME,
89 // Public, as the repository it follows is: a forge deployed from this one reads it.
90 visibility: "public",
91 description:
92 "This forge's own code: what it runs, following the forge it was deployed from.",
93 defaultBranch: "main",
94 });
95 if (!created.ok)
96 return err(`could not make ${OWN_FORGE_REPO}: ${created.error}`);
97 repo = created.value;
98 made = true;
99 }
100 const dir = repoDir(app.reposRoot, OWN_FORGE_ORG, FORGE_CODE_NAME);
101 // A boot that died before the copy finished finds no main and copies again. The checkout's
102 // HEAD is the commit this machine runs, so main is that commit and nothing newer.
103 const main = await runGit(
104 ["rev-parse", "--verify", "--quiet", "refs/heads/main^{commit}"],
105 { cwd: dir },
106 );
107 if (!main.ok) {
108 const copied = await copyForgeCode(tree, dir, "+HEAD:refs/heads/main");
109 if (!copied.ok) return copied;
110 made = true;
111 }
112 adoptForgeCode(app, OWN_FORGE_ORG, org.id);
113 if (getFollow(app.db, repo.id) === undefined) {
114 putFollow(app.db, {
115 repoId: repo.id,
116 url,
117 branch: "main",
118 enabled: true,
119 byId: org.id,
120 originId: "",
121 mode: "take-updates",
122 via: DEPLOYER_VIA,
123 });
124 made = true;
125 }
126 app.config.forgeRepo = OWN_FORGE_REPO;
127 if (made)
128 app.bus.append({
129 kind: "repo.upstream_follow",
130 repoId: repo.id,
131 actorId: org.id,
132 payload: { enabled: true, branch: "main" },
133 });
134 return ok(made ? "made" : "kept");
135 }
136
137 /**
138 * At the claim: the forge's own repository becomes the new admin's, under their name, and the
139 * forge's source names it there. Only the repository the deploy made, while it still waits in the
140 * reserved organisation, is moved; anything else is left alone (undefined).
141 */
142 export async function moveOwnForge(
143 app: App,
144 person: User,
145 ): Promise<Result<Repo | undefined, string>> {
146 const repo = getRepo(app.db, OWN_FORGE_ORG, FORGE_CODE_NAME);
147 const follow = repo === undefined ? undefined : getFollow(app.db, repo.id);
148 if (
149 repo === undefined ||
150 follow?.via !== DEPLOYER_VIA ||
151 storedForgeSource(app.db) !== OWN_FORGE_REPO
152 )
153 return ok(undefined);
154 const moved = await transferRepo(
155 app.db,
156 app.reposRoot,
157 repo,
158 person,
159 person.id,
160 );
161 if (!moved.ok) return err(moved.error);
162 const path = `${moved.value.ownerName}/${moved.value.name}`;
163 setForgeSource(app.db, path, person.id);
164 app.config.forgeRepo = path;
165 // The forge now acts for its owner when it proposes an update.
166 putFollow(app.db, {
167 repoId: repo.id,
168 url: follow.url,
169 branch: follow.branch,
170 enabled: follow.enabled,
171 byId: person.id,
172 originId: follow.originId,
173 });
174 app.bus.append({
175 kind: "repo.transferred",
176 repoId: repo.id,
177 actorId: person.id,
178 payload: { from: OWN_FORGE_REPO, to: path },
179 });
180 return ok(moved.value);
181 }
src/tui/screens/forks.ts +17 −1
@@ -26,6 +26,8 @@ import { upstreamCounts } from "../../actions/upstream_counts.ts";
2626 import { FOLLOW_MODE_REFUSALS, convergeWords, followModeOf, followStanding, followWords, lastModeChange, setFollowMode, takeOrTell, takeWords } from "../../actions/follow.ts";
2727 import { incomingOf, type Incoming } from "../../actions/follow_incoming.ts";
2828 import { convergeFollowed, followedAs, followedOf } from "../../actions/upstream_sync.ts";
29 import { crewResolvesWords, setCrewResolving, upstreamLabel } from "../../actions/upstream_follow.ts";
30 import type { UpstreamFollow } from "../../core/upstream_follow.ts";
2931 import { ancestry, ancestryLine } from "../../core/fork_ancestry.ts";
3032 import { forkOffers, sentOffers } from "../../core/fork_offers.ts";
3133 import { offerSizes, sizeLine } from "../../git/offer_size.ts";
@@ -194,6 +196,7 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
194196 let incoming: Incoming | undefined;
195197 /** What the repository follows by address, when it has no parent here. */
196198 let followed: ReturnType<typeof followedAs> | undefined;
199 let address: UpstreamFollow | undefined;
197200 let open: Pull | undefined;
198201 let mode: ForkFollowMode | undefined;
199202 let undo: { was: ForkFollowMode; at: string } | undefined;
@@ -262,7 +265,7 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
262265 relation = await relationOf(f.app, f.user, repo);
263266 open = relation === undefined ? undefined : openProposal(f.app, repo, relation.parent);
264267 incoming = relation === undefined ? undefined : await incomingOf(f.app.reposRoot, repo, relation);
265 const address = relation === undefined ? followedOf(f.app, repo) : undefined;
268 address = relation === undefined ? followedOf(f.app, repo) : undefined;
266269 followed = address === undefined ? undefined : followedAs(address);
267270 offer =
268271 followed === undefined
@@ -361,6 +364,8 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
361364 };
362365 const canSetMode = (): boolean =>
363366 relation !== undefined && f.user?.kind === "user" && canAdmin(f.db, repo, f.user) && canWrite(f.db, repo, f.user);
367 // An address follow's admin turns the crew's conflict resolving on and off with `r` (#16361).
368 const mayResolve = (): boolean => address !== undefined && f.user?.kind === "user" && canAdmin(f.db, repo, f.user);
364369 const self: Screen = {
365370 title: "Forks",
366371 get keys() {
@@ -373,6 +378,7 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
373378 ? [binding(["u"], open === undefined ? "propose upstream" : "open proposal")]
374379 : []),
375380 ...(canSetMode() ? [binding(["m"], "follow mode")] : []),
381 ...(mayResolve() ? [binding(["r"], address?.crewResolves === true ? "crew resolves conflicts: on" : "crew resolves conflicts: off")] : []),
376382 ...(canSetMode() && undo !== undefined ? [binding(["z"], "undo mode change")] : []),
377383 binding(["esc"], "close"),
378384 ];
@@ -446,6 +452,16 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
446452 converge();
447453 return true;
448454 }
455 if (e.key === "r" && mayResolve() && address !== undefined) {
456 const set = setCrewResolving(f.app, f.user, repo, !address.crewResolves);
457 if (!set.ok) {
458 ctx.toast("This repository follows no upstream.", "danger");
459 return true;
460 }
461 address = set.value;
462 ctx.toast(`${set.value.crewResolves ? "On" : "Off"}. ${crewResolvesWords(upstreamLabel(set.value.url))}`, "success");
463 return true;
464 }
449465 if (e.key === "m" && canSetMode()) {
450466 runAsync(ctx, async () => {
451467 // `m` steps through the three modes in turn.
src/web/pages/upstream-follow.ts +8
@@ -12,6 +12,7 @@ import {
1212 checkUpstreamNow,
1313 clockWords,
1414 conflictWaitingWords,
15 crewResolvesWords,
1516 FOLLOW_REFUSALS,
1617 followShown,
1718 openConflictIssue,
@@ -198,6 +199,12 @@ export function followUpstreamCard(ctx: Ctx, repo: Repo, choice: Html | null = n
198199 <span>Take its updates by itself when this branch has nothing the upstream lacks; otherwise they come as a pull, and nothing of yours is lost</span>
199200 </label>
200201 </div>
202 ${follow === undefined
203 ? null
204 : html`<label class="check" data-crew-resolves title="${crewResolvesWords(upstreamLabel(follow.url))}">
205 <input type="checkbox" name="resolve" ${follow.crewResolves ? html`checked` : null} />
206 <span>Crew merges conflicting updates. Off: they wait for you to decide in the code.</span>
207 </label>`}
201208 ${when(
202209 follow,
203210 (f) => html`<p class="hint" data-following-standing>${standing(f)}${
@@ -242,6 +249,7 @@ export async function followUpstreamUpdate(ctx: Ctx): Promise<Response> {
242249 branch: field(form, "branch"),
243250 enabled: form.get("enabled") !== null,
244251 mode: form.get("take") !== null ? "take-updates" : "tell-me",
252 crewResolves: form.get("resolve") !== null,
245253 });
246254 return flashTo(
247255 ctx,
src/web/pinned.ts +2 −2
@@ -98,8 +98,8 @@ export function deployPage(accounts: CloudAccount[], v: DeployForm, places: Plac
9898 ],
9999 })}
100100 ${field({ name: "app", label: "App", value: v.app, placeholder: "owner/name", mono: true, required: true, maxlength: 140, spellcheck: false })}
101 ${field({ name: "source", label: "Source", value: v.source, placeholder: "https://…", mono: true, required: true, maxlength: 400, spellcheck: false, hint: "An https git address." })}
102 ${field({ name: "version", label: "Version", value: v.version, mono: true, required: true, maxlength: 40, spellcheck: false, hint: "A full 40-character commit id or a tag like v1.2.3 — never a branch." })}
101 ${field({ name: "source", label: "Source", value: v.source, placeholder: "https://…", mono: true, maxlength: 400, spellcheck: false, hint: "An https git address. Empty: this forge's own repository, which the new forge follows." })}
102 ${field({ name: "version", label: "Version", value: v.version, mono: true, maxlength: 40, spellcheck: false, hint: "A full 40-character commit id or a tag like v1.2.3 — never a branch. Empty: the commit this forge runs." })}
103103 ${field({ name: "name", label: "Name", value: v.name, mono: true, required: true, maxlength: 40, spellcheck: false, hint: "Lowercase letters, digits and dashes." })}
104104 ${field({ name: "host", label: "Hostname", value: v.host, placeholder: domain === "" ? "forge.example.com" : `<name>.${domain}`, mono: true, required: domain === "", maxlength: 253, spellcheck: false, hint: domain === "" ? "The name it is served on, over HTTPS only. You create its DNS record once the deploy says the address, unless a Cloudflare account that allows writes can edit its zone and the forge writes it." : `Left empty it is the name above on ${domain}, and the forge writes its DNS record when a Cloudflare account that allows writes can edit the zone: nothing to configure. A full hostname may be given instead.` })}
105105 ${btn("Deploy", { variant: "primary", icon: "plus" })}
test/app-domains.test.ts +3
@@ -544,6 +544,9 @@ describe("an app gets its own domain", () => {
544544 expect((await ask("APP.EXAMPLE.COM.")).status).toBe(200);
545545 expect((await ask("example.com")).status).toBe(404);
546546 expect((await ask("nope.example.com")).status).toBe(404);
547 // An app of this forge at `<app>.<apps domain>` is asked for too; a made-up one is not.
548 expect((await ask(`notes.${DOMAIN}`)).status).toBe(200);
549 expect((await ask(`nothing-here.${DOMAIN}`)).status).toBe(404);
547550 expect((await viaHost("forge.test", "/__forge/domains/ask")).status).toBe(
548551 404,
549552 );
test/keeper-covered.test.ts +1 −1
@@ -96,6 +96,6 @@ describe("phoneGate", () => {
9696
9797 test("the keeper's verify goes through phoneGate, with the session token kept whole as the cookie value", async () => {
9898 const src = await Bun.file(new URL("../src/keeper/wire.ts", import.meta.url)).text();
99 expect(src).toContain("return phoneGate(loaded, phonePages(repo), look)");
99 expect(src).toContain("return phoneGate(loaded, phonePages(getRepoById(app.db, repo.id) ?? repo), look)");
100100 expect(src).toContain('{ name: "forge_session", value: session.token }');
101101 });
test/outbound-sweep.test.ts +1
@@ -68,6 +68,7 @@ const OWN_URL = /canonicalUrl|FORGE_APP_URL|FORGE_URL|forgeUrl|config\.url|ownHo
6868 * it goes through `outboundFetch` (refused, or answered by the listener with `self`) or says why.
6969 */
7070 const OWN_HOST: Record<string, string> = {
71 "src/actions/pinned.ts": "names its own public URL only as the source a deployed machine clones (#16361); it fetches the cloud API and the deployed forge, never its own host",
7172 "src/maintain/duties/wait_split.ts": "in a cell it reads loopback alone (#14664); outside one it times its own public URL on purpose, the edge being what it measures",
7273 "src/maintain/duties/edge_kept.ts": "in a cell it skips (#15350); outside one it GETs the forge's own public URL on purpose, the edge being what the duty measures (#14663)",
7374 "src/http/server.ts": "the forge's own unix socket; the public URL only names links",
test/own-forge.test.ts added +434
@@ -0,0 +1,434 @@
1 /**
2 * A deployed forge runs its own repository (#16361): the boot names it, the first boot makes it
3 * from the checkout, the claim moves it to the new admin, the crew resolves its conflicts only
4 * when told, and a deploy that names no code deploys this forge's own. No socket: the cloud is a
5 * recorded fetch and the checkout a temporary repository.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import {
14 addAccount,
15 allowWrite,
16 net as cloudNet,
17 } from "../src/actions/cloud.ts";
18 import { addToCrew, createAgent } from "../src/actions/crew.ts";
19 import { deployPinned, net, ownCode } from "../src/actions/pinned.ts";
20 import {
21 convergeConflict,
22 setCrewResolving,
23 } from "../src/actions/upstream_follow.ts";
24 import { bootConfig, servedEnv } from "../src/cloud/machine.ts";
25 import { checkConfig, getPinned } from "../src/core/pinned.ts";
26 import {
27 createRepo,
28 getRepo,
29 getRepoById,
30 updateRepoSettings,
31 } from "../src/core/repos.ts";
32 import { redirectFor } from "../src/core/transfer.ts";
33 import { getFollow, putFollow } from "../src/core/upstream_follow.ts";
34 import { createUser, getUserByName, type User } from "../src/core/users.ts";
35 import { repoDir } from "../src/git/repos.ts";
36 import { storedForgeSource } from "../src/settings/forge_source.ts";
37 import {
38 DEPLOYER_VIA,
39 moveOwnForge,
40 OWN_FORGE_REPO,
41 ownForgeAtBoot,
42 } from "../src/spawn/own_forge.ts";
43 import { gitRun } from "./helpers/git-client.ts";
44 import { quietLogs } from "./helpers/globals.ts";
45 import { seedPlaces } from "./helpers/places-fixture.ts";
46
47 quietLogs();
48
49 const UPSTREAM = "https://deployer.test/alice/forge.git";
50 const COMMIT = "c".repeat(40);
51
52 let dir = "";
53 beforeAll(async () => {
54 dir = await mkdtemp(join(tmpdir(), "forge-own-"));
55 });
56 afterAll(async () => {
57 await rm(dir, { recursive: true, force: true });
58 });
59
60 const booted = () => ({
61 name: "acme",
62 source: UPSTREAM,
63 version: COMMIT,
64 config: {},
65 host: "acme.forge.test",
66 claimHash: "",
67 claimExpires: "",
68 });
69
70 describe("the boot config", () => {
71 test("names the forge's own repository, what it follows, its commit and its keeper; none is a setting", () => {
72 const env = servedEnv(booted());
73 expect(env).toMatchObject({
74 FORGE_REPO: OWN_FORGE_REPO,
75 FORGE_UPSTREAM: UPSTREAM,
76 FORGE_COMMIT: COMMIT,
77 FORGE_RELEASE_KEEPER: "swap",
78 FORGE_SELF_SWAP: "1",
79 });
80 for (const name of [
81 "FORGE_REPO",
82 "FORGE_UPSTREAM",
83 "FORGE_COMMIT",
84 "FORGE_RELEASE_KEEPER",
85 "FORGE_SELF_SWAP",
86 ]) {
87 const r = checkConfig({ [name]: "x" });
88 expect(r.ok ? "" : r.error).toContain("is set by the deploy itself");
89 }
90 // A tag is not a commit: the forge is not told one.
91 expect(
92 servedEnv({ ...booted(), version: "v1.2.3" })["FORGE_COMMIT"],
93 ).toBeUndefined();
94 });
95
96 test("installs the crew before the forge starts, and starts the forge when it cannot", () => {
97 const script = bootConfig(booted(), "/mnt/forge_acme_data");
98 expect(script).toMatch(
99 /^packages:\n(?: {2}- \S+\n)* {2}- nodejs\n {2}- npm\n/m,
100 );
101 const install = script.indexOf(
102 " - npm install -g @anthropic-ai/claude-code || logger",
103 );
104 expect(install).toBeGreaterThan(
105 script.indexOf(`checkout --detach ${COMMIT}`),
106 );
107 expect(install).toBeLessThan(
108 script.indexOf("systemctl enable --now forge.service"),
109 );
110 });
111 });
112
113 /** A machine's checkout: a clone at a commit with history and a tag, its main one commit ahead. */
114 function checkout(name: string): { tree: string; head: string; ahead: string } {
115 const tree = join(dir, name);
116 gitRun(dir, "init", "-q", "-b", "main", tree);
117 const commit = (msg: string) => (
118 gitRun(tree, "commit", "-q", "--allow-empty", "-m", msg),
119 gitRun(tree, "rev-parse", "HEAD")
120 );
121 commit("one");
122 const head = commit("two");
123 gitRun(tree, "tag", "-a", "-m", "release", "v0.1.0");
124 const ahead = commit("three");
125 gitRun(tree, "checkout", "-q", "--detach", head);
126 return { tree, head, ahead };
127 }
128
129 async function freshApp(name: string): Promise<App> {
130 return createApp({ dataDir: join(dir, `${name}-data`), port: 0 });
131 }
132
133 const events = (app: App) =>
134 app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM event").get()!.n;
135
136 describe("first boot and claim", () => {
137 test("first boot makes forge/forge from the checkout and follows the upstream; a second boot changes nothing", async () => {
138 const app = await freshApp("boot");
139 const c = checkout("boot-tree");
140 expect(await ownForgeAtBoot(app, {}, c.tree)).toEqual({
141 ok: true,
142 value: "off",
143 });
144 expect(getRepo(app.db, "forge", "forge")).toBeUndefined();
145
146 expect(
147 await ownForgeAtBoot(app, { FORGE_UPSTREAM: UPSTREAM }, c.tree),
148 ).toEqual({ ok: true, value: "made" });
149 const repo = getRepo(app.db, "forge", "forge")!;
150 const git = repoDir(app.reposRoot, "forge", "forge");
151 // Main is the commit the machine runs, with its history, and the tags came along.
152 expect(gitRun(git, "rev-parse", "refs/heads/main")).toBe(c.head);
153 expect(gitRun(git, "rev-list", "--count", "refs/heads/main")).toBe("2");
154 expect(gitRun(git, "rev-parse", "refs/tags/v0.1.0^{commit}")).toBe(c.head);
155 expect(storedForgeSource(app.db)).toBe(OWN_FORGE_REPO);
156 expect(app.config.forgeRepo).toBe(OWN_FORGE_REPO);
157 expect(getFollow(app.db, repo.id)).toMatchObject({
158 url: UPSTREAM,
159 branch: "main",
160 enabled: true,
161 mode: "take-updates",
162 via: DEPLOYER_VIA,
163 crewResolves: false,
164 });
165
166 const before = {
167 follow: getFollow(app.db, repo.id),
168 refs: gitRun(git, "for-each-ref"),
169 events: events(app),
170 };
171 expect(
172 await ownForgeAtBoot(app, { FORGE_UPSTREAM: UPSTREAM }, c.tree),
173 ).toEqual({ ok: true, value: "kept" });
174 expect({
175 follow: getFollow(app.db, repo.id),
176 refs: gitRun(git, "for-each-ref"),
177 events: events(app),
178 }).toEqual(before);
179 expect(
180 await ownForgeAtBoot(
181 app,
182 { FORGE_UPSTREAM: "http://deployer.test/x.git" },
183 c.tree,
184 ),
185 ).toMatchObject({ ok: false });
186 app.close();
187 });
188
189 test("the claim moves it to the new admin; the setting, the config and the follow name the new path", async () => {
190 const app = await freshApp("claim");
191 const c = checkout("claim-tree");
192 expect(
193 (await ownForgeAtBoot(app, { FORGE_UPSTREAM: UPSTREAM }, c.tree)).ok,
194 ).toBe(true);
195 const id = getRepo(app.db, "forge", "forge")!.id;
196 const made = await createUser(app.db, {
197 origin: "seed",
198 trusted: true,
199 username: "dana",
200 email: "[email protected]",
201 password: "a-good-passphrase",
202 adminIfFirst: true,
203 });
204 if (!made.ok) throw new Error(made.error);
205 const moved = await moveOwnForge(app, made.value);
206 expect(moved.ok && moved.value?.ownerName).toBe("dana");
207 expect(getRepoById(app.db, id)).toMatchObject({
208 ownerName: "dana",
209 name: "forge",
210 });
211 expect(redirectFor(app.db, "forge", "forge")?.id).toBe(id);
212 expect(storedForgeSource(app.db)).toBe("dana/forge");
213 expect(app.config.forgeRepo).toBe("dana/forge");
214 expect(getFollow(app.db, id)).toMatchObject({
215 url: UPSTREAM,
216 mode: "take-updates",
217 byId: made.value.id,
218 via: DEPLOYER_VIA,
219 });
220 expect(
221 gitRun(
222 repoDir(app.reposRoot, "dana", "forge"),
223 "rev-parse",
224 "refs/heads/main",
225 ),
226 ).toBe(c.head);
227 // Once moved, a second claim moves nothing, and a restart reads the moved path and makes nothing.
228 expect(await moveOwnForge(app, made.value)).toEqual({
229 ok: true,
230 value: undefined,
231 });
232 app.config.forgeRepo = OWN_FORGE_REPO;
233 expect(
234 await ownForgeAtBoot(app, { FORGE_UPSTREAM: UPSTREAM }, c.tree),
235 ).toEqual({ ok: true, value: "kept" });
236 expect(app.config.forgeRepo).toBe("dana/forge");
237 expect(getRepo(app.db, "forge", "forge")).toBeUndefined();
238 app.close();
239 });
240
241 test("a forge with no deployed repository moves nothing at its claim", async () => {
242 const app = await freshApp("plain");
243 const made = await createUser(app.db, {
244 origin: "seed",
245 trusted: true,
246 username: "eve",
247 email: "[email protected]",
248 password: "a-good-passphrase",
249 adminIfFirst: true,
250 });
251 if (!made.ok) throw new Error(made.error);
252 expect(await moveOwnForge(app, made.value)).toEqual({
253 ok: true,
254 value: undefined,
255 });
256 app.close();
257 });
258 });
259
260 describe("the crew resolves upstream conflicts only when told", () => {
261 test("off, even with autonomy on, the issue is opened and nobody is assigned; on, a builder takes it", async () => {
262 const app = await freshApp("crew");
263 const made = await createUser(app.db, {
264 origin: "seed",
265 trusted: true,
266 username: "ann",
267 email: "[email protected]",
268 password: "a-good-passphrase",
269 adminIfFirst: true,
270 });
271 if (!made.ok) throw new Error(made.error);
272 const ann: User = made.value;
273 const created = await createRepo(app.db, app.reposRoot, {
274 ownerId: ann.id,
275 name: "yard",
276 });
277 if (!created.ok) throw new Error(created.error);
278 const repo = created.value;
279 putFollow(app.db, {
280 repoId: repo.id,
281 url: UPSTREAM,
282 branch: "main",
283 enabled: true,
284 byId: ann.id,
285 originId: "",
286 });
287 updateRepoSettings(app.db, repo, {
288 autonomy: "assisted",
289 autonomyBy: ann.id,
290 });
291 const bot = await createAgent(app, ann, {
292 username: "bot",
293 brief: "Be brief.",
294 });
295 expect(bot.ok).toBe(true);
296 expect(addToCrew(app, ann, repo, "bot").ok).toBe(true);
297 const follow = { url: UPSTREAM, branch: "main" };
298
299 const off = convergeConflict(app, repo, ann, follow, "1".repeat(40), [
300 "src/a.ts",
301 ]);
302 expect(off?.agent).toBeUndefined();
303 expect(off?.issue.body).toContain("src/a.ts");
304 expect(off?.issue.assigneeId).toBeNull();
305
306 // Only an admin may turn it on; then the same conflict, a new head, goes to the builder.
307 expect(setCrewResolving(app, undefined, repo, true)).toEqual({
308 ok: false,
309 error: "not_found",
310 });
311 expect(setCrewResolving(app, ann, repo, true).ok).toBe(true);
312 const on = convergeConflict(
313 app,
314 getRepoById(app.db, repo.id)!,
315 ann,
316 follow,
317 "2".repeat(40),
318 ["src/a.ts"],
319 );
320 expect(on?.agent?.user.username).toBe("bot");
321 expect(on?.issue.id).toBe(off?.issue.id);
322 expect(getUserByName(app.db, "bot")?.id).toBe(on?.issue.assigneeId ?? "");
323 app.close();
324 });
325 });
326
327 describe("a deploy that names no code", () => {
328 let app: App;
329 let alice: User;
330 let userData = "";
331
332 beforeAll(async () => {
333 app = createApp({
334 dataDir: join(dir, "deploy-data"),
335 port: 0,
336 url: "https://deployer.test",
337 forgeRepo: "alice/forge",
338 });
339 await seedPlaces(app.db);
340 const made = await createUser(app.db, {
341 origin: "seed",
342 trusted: true,
343 username: "alice",
344 email: "[email protected]",
345 password: "a-good-passphrase",
346 adminIfFirst: true,
347 });
348 if (!made.ok) throw new Error(made.error);
349 alice = made.value;
350 const repo = await createRepo(app.db, app.reposRoot, {
351 ownerId: alice.id,
352 name: "forge",
353 visibility: "public",
354 });
355 if (!repo.ok) throw new Error(repo.error);
356 cloudNet.fetch = async () =>
357 new Response(
358 JSON.stringify({ account: { email: "[email protected]", status: "active" } }),
359 { status: 200 },
360 );
361 const added = await addAccount(
362 app,
363 alice,
364 "digitalocean",
365 "main",
366 "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5",
367 );
368 if (!added.ok) throw new Error(String(added.error));
369 allowWrite(app, alice, "digitalocean", "main", true);
370 net.resolve = async () => [];
371 net.fetch = async (url, init) => {
372 const u = new URL(url);
373 const body = init?.body ? JSON.parse(String(init.body)) : undefined;
374 if (typeof body?.user_data === "string") userData = body.user_data;
375 if (u.pathname === "/v2/account/keys" && init?.method === "POST")
376 return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), {
377 status: 201,
378 });
379 if (u.pathname === "/v2/volumes")
380 return new Response(JSON.stringify({ volume: { id: "vol-1" } }), {
381 status: 201,
382 });
383 if (init?.method === "DELETE") return new Response(null, { status: 204 });
384 return new Response(JSON.stringify({ droplet: { id: 1001 } }), {
385 status: 202,
386 });
387 };
388 });
389 afterAll(() => app.close());
390
391 test("runs this forge's own repository at the commit this forge runs", async () => {
392 const was = process.env["FORGE_COMMIT"];
393 process.env["FORGE_COMMIT"] = COMMIT;
394 try {
395 expect(ownCode(app, {})).toEqual({
396 ok: true,
397 value: { source: UPSTREAM, version: COMMIT },
398 });
399 // Named code is kept as named.
400 expect(
401 ownCode(app, {
402 source: "https://elsewhere.test/o/r.git",
403 version: "v1.0.0",
404 }),
405 ).toEqual({
406 ok: true,
407 value: { source: "https://elsewhere.test/o/r.git", version: "v1.0.0" },
408 });
409 const r = await deployPinned(app, alice, {
410 name: "acme",
411 host: "acme.forge.test",
412 target: "digitalocean",
413 account: "main",
414 app: "alice/shop",
415 source: "",
416 version: "",
417 });
418 expect(r.ok).toBe(true);
419 expect(getPinned(app.db, "acme")).toMatchObject({
420 source: UPSTREAM,
421 version: COMMIT,
422 });
423 expect(userData).toContain(`git clone ${UPSTREAM} /opt/forge`);
424 expect(userData).toContain(`FORGE_UPSTREAM=${UPSTREAM}`);
425 } finally {
426 if (was === undefined) delete process.env["FORGE_COMMIT"];
427 else process.env["FORGE_COMMIT"] = was;
428 }
429 // A forge that does not know its full commit, or whose code is private, says so.
430 delete process.env["FORGE_COMMIT"];
431 expect(ownCode(app, {})).toMatchObject({ ok: false });
432 if (was !== undefined) process.env["FORGE_COMMIT"] = was;
433 });
434 });
test/pinned-claim.test.ts +1 −1
@@ -1104,7 +1104,7 @@ describe("the name and the boot config", () => {
11041104 test("the forge listens on loopback behind a proxy that serves its one name; config cannot say otherwise", () => {
11051105 const MOUNT = "/mnt/forge_acme_data";
11061106 expect(proxyConfig(booted({ config: { PORT: "8080" } }), MOUNT)).toBe(
1107 `{\n\tstorage file_system ${MOUNT}/caddy\n}\n${HOST} {\n\treverse_proxy 127.0.0.1:8080\n}\n`,
1107 `{\n\tstorage file_system ${MOUNT}/caddy\n\ton_demand_tls {\n\t\task http://127.0.0.1:8080/__forge/domains/ask\n\t}\n}\n${HOST} {\n\treverse_proxy 127.0.0.1:8080\n}\n*.${HOST} {\n\ttls {\n\t\ton_demand\n\t}\n\treverse_proxy 127.0.0.1:8080\n}\n`,
11081108 );
11091109 expect(proxyConfig(booted(), MOUNT)).toContain(
11101110 "reverse_proxy 127.0.0.1:3000",
test/pinned-dns.test.ts +11 −3
@@ -238,6 +238,14 @@ describe("a deploy needs no DNS work from its buyer", () => {
238238 proxied: false,
239239 ttl: 60,
240240 });
241 // The apps' names ride beside it: `*.<host>` at the same address, the same way.
242 expect(named("*.acme.forges.test")).toHaveLength(1);
243 expect(named("*.acme.forges.test")[0]).toMatchObject({
244 type: "A",
245 content: p.address,
246 proxied: false,
247 ttl: 60,
248 });
241249 // The token travels in the Authorization header alone, to the fixed host, and every call is audited.
242250 expect(cf.every((c) => c.auth === `Bearer ${CF_TOKEN}`)).toBe(true);
243251 expect(JSON.stringify(cf.map((c) => [c.path, c.body]))).not.toContain(
@@ -303,7 +311,7 @@ describe("a deploy needs no DNS work from its buyer", () => {
303311 proxied: false,
304312 ttl: 60,
305313 });
306 expect(writes().map((c) => c.method)).toEqual(["PATCH"]);
314 expect(writes().map((c) => c.method)).toEqual(["PATCH", "PATCH"]);
307315 expect(r.ok && r.value.dnsWrittenBy).toBe("cloudflare/main");
308316 });
309317
@@ -314,7 +322,7 @@ describe("a deploy needs no DNS work from its buyer", () => {
314322 const p = getPinned(app.db, "acme")!;
315323 expect(named("acme.forges.test")).toHaveLength(1);
316324 expect(named("acme.forges.test")[0]!.content).toBe(p.address);
317 expect(writes().map((c) => c.method)).toEqual(["PATCH"]);
325 expect(writes().map((c) => c.method)).toEqual(["PATCH", "PATCH"]);
318326 });
319327
320328 test("Check says the record is the forge's own, and asking again writes nothing", async () => {
@@ -348,7 +356,7 @@ describe("a deploy needs no DNS work from its buyer", () => {
348356 proxied: false,
349357 ttl: 60,
350358 });
351 expect(writes().map((c) => c.method)).toEqual(["PATCH"]);
359 expect(writes().map((c) => c.method)).toEqual(["PATCH", "POST"]);
352360 });
353361
354362 test("a token that cannot edit the zone falls back to naming the record, on the deploy and on Check", async () => {
test/pinned-harden.test.ts +3 −1
@@ -58,6 +58,8 @@ describe.each(Object.entries(boots))("the %s machine", (_name, boot) => {
5858 expect(unit).toContain("User=forge\n");
5959 expect(unit).toContain("Group=forge\n");
6060 expect(unit).toContain("ExecStart=/opt/bun/bin/bun run src/main.ts");
61 // The apps the forge starts find Bun on the unit's own path.
62 expect(unit).toContain("Environment=PATH=/opt/bun/bin:/usr/local/bin:/usr/bin:/bin");
6163 expect(boot()).not.toContain("/root");
6264 expect(
6365 doc.runcmd.some(
@@ -134,7 +136,7 @@ describe.each(Object.entries(boots))("the %s machine", (_name, boot) => {
134136 const dir = /^FORGE_DATA=(\/mnt\/\S+)$/m.exec(file(doc, "/etc/forge/env"))![1]!;
135137 // Its config is where the package reads it before the package exists, so its first start is
136138 // on this and never on a welcome page; nothing copies a config in afterwards.
137 expect(file(doc, "/etc/caddy/Caddyfile")).toBe(`{\n\tstorage file_system ${dir}/caddy\n}\nacme.forge.test {\n\treverse_proxy 127.0.0.1:3000\n}\n`);
139 expect(file(doc, "/etc/caddy/Caddyfile")).toBe(`{\n\tstorage file_system ${dir}/caddy\n\ton_demand_tls {\n\t\task http://127.0.0.1:3000/__forge/domains/ask\n\t}\n}\nacme.forge.test {\n\treverse_proxy 127.0.0.1:3000\n}\n*.acme.forge.test {\n\ttls {\n\t\ton_demand\n\t}\n\treverse_proxy 127.0.0.1:3000\n}\n`);
138140 expect(doc.write_files.filter((f) => f.path.endsWith("Caddyfile"))).toHaveLength(1);
139141 expect(doc.runcmd.some((c) => c.includes("Caddyfile"))).toBe(false);
140142 // Its certificates live on the data volume, the proxy's own, so a replaced machine reuses them:
test/pinned-retire.test.ts +1 −1
@@ -195,7 +195,7 @@ describe("retiring a pinned forge", () => {
195195 test("retire deletes the machine and the record the forge wrote, keeps the volume, and says what keeping it costs", async () => {
196196 expect((await deployPinned(app, admin(), input("keeper"))).ok).toBe(true);
197197 const was = getPinned(app.db, "keeper")!;
198 expect(records.map((r) => r.name)).toEqual(["keeper.forges.test"]);
198 expect(records.map((r) => r.name)).toEqual(["keeper.forges.test", "*.keeper.forges.test"]);
199199 expect(monthly("digitalocean")).toBe(1300);
200200 calls.length = 0;
201201 const r = await retirePinned(app, admin(), "keeper");
test/upstream_follow.test.ts +13 −8
@@ -38,6 +38,7 @@ import {
3838 listFollowing,
3939 noteCheck,
4040 putFollow,
41 setCrewResolves,
4142 upstreamUrl,
4243 } from "../src/core/upstream_follow.ts";
4344
@@ -526,18 +527,19 @@ describe("checking an upstream (layer 2)", () => {
526527 }
527528 });
528529
529 /** A conflicting head with a builder on the crew; autonomy as given. */
530 async function clash(name: string, autonomy: "off" | "assisted") {
530 /** A conflicting head with a builder on the crew, autonomy on; the crew resolves as given. */
531 async function clash(name: string, resolves: boolean) {
531532 const t = await staged(name, "ours\n", "theirs\n");
532533 const bot = ok(await createAgent(app, alice, { username: `bot-${name}`, brief: "Be brief." }));
533534 expect(addToCrew(app, alice, getRepoById(app.db, t.r.id)!, `bot-${name}`).ok).toBe(true);
534 updateRepoSettings(app.db, t.r, { autonomy, autonomyBy: alice.id });
535 updateRepoSettings(app.db, t.r, { autonomy: "assisted", autonomyBy: alice.id });
536 expect(setCrewResolves(app.db, t.r.id, resolves)).toBe(true);
535537 const runs = () => listRuns(app.db, t.r.id, { kind: "agent", limit: 50 }).filter((r) => r.reason === "converge");
536538 return { ...t, bot, runs };
537539 }
538540
539541 test("a conflicting head starts one converge run; a second check of it starts none", async () => {
540 const t = await clash("once", "assisted");
542 const t = await clash("once", true);
541543 try {
542544 expect(ok(await checkUpstream(app, t.r)).outcome).toBe("conflict");
543545 expect(t.runs().length).toBe(1);
@@ -581,7 +583,7 @@ describe("checking an upstream (layer 2)", () => {
581583 });
582584
583585 test("the runner picks the upstream brief for an Upstream: issue and strips the summary prefix", async () => {
584 const t = await clash("runner", "assisted");
586 const t = await clash("runner", true);
585587 try {
586588 ok(await checkUpstream(app, t.r));
587589 const repo = getRepoById(app.db, t.r.id)!;
@@ -621,13 +623,16 @@ describe("checking an upstream (layer 2)", () => {
621623 }
622624 });
623625
624 test("with autonomy off the conflict is an issue for people, and no run starts", async () => {
625 const t = await clash("quiet", "off");
626 test("with the crew's resolving off the conflict is an issue for people, even with autonomy on", async () => {
627 const t = await clash("quiet", false);
626628 try {
627629 expect(ok(await checkUpstream(app, t.r)).outcome).toBe("conflict");
628630 expect(getFollow(app.db, t.r.id)!.error).toBe("conflict");
629631 expect(t.runs().length).toBe(0);
630 expect(listIssues(app.db, t.r.id, { state: "all" }).length).toBe(1);
632 const issues = listIssues(app.db, t.r.id, { state: "all" });
633 expect(issues.length).toBe(1);
634 expect(issues[0]!.body).toContain("f.txt");
635 expect(issues[0]!.assigneeId).toBeNull();
631636 } finally {
632637 t.srv.server.stop(true);
633638 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs