diff --git a/scripts/test/provision-adopts-own-repo.ts b/scripts/test/provision-adopts-own-repo.ts new file mode 100644 index 000000000..44651f5a3 --- /dev/null +++ b/scripts/test/provision-adopts-own-repo.ts @@ -0,0 +1,131 @@ +/** + * A provision that GitHub refuses with 422 "name already exists" links the + * repository Loki itself made for that project, and nothing else. + * Run: npx tsx scripts/test/provision-adopts-own-repo.ts + * + * 2026-11-19: Hendlar's provision created bitbaum/hendlar (starter commit and + * all), then Loki restarted before the link was written. Every retry since + * asked GitHub to create it again and got 422, so the project could never + * start. The fix reads the repo back and adopts it — only when it carries the + * exact stamp Loki puts on its own repos, so a hand-made repository of the + * same name is never taken over. + */ +import assert from "node:assert/strict"; +import { + findLokiStartedRepo, + isLokiStartedRepo, + isNameTakenRefusal, + lokiRepoDescription, +} from "../../src/lib/github-provision"; + +const ours = { + name: "hendlar", + owner: { login: "bitbaum" }, + description: "Started from Loki · Hendlar", +}; + +// ---- which refusals are "name taken" ------------------------------------- +assert.equal(isNameTakenRefusal(422, "name already exists on this account"), true); +assert.equal( + isNameTakenRefusal(422, "Repository creation failed."), + false, + "other 422s fail as before", +); +assert.equal(isNameTakenRefusal(403, "name already exists on this account"), false); +assert.equal(isNameTakenRefusal(422, undefined), false); + +// ---- the stamp ------------------------------------------------------------- +assert.equal(lokiRepoDescription("Hendlar"), "Started from Loki · Hendlar"); +assert.equal(isLokiStartedRepo(ours, "Hendlar", "bitbaum"), true); +assert.equal( + isLokiStartedRepo({ ...ours, owner: { login: "BitBaum" } }, "Hendlar", "bitbaum"), + true, +); +assert.equal( + isLokiStartedRepo({ ...ours, description: "my own thing" }, "Hendlar", "bitbaum"), + false, + "a repo a person made by hand is never adopted", +); +assert.equal(isLokiStartedRepo({ ...ours, description: null }, "Hendlar", "bitbaum"), false); +assert.equal( + isLokiStartedRepo({ ...ours, owner: { login: "catomean" } }, "Hendlar", "bitbaum"), + false, + "only the fleet's org", +); +assert.equal( + isLokiStartedRepo(ours, "Hendlar Portal", "bitbaum"), + false, + "the slug must be the one this project would get", +); + +// ---- reading it back (fetch stubbed) ------------------------------------- +const realFetch = globalThis.fetch; +async function withFetch( + answer: (url: string) => Response | Promise, + fn: () => Promise, +): Promise<{ value: T; urls: string[] }> { + const urls: string[] = []; + globalThis.fetch = (async (input: string | URL | Request) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + urls.push(url); + return answer(url); + }) as typeof fetch; + try { + return { value: await fn(), urls }; + } finally { + globalThis.fetch = realFetch; + } +} +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); + +const repoBody = { + id: 1, + name: "hendlar", + full_name: "bitbaum/hendlar", + html_url: "https://github.com/bitbaum/hendlar", + ssh_url: "git@github.com:bitbaum/hendlar.git", + clone_url: "https://github.com/bitbaum/hendlar.git", + private: true, + owner: { login: "bitbaum" }, + description: "Started from Loki · Hendlar", +}; + +(async () => { + { + const { value, urls } = await withFetch( + () => json(repoBody), + () => findLokiStartedRepo("t", "Hendlar"), + ); + assert.equal(value?.full_name, "bitbaum/hendlar"); + assert.equal(urls.length, 1); + assert.match(urls[0]!, /\/repos\/bitbaum\/hendlar$/); + } + { + const { value } = await withFetch( + () => json({ ...repoBody, description: "hand made" }), + () => findLokiStartedRepo("t", "Hendlar"), + ); + assert.equal(value, null, "not stamped by Loki → not adopted"); + } + { + const { value } = await withFetch( + () => json({ message: "Not Found" }, 404), + () => findLokiStartedRepo("t", "Hendlar"), + ); + assert.equal(value, null); + } + { + const { value } = await withFetch( + () => { + throw new Error("network down"); + }, + () => findLokiStartedRepo("t", "Hendlar"), + ); + assert.equal(value, null, "unknown is never adoption"); + } + console.log("provision-adopts-own-repo: ok"); +})().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/src/lib/github-provision.ts b/src/lib/github-provision.ts index 032cbdde1..d4e056420 100644 --- a/src/lib/github-provision.ts +++ b/src/lib/github-provision.ts @@ -172,6 +172,64 @@ export type ProvisionResult = | { ok: true; repo: ProvisionedRepo; templateSeeded: boolean } | { ok: false; status: number; error: string; detail?: string }; +/** The description Loki stamps on every repository it creates for a project. */ +export function lokiRepoDescription(projectName: string): string { + return `Started from Loki · ${projectName}`; +} + +/** GitHub's answer when the org already has a repository by that name. */ +export function isNameTakenRefusal(status: number, detail: string | undefined): boolean { + return status === 422 && /already exists/i.test(detail ?? ""); +} + +/** + * Pure: is this existing repository one Loki itself created for a project of + * this name? It must sit in the fleet's organisation, under the exact slug + * Loki would have used, and carry the description Loki stamps at create time. + * Anything else — a person's hand-made repo, another name — is not ours to take. + */ +export function isLokiStartedRepo( + repo: Pick & { description?: string | null }, + projectName: string, + owner: string = GITHUB_REPO_OWNER, +): boolean { + return ( + repo.owner.login.toLowerCase() === owner.toLowerCase() && + repo.name.toLowerCase() === repoSlug(projectName) && + (repo.description ?? "") === lokiRepoDescription(projectName) + ); +} + +/** + * After a 422 "name already exists": the repository a previous provision of + * this same project created, or null. A create that succeeded on GitHub but + * never got linked (Loki restarted mid-step, 2026-11-19, bitbaum/hendlar) + * left the project unable to provision forever; reading the repo back lets + * the caller link it instead. Never throws; unknown is null. + */ +export async function findLokiStartedRepo( + token: string, + projectName: string, +): Promise { + const name = repoSlug(projectName); + if (!name) return null; + try { + const res = await fetch(`${GITHUB_API_BASE}/repos/${GITHUB_REPO_OWNER}/${name}`, { + signal: AbortSignal.timeout(HTTP_TIMEOUT_SHORT_MS), + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }, + }); + if (!res.ok) return null; + const repo = (await res.json()) as ProvisionedRepo & { description?: string | null }; + return isLokiStartedRepo(repo, projectName) ? repo : null; + } catch { + return null; + } +} + /** * The message a person can act on when the org refuses the create. GitHub * answers 404 (not 403) when an OAuth token has no access to an org, so the @@ -214,7 +272,7 @@ export async function provisionGithubRepo( error: "Name must contain at least one alphanumeric character", }; - const description = opts.description ?? `Started from Loki · ${opts.name}`; + const description = opts.description ?? lokiRepoDescription(opts.name); let res: Response; try { res = await fetch(`${GITHUB_API_BASE}/orgs/${GITHUB_REPO_OWNER}/repos`, { diff --git a/src/lib/kickoff/steps.ts b/src/lib/kickoff/steps.ts index 4b1114f1f..f5edd6578 100644 --- a/src/lib/kickoff/steps.ts +++ b/src/lib/kickoff/steps.ts @@ -9,14 +9,22 @@ import { CODE_CUSTODY } from "@/db/schema/user-projects"; import { isRepoCopyProject } from "@/lib/repo-brief"; import { disableGithubActions, + findLokiStartedRepo, + isNameTakenRefusal, + lokiRepoDescription, parseGithubRepoUrl, provisionGithubRepo, repoHasStarterFiles, repoSlug, seedTemplate, + type ProvisionResult, } from "@/lib/github-provision"; import { getProjectCore, patchProject } from "@/db/queries/projects"; -import { getUserProjectByEntityId, updateUserProject } from "@/db/queries/user-projects"; +import { + findProjectByRepo, + getUserProjectByEntityId, + updateUserProject, +} from "@/db/queries/user-projects"; import { fetchAttributesByEntityIds } from "@/db/queries/utils"; import { createGoal } from "@/db/queries/goals"; import { getProjectAccess } from "@/db/queries/project-access"; @@ -340,12 +348,36 @@ export async function provisionStep( ); } - const result = await provisionGithubRepo(token, { + let result: ProvisionResult = await provisionGithubRepo(token, { name: project.name, visibility: input.visibility, template, feedback, }); + // "Name already exists" is often our own earlier create: GitHub made the repo, + // then Loki stopped before linking it (a restart mid-step), and every retry + // since hit this 422. Link that repo instead of failing — but only one Loki + // stamped for a project of this name, and only if no project links it yet. + if (!result.ok && isNameTakenRefusal(result.status, result.detail)) { + const existing = await findLokiStartedRepo(token, project.name); + const claimed = existing ? await findProjectByRepo(existing.full_name) : null; + if (existing && !claimed) { + let templateSeeded = + template === "bare" || + (await repoHasStarterFiles(token, existing.owner.login, existing.name, template)); + if (!templateSeeded) { + templateSeeded = await seedTemplate( + token, + existing.owner.login, + existing.name, + template, + { name: project.name, description: lokiRepoDescription(project.name) }, + feedback, + ); + } + result = { ok: true, repo: existing, templateSeeded }; + } + } if (!result.ok) { return json({ error: result.error, detail: result.detail }, result.status === 422 ? 409 : 502); }