diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index aea78bd..2a6f82a 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -3,10 +3,10 @@ name: sprout preview (reusable) # Thin bootstrapper for GitHub pull-request previews: installs the pinned, # checksum-verified `sprout` binary and calls `sprout ci preview` / # `sprout ci teardown`. All preview behaviour (image build and push, seed -# image, deploy, PR comment, dotenv emission, log dump on failure) lives in -# the CLI. A reset is an ordinary action: run `sprout ci reset` from a -# hand-rolled job or laptop (same env as below) — no ticked box, no marker -# token, no server-side bookkeeping. +# image, deploy, PR comment, dotenv emission, teardown image-tag cleanup, +# log dump on failure) lives in the CLI. A reset is an ordinary action: run +# `sprout ci reset` from a hand-rolled job or laptop (same env as below) — +# no ticked box, no marker token, no server-side bookkeeping. # # Caller (`.github/workflows/sprout.yml` in the adopting repo): # @@ -154,7 +154,6 @@ jobs: - name: Prepare image ref and env blobs id: prep - if: github.event.action != 'closed' env: APP_ENV_BLOB: ${{ secrets.SPROUT_APP_ENV }} SEED_ENV_BLOB: ${{ secrets.SPROUT_SEED_ENV }} @@ -203,6 +202,7 @@ jobs: SPROUT_URL: ${{ secrets.SPROUT_URL }} SPROUT_TOKEN: ${{ secrets.SPROUT_TOKEN }} GITHUB_TOKEN: ${{ github.token }} + GHCR_DELETE_TOKEN: ${{ secrets.REGISTRY_PASSWORD }} run: | set -eu sprout ci teardown diff --git a/apps/cli/src/commands/ci-identity.test.ts b/apps/cli/src/commands/ci-identity.test.ts index 92ee926..780cf9a 100644 --- a/apps/cli/src/commands/ci-identity.test.ts +++ b/apps/cli/src/commands/ci-identity.test.ts @@ -3,6 +3,7 @@ import { requireCiSource, resolveCiIdentity, resolveCiPreviewIdentity, + resolveCiPushedImageRefs, resolveImageRef, } from "./ci-identity.ts"; import type { CliDeps } from "../context.ts"; @@ -437,6 +438,37 @@ describe("resolveCiIdentity", () => { }); }); + test("GitHub locks the pull request head SHA so teardown matches the preview build", async () => { + const event = { + pull_request: { number: 42, head: { sha: "headsha" } }, + }; + expect( + await resolveCiIdentity( + deps( + { + GITHUB_REPOSITORY: "org/repo", + GITHUB_EVENT_NAME: "pull_request", + GITHUB_EVENT_PATH: "/event.json", + GITHUB_SHA: "basesha", + }, + { + readTextFile: async (path) => + path === "/event.json" ? JSON.stringify(event) : null, + }, + ), + ), + ).toEqual({ + ok: true, + value: { + forge: "github", + repo: "https://github.com/org/repo", + prId: 42, + pipelineSource: "pull_request", + commitSha: "headsha", + }, + }); + }); + test("leaves commitSha undefined when the forge's var is missing", async () => { expect( await resolveCiIdentity( @@ -540,3 +572,81 @@ describe("resolveCiPreviewIdentity", () => { }); }); }); + +describe("resolveCiPushedImageRefs", () => { + const identity = { + forge: "gitlab" as const, + pipelineSource: "merge_request_event" as const, + repo: "https://gitlab.com/group/repo", + prId: 17, + commitSha: "abc123", + }; + const env = { + CI_REGISTRY_IMAGE: "registry.gitlab.com/group/repo", + CI_COMMIT_SHA: "abc123", + }; + + test("resolves the app ref and the commit-scoped seed ref", async () => { + expect( + await resolveCiPushedImageRefs( + deps( + env, + { + readTextFile: async (path) => + path.endsWith(".sprout.yaml") + ? `slug: myapp +preview: + hostname: "pr-{pr_id}.example.com" +seed: + dockerfile: Dockerfile.seed +` + : null, + }, + ), + identity, + ), + ).toEqual({ + refs: [ + "registry.gitlab.com/group/repo:abc123", + "registry.gitlab.com/group/repo:abc123-seed", + ], + warnings: [], + }); + }); + + test("never treats content-addressed seed tags as cleanup targets", async () => { + const result = await resolveCiPushedImageRefs( + deps( + env, + { + readTextFile: async (path) => { + if (path.endsWith(".sprout.yaml")) { + return `slug: myapp +preview: + hostname: "pr-{pr_id}.example.com" +seed: + dockerfile: Dockerfile.seed + inputs: + - Dockerfile.seed +`; + } + if (path.endsWith("Dockerfile.seed")) return "FROM oven/bun:1\n"; + return null; + }, + }, + ), + identity, + ); + expect(result.warnings).toEqual([]); + expect(result.refs).toEqual(["registry.gitlab.com/group/repo:abc123"]); + }); + + test("skips silently when the commit's image ref cannot be derived", async () => { + expect( + await resolveCiPushedImageRefs( + deps({ CI_COMMIT_SHA: "abc123" }, { readTextFile: async () => null }), + identity, + ), + ).toEqual({ refs: [], warnings: [] }); + }); +}); diff --git a/apps/cli/src/commands/ci-identity.ts b/apps/cli/src/commands/ci-identity.ts index 1bac7fb..27c6ed9 100644 --- a/apps/cli/src/commands/ci-identity.ts +++ b/apps/cli/src/commands/ci-identity.ts @@ -4,10 +4,12 @@ import { commitShaEnvVar, resolveCommitSha, resolvePrId, + resolvePullRequestHeadSha, resolveRepoForForge, } from "../identity.ts"; import { resolveDeployHostname } from "../hostname.ts"; import type { Result } from "../result.ts"; +import { resolveSeedTarget } from "./seed-image.ts"; export type CiSource = | { forge: "gitlab"; pipelineSource: "merge_request_event" } @@ -107,14 +109,16 @@ export async function resolveCiIdentity( if (!repo.ok) return repo; let prId: Result; + let eventPayload: unknown; if (source.value.forge === "gitlab") { prId = resolvePrId({ env: deps.env, forge: "gitlab" }); } else { const event = await loadEventPayload(deps); if (!event.ok) return event; + eventPayload = event.value; prId = resolvePrId({ env: deps.env, - eventPayload: event.value, + eventPayload, forge: "github", }); } @@ -122,13 +126,19 @@ export async function resolveCiIdentity( return prId; } + const commitSha = + source.value.forge === "github" + ? resolvePullRequestHeadSha(eventPayload) ?? + resolveCommitSha(deps.env, "github") + : resolveCommitSha(deps.env, "gitlab"); + return { ok: true, value: { ...source.value, repo: repo.value, prId: prId.value, - commitSha: resolveCommitSha(deps.env, source.value.forge), + commitSha, }, }; } @@ -162,3 +172,43 @@ export async function resolveCiPreviewIdentity( }, }; } + +export type CiPushedImageRefs = { + refs: string[]; + warnings: string[]; +}; + +/** Re-resolves the exact app + per-run seed refs the preview build pushed for this commit. */ +export async function resolveCiPushedImageRefs( + deps: CliDeps, + identity: CiIdentity, +): Promise { + const app = resolveImageRef(deps.env, identity); + if (!app.ok) return { refs: [], warnings: [] }; + + const yaml = await loadYaml(deps); + if (!yaml.ok) { + return { + refs: [app.value], + warnings: [`registry cleanup: seed tag not resolved (${yaml.error})`], + }; + } + if (!yaml.value.seed) return { refs: [app.value], warnings: [] }; + + const seed = await resolveSeedTarget( + yaml.value.seed, + app.value, + deps.cwd, + deps.readTextFile, + ); + if (!seed.ok) { + return { + refs: [app.value], + warnings: [`registry cleanup: seed tag not resolved (${seed.error})`], + }; + } + // Content-addressed seed tags are shared cache across previews, so only the + // commit-scoped seed tag is a per-run artifact this teardown may delete. + if (seed.value.allowReuse) return { refs: [app.value], warnings: [] }; + return { refs: [app.value, seed.value.ref], warnings: [] }; +} diff --git a/apps/cli/src/commands/ci-teardown-reseed-logs.test.ts b/apps/cli/src/commands/ci-teardown-reseed-logs.test.ts index 57e4dbe..a6b0744 100644 --- a/apps/cli/src/commands/ci-teardown-reseed-logs.test.ts +++ b/apps/cli/src/commands/ci-teardown-reseed-logs.test.ts @@ -105,7 +105,9 @@ describe("sprout ci teardown", () => { }), ); expect(code).toBe(0); - expect(stderr).toEqual([]); + expect(stderr).toEqual([ + "warning: registry tag cleanup skipped: no GitLab token available (set GITLAB_TOKEN with api scope, or run in a CI job with CI_JOB_TOKEN)", + ]); expect(captured).toEqual([ { method: "POST", @@ -130,7 +132,9 @@ describe("sprout ci teardown", () => { }), ); expect(code).toBe(0); - expect(stderr).toEqual([]); + expect(stderr).toEqual([ + "warning: registry tag cleanup skipped: no GitLab token available (set GITLAB_TOKEN with api scope, or run in a CI job with CI_JOB_TOKEN)", + ]); }); test("surfaces the gateway error code on failure", async () => { diff --git a/apps/cli/src/commands/ci-teardown-tags.test.ts b/apps/cli/src/commands/ci-teardown-tags.test.ts new file mode 100644 index 0000000..dfcd06a --- /dev/null +++ b/apps/cli/src/commands/ci-teardown-tags.test.ts @@ -0,0 +1,388 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { createApiClient } from "@sprout/api-client"; +import { runCli, type CliDeps } from "../run.ts"; +import { parseImageRef } from "./image-cleanup.ts"; + +type FetchCall = { + url: string; + method: string; + headers: Record; +}; + +let server: ReturnType | undefined; +let stdout: string[] = []; +let stderr: string[] = []; + +afterEach(() => { + server?.stop(true); + server = undefined; + stdout = []; + stderr = []; +}); + +const YAML = `slug: myapp +preview: + hostname: "pr-{pr_id}.myapp.preview.example.com" +seed: + dockerfile: Dockerfile.seed +`; + +function startGateway(): string { + server = Bun.serve({ + port: 0, + fetch() { + return Response.json({ ok: true, status: "removed" }); + }, + }); + return `http://127.0.0.1:${server.port}`; +} + +function deps( + env: NodeJS.ProcessEnv, + fetchFn: (url: string, init?: RequestInit) => Promise, +): CliDeps { + return { + cwd: "/", + readTextFile: async (path) => (path.endsWith(".sprout.yaml") ? YAML : null), + getGitRemoteUrl: () => null, + createClient: (baseUrl, token) => + createApiClient(baseUrl, { + headers: token ? { Authorization: `Bearer ${token}` } : undefined, + }), + fetchFn, + io: { + stdout: (line) => stdout.push(line), + stderr: (line) => stderr.push(line), + }, + env, + }; +} + +function headersOf(init?: RequestInit): Record { + return Object.fromEntries(new Headers(init?.headers).entries()); +} + +const GITLAB_ENV: NodeJS.ProcessEnv = { + SPROUT_TOKEN: "t", + CI_PROJECT_URL: "https://gitlab.com/group/repo", + CI_PROJECT_ID: "99", + CI_MERGE_REQUEST_IID: "17", + CI_PIPELINE_SOURCE: "merge_request_event", + CI_JOB_TOKEN: "job-token", + CI_REGISTRY_IMAGE: "registry.gitlab.com/group/repo", + CI_COMMIT_SHA: "abc123", +}; + +function gitlabFetch( + calls: FetchCall[], + deleteStatus: (url: string) => number = () => 204, +) { + return async (url: string, init?: RequestInit) => { + const method = init?.method ?? "GET"; + calls.push({ url, method, headers: headersOf(init) }); + if (url.includes("/registry/repositories?")) { + return Response.json([{ id: 5, path: "group/repo" }]); + } + if (url.includes("/merge_requests/")) { + if (method === "GET") return Response.json([]); + return Response.json({ id: 1 }); + } + if (method === "DELETE" && url.includes("/registry/repositories/5/tags/")) { + return new Response(null, { status: deleteStatus(url) }); + } + return new Response("not found", { status: 404 }); + }; +} + +describe("ci teardown image tags", () => { + test("deletes the app and seed tags pushed for the commit", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const code = await runCli( + ["ci", "teardown"], + deps( + { ...GITLAB_ENV, SPROUT_URL: baseUrl }, + gitlabFetch(calls), + ), + ); + + expect(code).toBe(0); + expect(stderr).toEqual([]); + const deletes = calls.filter((call) => call.method === "DELETE"); + expect(deletes.map((call) => call.url)).toEqual([ + "https://gitlab.com/api/v4/projects/99/registry/repositories/5/tags/abc123", + "https://gitlab.com/api/v4/projects/99/registry/repositories/5/tags/abc123-seed", + ]); + expect(deletes[0]?.headers["job-token"]).toBe("job-token"); + }); + + test("already-deleted tags warn and still exit 0", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const code = await runCli( + ["ci", "teardown"], + deps( + { ...GITLAB_ENV, SPROUT_URL: baseUrl }, + gitlabFetch(calls, () => 404), + ), + ); + + expect(code).toBe(0); + expect(stderr).toEqual([ + "warning: registry tag already absent: registry.gitlab.com/group/repo:abc123", + "warning: registry tag already absent: registry.gitlab.com/group/repo:abc123-seed", + ]); + }); + + test("a failed delete is a warning, never a teardown failure", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const code = await runCli( + ["ci", "teardown"], + deps( + { ...GITLAB_ENV, SPROUT_URL: baseUrl }, + gitlabFetch(calls, () => 500), + ), + ); + + expect(code).toBe(0); + expect(stderr).toHaveLength(2); + expect(stderr[0]).toContain("warning: registry tag delete failed"); + expect(stderr[0]).toContain("500"); + }); + + test("missing delete permission warns once with the missing scope", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const code = await runCli( + ["ci", "teardown"], + deps( + { ...GITLAB_ENV, SPROUT_URL: baseUrl }, + gitlabFetch(calls, () => 403), + ), + ); + + expect(code).toBe(0); + expect(stderr).toHaveLength(1); + expect(stderr[0]).toContain("warning: registry tag delete is not authorized"); + expect(stderr[0]).toContain("api"); + }); + + test("gateway failure skips registry cleanup", async () => { + const calls: FetchCall[] = []; + server = Bun.serve({ + port: 0, + fetch() { + return Response.json({ error: "boom" }, { status: 500 }); + }, + }); + const code = await runCli( + ["ci", "teardown"], + deps( + { + ...GITLAB_ENV, + SPROUT_URL: `http://127.0.0.1:${server.port}`, + }, + gitlabFetch(calls), + ), + ); + + expect(code).toBe(1); + expect(stderr).toEqual(["500 boom"]); + expect(calls).toEqual([]); + }); + + test("GHCR teardown deletes package versions carrying the SHA tags", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const fetchFn = async (url: string, init?: RequestInit) => { + const method = init?.method ?? "GET"; + calls.push({ url, method, headers: headersOf(init) }); + if (url.includes("/issues/42/comments")) { + if (method === "GET") return Response.json([]); + return Response.json({ id: 1 }); + } + if (url === "https://api.github.com/users/org") { + return Response.json({ type: "Organization" }); + } + if ( + method === "GET" && + url.includes("/orgs/org/packages/container/repo/versions") + ) { + return Response.json([ + { + id: 11, + metadata: { container: { tags: ["def456"] } }, + }, + { + id: 12, + metadata: { container: { tags: ["def456-seed"] } }, + }, + ]); + } + if (method === "DELETE" && url.includes("/versions/")) { + return new Response(null, { status: 204 }); + } + return new Response("not found", { status: 404 }); + }; + + const code = await runCli( + ["ci", "teardown"], + deps( + { + SPROUT_URL: baseUrl, + SPROUT_TOKEN: "t", + GITHUB_EVENT_NAME: "pull_request", + GITHUB_REF: "refs/pull/42/merge", + GITHUB_REPOSITORY: "org/repo", + GITHUB_SHA: "def456", + GITHUB_TOKEN: "gh-token", + CI_REGISTRY_IMAGE: "ghcr.io/org/repo", + }, + fetchFn, + ), + ); + + expect(code).toBe(0); + expect(stderr).toEqual([]); + const deletes = calls.filter((call) => call.method === "DELETE"); + expect(deletes.map((call) => call.url)).toEqual([ + "https://api.github.com/orgs/org/packages/container/repo/versions/11", + "https://api.github.com/orgs/org/packages/container/repo/versions/12", + ]); + expect(deletes[0]?.headers.authorization).toBe("Bearer gh-token"); + }); + + test("GHCR retries a refused delete with the job token", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const fetchFn = async (url: string, init?: RequestInit) => { + const method = init?.method ?? "GET"; + const headers = headersOf(init); + calls.push({ url, method, headers }); + if (url.includes("/issues/42/comments")) { + if (method === "GET") return Response.json([]); + return Response.json({ id: 1 }); + } + if (url === "https://api.github.com/users/org") { + return Response.json({ type: "Organization" }); + } + if ( + method === "GET" && + url.includes("/orgs/org/packages/container/repo/versions") + ) { + return Response.json([ + { id: 11, metadata: { container: { tags: ["def456"] } } }, + { id: 12, metadata: { container: { tags: ["def456-seed"] } } }, + ]); + } + if (method === "DELETE") { + return new Response(null, { + status: + headers.authorization === "Bearer delete-token" ? 403 : 204, + }); + } + return new Response("not found", { status: 404 }); + }; + + const code = await runCli( + ["ci", "teardown"], + deps( + { + SPROUT_URL: baseUrl, + SPROUT_TOKEN: "t", + GITHUB_EVENT_NAME: "pull_request", + GITHUB_REF: "refs/pull/42/merge", + GITHUB_REPOSITORY: "org/repo", + GITHUB_SHA: "def456", + GITHUB_TOKEN: "gh-token", + GHCR_DELETE_TOKEN: "delete-token", + CI_REGISTRY_IMAGE: "ghcr.io/org/repo", + }, + fetchFn, + ), + ); + + expect(code).toBe(0); + expect(stderr).toEqual([]); + const deletes = calls.filter((call) => call.method === "DELETE"); + expect(deletes.map((call) => call.headers.authorization)).toEqual([ + "Bearer delete-token", + "Bearer gh-token", + "Bearer delete-token", + "Bearer gh-token", + ]); + }); + + test("GHCR missing delete permission names delete:packages once", async () => { + const calls: FetchCall[] = []; + const baseUrl = startGateway(); + const fetchFn = async (url: string, init?: RequestInit) => { + const method = init?.method ?? "GET"; + calls.push({ url, method, headers: headersOf(init) }); + if (url.includes("/issues/42/comments")) { + if (method === "GET") return Response.json([]); + return Response.json({ id: 1 }); + } + if (url === "https://api.github.com/users/org") { + return Response.json({ type: "Organization" }); + } + if ( + method === "GET" && + url.includes("/orgs/org/packages/container/repo/versions") + ) { + return Response.json([ + { id: 11, metadata: { container: { tags: ["def456"] } } }, + { id: 12, metadata: { container: { tags: ["def456-seed"] } } }, + ]); + } + if (method === "DELETE") return new Response(null, { status: 403 }); + return new Response("not found", { status: 404 }); + }; + + const code = await runCli( + ["ci", "teardown"], + deps( + { + SPROUT_URL: baseUrl, + SPROUT_TOKEN: "t", + GITHUB_EVENT_NAME: "pull_request", + GITHUB_REF: "refs/pull/42/merge", + GITHUB_REPOSITORY: "org/repo", + GITHUB_SHA: "def456", + GITHUB_TOKEN: "gh-token", + CI_REGISTRY_IMAGE: "ghcr.io/org/repo", + }, + fetchFn, + ), + ); + + expect(code).toBe(0); + expect(stderr).toHaveLength(1); + expect(stderr[0]).toContain("warning: registry tag delete is not authorized"); + expect(stderr[0]).toContain("delete:packages"); + }); +}); + +describe("parseImageRef", () => { + test("splits registry, repository, and tag", () => { + expect(parseImageRef("registry.gitlab.com/group/repo:abc123")).toEqual({ + registry: "registry.gitlab.com", + repository: "group/repo", + tag: "abc123", + }); + }); + + test("keeps a registry port", () => { + expect(parseImageRef("localhost:5000/app:sha")).toEqual({ + registry: "localhost:5000", + repository: "app", + tag: "sha", + }); + }); + + test("rejects a ref without a tag or registry host", () => { + expect(parseImageRef("registry/app")).toBeNull(); + expect(parseImageRef("org/app:sha")).toBeNull(); + }); +}); diff --git a/apps/cli/src/commands/ci-teardown.ts b/apps/cli/src/commands/ci-teardown.ts index 1cad161..06ccaf8 100644 --- a/apps/cli/src/commands/ci-teardown.ts +++ b/apps/cli/src/commands/ci-teardown.ts @@ -1,8 +1,12 @@ import type { CliContext } from "../context.ts"; import { fail } from "../context.ts"; import { parseFlags } from "../flags.ts"; -import type { CiIdentity } from "./ci-identity.ts"; +import { + resolveCiPushedImageRefs, + type CiIdentity, +} from "./ci-identity.ts"; import { publishTeardownNote, warnForgeNote } from "./forge-note.ts"; +import { cleanupPushedImageRefs } from "./image-cleanup.ts"; import { teardownPreview } from "./teardown.ts"; /** Idempotent: the gateway reports `removed` when no preview exists. */ @@ -22,6 +26,25 @@ export async function runCiTeardown( const result = await teardownPreview(ctx.client, identity); if (!result.ok) return fail(ctx.deps.io, result.error); + + try { + const images = await resolveCiPushedImageRefs(ctx.deps, identity); + for (const warning of images.warnings) { + ctx.deps.io.stderr(`warning: ${warning}`); + } + const cleanup = await cleanupPushedImageRefs( + ctx.deps, + identity, + images.refs, + ); + for (const warning of cleanup.warnings) { + ctx.deps.io.stderr(`warning: ${warning}`); + } + } catch (err) { + const detail = err instanceof Error ? err.message : String(err); + ctx.deps.io.stderr(`warning: registry tag cleanup skipped: ${detail}`); + } + warnForgeNote(ctx.deps.io, await publishTeardownNote(ctx.deps, identity)); return 0; } diff --git a/apps/cli/src/commands/image-cleanup.ts b/apps/cli/src/commands/image-cleanup.ts new file mode 100644 index 0000000..8e33257 --- /dev/null +++ b/apps/cli/src/commands/image-cleanup.ts @@ -0,0 +1,606 @@ +import type { CliDeps } from "../context.ts"; +import type { CiIdentity } from "./ci-identity.ts"; +import type { Result } from "../result.ts"; + +export type ParsedImageRef = { + registry: string; + repository: string; + tag: string; +}; + +export type ImageCleanupReport = { + deleted: string[]; + warnings: string[]; +}; + +const MAX_GITLAB_REPOSITORIES_PAGES = 10; +const MAX_GHCR_VERSION_PAGES = 100; + +function fetchFor(deps: CliDeps): (url: string, init?: RequestInit) => Promise { + return deps.fetchFn ?? globalThis.fetch; +} + +function stripTrailingSlash(url: string): string { + return url.replace(/\/+$/, ""); +} + +export function parseImageRef(ref: string): ParsedImageRef | null { + const trimmed = ref.trim(); + const slash = trimmed.lastIndexOf("/"); + const colon = trimmed.lastIndexOf(":"); + if (slash <= 0 || colon <= slash || colon === trimmed.length - 1) return null; + + const name = trimmed.slice(0, colon); + const tag = trimmed.slice(colon + 1); + const hostEnd = name.indexOf("/"); + if (hostEnd <= 0) return null; + const registry = name.slice(0, hostEnd); + if ( + !registry.includes(".") && + !registry.includes(":") && + registry !== "localhost" + ) { + return null; + } + const repository = name.slice(hostEnd + 1); + if (!repository || tag.includes("/")) return null; + return { registry, repository, tag }; +} + +async function readErrorBody(res: Response): Promise { + try { + const text = (await res.text()).trim(); + return text ? text.slice(0, 300) : res.statusText || "unknown error"; + } catch { + return res.statusText || "unknown error"; + } +} + +function unauthorizedStatus(status: number): boolean { + return status === 401 || status === 403; +} + +function unauthorizedDetail(detail: string): boolean { + return /\b(401|403)\b/.test(detail); +} + +type GitlabTarget = { + api: string; + project: string; + token: string; + tokenHeader: "JOB-TOKEN" | "PRIVATE-TOKEN"; +}; + +function resolveGitlabTarget(env: NodeJS.ProcessEnv): Result { + const pat = env.GITLAB_TOKEN?.trim(); + const jobToken = env.CI_JOB_TOKEN?.trim(); + const token = pat || jobToken; + if (!token) { + return { + ok: false, + error: + "no GitLab token available (set GITLAB_TOKEN with api scope, or run in a CI job with CI_JOB_TOKEN)", + }; + } + + const server = env.CI_SERVER_URL?.trim(); + const api = stripTrailingSlash( + env.CI_API_V4_URL?.trim() || + (server ? `${stripTrailingSlash(server)}/api/v4` : "https://gitlab.com/api/v4"), + ); + + const projectId = env.CI_PROJECT_ID?.trim(); + const projectPath = env.CI_PROJECT_PATH?.trim(); + if (!projectId && !projectPath) { + return { + ok: false, + error: + "cannot resolve GitLab project (set CI_PROJECT_ID or CI_PROJECT_PATH)", + }; + } + + return { + ok: true, + value: { + api, + project: projectId || encodeURIComponent(projectPath!), + token, + tokenHeader: pat ? "PRIVATE-TOKEN" : "JOB-TOKEN", + }, + }; +} + +function gitlabHeaders(target: GitlabTarget): Record { + return { [target.tokenHeader]: target.token }; +} + +async function listGitlabRepositories( + doFetch: (url: string, init?: RequestInit) => Promise, + target: GitlabTarget, +): Promise>> { + const repositories = new Map(); + for (let page = 1; page <= MAX_GITLAB_REPOSITORIES_PAGES; page++) { + let res: Response; + try { + res = await doFetch( + `${target.api}/projects/${target.project}/registry/repositories?per_page=100&page=${page}`, + { method: "GET", headers: gitlabHeaders(target) }, + ); + } catch (err) { + const detail = err instanceof Error ? err.message : String(err); + return { ok: false, error: `registry repository list failed: ${detail}` }; + } + if (!res.ok) { + const body = await readErrorBody(res); + if (unauthorizedStatus(res.status)) { + return { + ok: false, + error: `registry repository list unauthorized: ${res.status} ${body}`, + }; + } + return { + ok: false, + error: `registry repository list failed: ${res.status} ${body}`, + }; + } + + let data: unknown; + try { + data = await res.json(); + } catch { + return { ok: false, error: "registry repository list returned invalid JSON" }; + } + if (!Array.isArray(data)) { + return { ok: false, error: "registry repository list returned invalid JSON" }; + } + + for (const item of data) { + if (typeof item !== "object" || item === null) continue; + const record = item as { id?: unknown; path?: unknown }; + if (typeof record.id === "number" && typeof record.path === "string") { + repositories.set(record.path.toLowerCase(), record.id); + } + } + if (data.length < 100) break; + } + return { ok: true, value: repositories }; +} + +type DeleteOutcome = + | { status: "deleted" } + | { status: "missing" } + | { status: "unauthorized" } + | { status: "failed"; detail: string }; + +async function deleteGitlabTag( + doFetch: (url: string, init?: RequestInit) => Promise, + target: GitlabTarget, + repositoryId: number, + tag: string, +): Promise { + let res: Response; + try { + res = await doFetch( + `${target.api}/projects/${target.project}/registry/repositories/${repositoryId}/tags/${encodeURIComponent(tag)}`, + { method: "DELETE", headers: gitlabHeaders(target) }, + ); + } catch (err) { + const detail = err instanceof Error ? err.message : String(err); + return { status: "failed", detail }; + } + if (res.ok || res.status === 202) return { status: "deleted" }; + if (res.status === 404) return { status: "missing" }; + if (unauthorizedStatus(res.status)) return { status: "unauthorized" }; + return { + status: "failed", + detail: `${res.status} ${await readErrorBody(res)}`, + }; +} + +function unauthorizedWarning(scope: string): string { + return `registry tag delete is not authorized (missing ${scope} scope); leaving the tags to the forge expiration policy`; +} + +async function cleanupGitlab( + deps: CliDeps, + refs: string[], +): Promise { + const target = resolveGitlabTarget(deps.env); + if (!target.ok) { + return { deleted: [], warnings: [`registry tag cleanup skipped: ${target.error}`] }; + } + + const parsed = refs.flatMap((ref) => { + const image = parseImageRef(ref); + return image ? [{ ref, image }] : []; + }); + if (parsed.length === 0) return { deleted: [], warnings: [] }; + + const repositories = await listGitlabRepositories(fetchFor(deps), target.value); + if (!repositories.ok) { + const unauthorized = repositories.error.includes("unauthorized"); + return { + deleted: [], + warnings: [ + unauthorized + ? unauthorizedWarning("api") + : `${repositories.error}`, + ], + }; + } + + const deleted: string[] = []; + const warnings: string[] = []; + let sawUnauthorized = false; + for (const { ref, image } of parsed) { + const repositoryId = repositories.value.get(image.repository.toLowerCase()); + if (repositoryId === undefined) { + warnings.push(`registry tag already absent: ${ref}`); + continue; + } + const outcome = await deleteGitlabTag( + fetchFor(deps), + target.value, + repositoryId, + image.tag, + ); + switch (outcome.status) { + case "deleted": + deleted.push(ref); + break; + case "missing": + warnings.push(`registry tag already absent: ${ref}`); + break; + case "unauthorized": + sawUnauthorized = true; + break; + case "failed": + warnings.push(`registry tag delete failed for ${ref}: ${outcome.detail}`); + break; + } + } + if (sawUnauthorized) warnings.push(unauthorizedWarning("api")); + return { deleted, warnings }; +} + +type GithubTarget = { api: string; token: string; fallbackToken?: string }; + +function resolveGithubTarget(env: NodeJS.ProcessEnv): Result { + const deleteToken = env.GHCR_DELETE_TOKEN?.trim(); + const githubToken = env.GITHUB_TOKEN?.trim(); + const ghToken = env.GH_TOKEN?.trim(); + const token = deleteToken || githubToken || ghToken; + if (!token) { + return { + ok: false, + error: + "no GitHub token available (set GITHUB_TOKEN with delete:packages or package admin)", + }; + } + const fallbackToken = + deleteToken && deleteToken !== githubToken && deleteToken !== ghToken + ? githubToken || ghToken + : undefined; + return { + ok: true, + value: { + api: stripTrailingSlash( + env.GITHUB_API_URL?.trim() || "https://api.github.com", + ), + token, + ...(fallbackToken ? { fallbackToken } : {}), + }, + }; +} + +function githubHeaders(token: string): Record { + return { + Authorization: `Bearer ${token}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }; +} + +type GithubPackage = { packageBase: string; packageName: string }; + +async function resolveGithubPackage( + doFetch: (url: string, init?: RequestInit) => Promise, + target: GithubTarget, + image: ParsedImageRef, +): Promise> { + const parts = image.repository.split("/"); + const owner = parts[0]; + const packageName = parts.slice(1).join("/"); + if (!owner || !packageName) { + return { + ok: false, + error: `cannot derive GHCR package from ${image.registry}/${image.repository}`, + }; + } + + let res: Response; + try { + res = await doFetch( + `${target.api}/users/${encodeURIComponent(owner)}`, + { method: "GET", headers: githubHeaders(target.token) }, + ); + } catch (err) { + const detail = err instanceof Error ? err.message : String(err); + return { ok: false, error: `GHCR owner lookup failed: ${detail}` }; + } + if (!res.ok) { + const body = await readErrorBody(res); + return { + ok: false, + error: `GHCR owner lookup failed: ${res.status} ${body}`, + }; + } + + let data: unknown; + try { + data = await res.json(); + } catch { + return { ok: false, error: "GHCR owner lookup returned invalid JSON" }; + } + const type = + typeof data === "object" && data !== null + ? (data as { type?: unknown }).type + : undefined; + const ownerBase = type === "Organization" ? "orgs" : "users"; + return { + ok: true, + value: { + packageBase: `${ownerBase}/${encodeURIComponent(owner)}/packages/container`, + packageName, + }, + }; +} + +function nextLink(link: string | null): string | null { + if (!link) return null; + for (const part of link.split(",")) { + if (!/rel\s*=\s*"?next"?/.test(part)) continue; + const match = /<([^>]+)>/.exec(part); + if (match) return match[1] ?? null; + } + return null; +} + +type GithubVersion = { id: number; tags: string[] }; + +async function findGithubVersion( + doFetch: (url: string, init?: RequestInit) => Promise, + target: GithubTarget, + pkg: GithubPackage, + tag: string, +): Promise> { + let url = `${target.api}/${pkg.packageBase}/${encodeURIComponent(pkg.packageName)}/versions?per_page=100`; + for (let page = 0; page < MAX_GHCR_VERSION_PAGES; page++) { + let res: Response; + try { + res = await doFetch(url, { method: "GET", headers: githubHeaders(target.token) }); + } catch (err) { + const detail = err instanceof Error ? err.message : String(err); + return { ok: false, error: `GHCR version list failed: ${detail}` }; + } + if (!res.ok) { + const body = await readErrorBody(res); + return { + ok: false, + error: `GHCR version list failed: ${res.status} ${body}`, + }; + } + + let data: unknown; + try { + data = await res.json(); + } catch { + return { ok: false, error: "GHCR version list returned invalid JSON" }; + } + if (!Array.isArray(data)) { + return { ok: false, error: "GHCR version list returned invalid JSON" }; + } + + for (const item of data) { + if (typeof item !== "object" || item === null) continue; + const record = item as { + id?: unknown; + metadata?: { container?: { tags?: unknown } }; + }; + const tags = record.metadata?.container?.tags; + if ( + typeof record.id === "number" && + Array.isArray(tags) && + tags.includes(tag) + ) { + return { + ok: true, + value: { + id: record.id, + tags: tags.filter((item): item is string => typeof item === "string"), + }, + }; + } + } + + const next = nextLink(res.headers.get("link")); + if (!next) return { ok: true, value: null }; + url = next; + } + return { ok: true, value: null }; +} + +async function deleteGithubVersionWithToken( + doFetch: (url: string, init?: RequestInit) => Promise, + target: GithubTarget, + token: string, + pkg: GithubPackage, + versionId: number, +): Promise { + let res: Response; + try { + res = await doFetch( + `${target.api}/${pkg.packageBase}/${encodeURIComponent(pkg.packageName)}/versions/${versionId}`, + { method: "DELETE", headers: githubHeaders(token) }, + ); + } catch (err) { + const detail = err instanceof Error ? err.message : String(err); + return { status: "failed", detail }; + } + if (res.ok || res.status === 204) return { status: "deleted" }; + if (res.status === 404) return { status: "missing" }; + if (unauthorizedStatus(res.status)) return { status: "unauthorized" }; + return { + status: "failed", + detail: `${res.status} ${await readErrorBody(res)}`, + }; +} + +/** The registry login token often lacks delete:packages; the job token can delete. */ +async function deleteGithubVersion( + doFetch: (url: string, init?: RequestInit) => Promise, + target: GithubTarget, + pkg: GithubPackage, + versionId: number, +): Promise { + const outcome = await deleteGithubVersionWithToken( + doFetch, + target, + target.token, + pkg, + versionId, + ); + if (outcome.status !== "unauthorized" || !target.fallbackToken) return outcome; + return deleteGithubVersionWithToken( + doFetch, + target, + target.fallbackToken, + pkg, + versionId, + ); +} + +async function cleanupGithub( + deps: CliDeps, + refs: string[], +): Promise { + const target = resolveGithubTarget(deps.env); + if (!target.ok) { + return { deleted: [], warnings: [`registry tag cleanup skipped: ${target.error}`] }; + } + + type GithubEntry = + | { ref: string; warning: string } + | { ref: string; image: ParsedImageRef }; + const parsed: GithubEntry[] = refs.map((ref) => { + const image = parseImageRef(ref); + if (!image) { + return { + ref, + warning: `registry tag cleanup skipped for ${ref}: unsupported image reference`, + }; + } + if (image.registry.toLowerCase() !== "ghcr.io") { + return { + ref, + warning: `registry tag cleanup skipped for ${ref}: only ghcr.io is supported on GitHub`, + }; + } + return { ref, image }; + }); + + const targetTags = new Map>(); + for (const entry of parsed) { + if (!("image" in entry)) continue; + const tags = targetTags.get(entry.image.repository) ?? new Set(); + tags.add(entry.image.tag); + targetTags.set(entry.image.repository, tags); + } + + const deleted: string[] = []; + const warnings: string[] = []; + let sawUnauthorized = false; + for (const entry of parsed) { + if ("warning" in entry) { + warnings.push(entry.warning); + continue; + } + const pkg = await resolveGithubPackage( + fetchFor(deps), + target.value, + entry.image, + ); + if (!pkg.ok) { + if (unauthorizedDetail(pkg.error)) { + sawUnauthorized = true; + } else { + warnings.push( + `registry tag cleanup skipped for ${entry.ref}: ${pkg.error}`, + ); + } + continue; + } + const version = await findGithubVersion( + fetchFor(deps), + target.value, + pkg.value, + entry.image.tag, + ); + if (!version.ok) { + if (unauthorizedDetail(version.error)) { + sawUnauthorized = true; + } else { + warnings.push( + `registry tag cleanup skipped for ${entry.ref}: ${version.error}`, + ); + } + continue; + } + if (version.value === null) { + warnings.push(`registry tag already absent: ${entry.ref}`); + continue; + } + const wanted = targetTags.get(entry.image.repository) ?? new Set(); + const extraTags = version.value.tags.filter((tag) => !wanted.has(tag)); + if (extraTags.length > 0) { + warnings.push( + `registry tag delete skipped for ${entry.ref}: GHCR version ${version.value.id} also carries ${extraTags.join(", ")}`, + ); + continue; + } + const outcome = await deleteGithubVersion( + fetchFor(deps), + target.value, + pkg.value, + version.value.id, + ); + switch (outcome.status) { + case "deleted": + deleted.push(entry.ref); + break; + case "missing": + warnings.push(`registry tag already absent: ${entry.ref}`); + break; + case "unauthorized": + sawUnauthorized = true; + break; + case "failed": + warnings.push( + `registry tag delete failed for ${entry.ref}: ${outcome.detail}`, + ); + break; + } + } + if (sawUnauthorized) warnings.push(unauthorizedWarning("delete:packages")); + return { deleted, warnings }; +} + +export async function cleanupPushedImageRefs( + deps: CliDeps, + identity: Pick, + refs: string[], +): Promise { + if (refs.length === 0) return { deleted: [], warnings: [] }; + if (identity.forge === "gitlab") return cleanupGitlab(deps, refs); + return cleanupGithub(deps, refs); +} diff --git a/apps/cli/src/identity.ts b/apps/cli/src/identity.ts index f16f6d5..fab7e11 100644 --- a/apps/cli/src/identity.ts +++ b/apps/cli/src/identity.ts @@ -173,6 +173,19 @@ export function resolveCommitSha( return env[commitShaEnvVar(forge)]?.trim() || undefined; } +/** The head SHA survives a merged pull_request closed event; GITHUB_SHA does not. */ +export function resolvePullRequestHeadSha( + eventPayload: unknown, +): string | undefined { + if (typeof eventPayload !== "object" || eventPayload === null) return undefined; + const pullRequest = (eventPayload as { pull_request?: unknown }).pull_request; + if (typeof pullRequest !== "object" || pullRequest === null) return undefined; + const head = (pullRequest as { head?: unknown }).head; + if (typeof head !== "object" || head === null) return undefined; + const sha = (head as { sha?: unknown }).sha; + return typeof sha === "string" ? sha.trim() || undefined : undefined; +} + export function resolveCommitShaAny(env: NodeJS.ProcessEnv): string | undefined { return resolveCommitSha(env, "github") ?? resolveCommitSha(env, "gitlab"); } diff --git a/docs/ci-integration.md b/docs/ci-integration.md index 55a9a2e..3928e00 100644 --- a/docs/ci-integration.md +++ b/docs/ci-integration.md @@ -46,7 +46,10 @@ What the three jobs do: comes from the CLI's output only — never reconstruct the hostname in CI. - `sprout-stop-preview` (`on_stop`, Stop button / MR close / merge / `auto_stop_in` expiry): `sprout ci teardown` (idempotent — exit 0 when - already gone). + already gone). Once the preview is gone it also deletes the commit's app + and commit-scoped seed tags from the project registry, using the same CI + job token / credentials the push used. Missing tags and missing delete + permission only warn (the forge expiration policy remains the backstop). - `sprout-reset` (manual, instant): `sprout ci reset` — wipe the preview database and redeploy + seed from scratch (data wiped). Press **Run** on it inside the MR pipeline for the reset *now* (GitLab has no @@ -73,7 +76,7 @@ Flag details live in [CLI reference](cli-reference.md#ci-commands). | Component job | CLI call | Owns | |---|---|---| | `sprout-preview` | `sprout ci preview --tail … --dotenv-file … [--app-env-file …] [--seed-env-file …] [--reseed]` | Builds + pushes the app image and — when `.sprout.yaml` sets `seed` — the seed image (always rebuilt, unless explicit `seed.inputs` opt into content-addressed reuse: an existing tag skips the rebuild, reuse is logged, a failed check rebuilds), deploys (with `--reseed` when the flag is passed), writes `PREVIEW_URL=` to the dotenv artifact, dumps the gateway log tail on failure, and posts/updates the MR note (best-effort). | -| `sprout-stop-preview` | `sprout ci teardown` (no flags) | Idempotent teardown; rewrites the MR note in place ("preview was removed"). No Docker daemon, no registry login on this path. | +| `sprout-stop-preview` | `sprout ci teardown` (no flags) | Idempotent teardown; rewrites the MR note in place ("preview was removed"). Deletes the commit's app + commit-scoped seed registry tags through the GitLab API (best-effort warnings only). No Docker daemon, no registry login on this path. | | `sprout-reset` | `sprout ci reset --tail … --dotenv-file … [--app-env-file …] [--seed-env-file …]` | Wipe the preview database and redeploy + seed from scratch (data wiped). No rebuild: reuses the already pushed images for the commit, so no Docker daemon and no registry login on this path. | Manual helpers (never called by the component): `sprout ci reseed -s …` @@ -146,19 +149,31 @@ bootstrapper over `sprout ci preview` / `sprout ci teardown`) does: - Preview on `opened` / `synchronize` / `reopened`: installs the pinned, checksum-verified `sprout` binary, builds + pushes images - (`/:`, seed image driven by `.sprout.yaml` as on - GitLab), deploys, and posts/updates the PR comment with the preview URL. + (`/:`, seed image driven by `.sprout.yaml` + as on GitLab; the head SHA stays stable across the `closed` event so + teardown can find the same tags), deploys, and posts/updates the PR + comment with the preview URL. The URL is also exposed as the `preview_url` output and feeds `environment: url`. - Teardown on `closed`: `sprout ci teardown` (idempotent — exit 0 if - already gone). + already gone). It also deletes the commit's app and commit-scoped + (`-seed`) seed tags from GHCR through the GitHub Packages API; + content-addressed `seed-` tags are shared cache and are left in + place. Deletion tries `REGISTRY_PASSWORD` first and retries with + `GITHUB_TOKEN` if the delete is refused; if both are refused, a single + warning names the missing `delete:packages` scope and leaves cleanup to + the package expiration policy. - Reset is an ordinary action: run `sprout ci reset` from a hand-rolled job or laptop with the same secrets — no ticked box, no marker token. - Per-PR serial runs via a `sprout-preview-` concurrency group. The caller must grant `contents: read` (checkout), `pull-requests: write` (PR comment), and `packages: write` (image push to `ghcr.io`) — a reusable -workflow cannot elevate permissions. +workflow cannot elevate permissions. Tag cleanup on teardown uses the +repository's `GITHUB_TOKEN` by default; if GitHub refuses the package +delete, set the optional `REGISTRY_PASSWORD` secret to a token with +`delete:packages` (and package admin) to let cleanup run without waiting +for the expiration policy. Secrets (repo settings): diff --git a/docs/cli-reference.md b/docs/cli-reference.md index d756ad2..6876460 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -43,7 +43,7 @@ auth so outside-pipeline errors win over missing-token. | | `--tail N` | Gateway log lines printed when the deploy fails (default `200`; must be a positive integer, checked before building). | | | `--dotenv-file PATH` | Dotenv artifact the CLI writes `PREVIEW_URL=` to (default `sprout-preview.env`, relative to the workspace root). Emitted only once the preview is healthy. | | | `--reseed` | Force the gateway to re-run the seed against the existing database (requires a `seed` block) — re-seeds even when the seed image is unchanged. A changed seed image already re-seeds automatically; without seed changes, omit it — a reused image still seeds every fresh PR (`seeded_at` unset). | -| `sprout ci teardown` | *(no flags — extra args are rejected)* | Tear down this MR's preview. Idempotent; rewrites the MR note in place ("preview was removed"). Note failures only warn so gateway success owns the exit code. | +| `sprout ci teardown` | *(no flags — extra args are rejected)* | Tear down this MR's preview. Idempotent; rewrites the MR note in place ("preview was removed"). After the preview is gone, deletes the commit's app + commit-scoped seed image tags through the forge registry API (best effort: a missing tag or missing delete permission warns; the exit code stays 0). Note failures only warn so gateway success owns the exit code. | | `sprout ci reseed` | `-s ` (required) | Re-run the seed job against the existing database (data kept; no image build; app tag from `CI_REGISTRY_IMAGE` + SHA). Body is a reseed request, so companions stay as last deployed by construction. | | | `--seed-env`, `--seed-env-file`, `--seed-arg`, `--app-env`, `--app-env-file` | Same env layering as `preview` (yaml + blob + files + flags). | | `sprout ci reset` | `--tail N`, `--dotenv-file PATH`, `--app-env[-file]`, `--seed-env[-file]`, `--seed-arg`, `--service`, `--clear-services` (same deploy flags as `preview`, no `--reseed`) | Wipe the preview database and any `preview.volumes` data volumes, then redeploy + seed from scratch (data wiped; no rebuild — reuses the already pushed images for the commit). The note gains a `Reset: at ` line. The component's `sprout-reset` manual job funnels here. | diff --git a/docs/getting-started.md b/docs/getting-started.md index 2dd22db..b4e606c 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -80,7 +80,8 @@ preview URL. - Open / synchronize: the job deploys and writes `PREVIEW_URL=`. Read the URL from the CLI output — never reconstruct the hostname in CI. - Close / merge: `sprout ci teardown` runs via `on_stop` (idempotent — - exit 0 when already gone). + exit 0 when already gone) and deletes the commit's app + commit-scoped + seed image tags. - Manual wipe + redeploy: `sprout ci reset` (data wiped). - A missed teardown is recovered by the gateway sweep. - The gateway reports anonymous [install telemetry](telemetry.md) by diff --git a/templates/README.md b/templates/README.md index f83d783..bee77b4 100644 --- a/templates/README.md +++ b/templates/README.md @@ -25,7 +25,9 @@ instance. The component declares three jobs: - `sprout-preview` — builds + pushes images, deploys, writes `PREVIEW_URL=` to the dotenv artifact that feeds `environment:url`. - `sprout-stop-preview` — `on_stop` teardown (environment Stop button, MR - close/merge, `auto_stop_in` expiry). + close/merge, `auto_stop_in` expiry), deleting the commit's app + seed + registry tags after the preview is gone (best-effort; missing tags or + delete permission only warn). - `sprout-reset` — manual one-click wipe + redeploy + seed (`sprout ci reset`, data wiped). Play it from the MR pipeline when you want the reset *now*. @@ -70,7 +72,10 @@ Prerequisites on the GitLab side: - Container registry credentials come from the predefined `CI_REGISTRY_USER` / `CI_REGISTRY_PASSWORD`; the component logs in automatically when they are present. The app tag is always - `CI_REGISTRY_IMAGE:`. + `CI_REGISTRY_IMAGE:`. Teardown deletes that tag and the seed tag + through the GitLab container registry API using `CI_JOB_TOKEN` (or + `GITLAB_TOKEN` with `api` scope when set); an instance that refuses the + delete only produces a warning. ## Reset: manual job diff --git a/templates/preview.test.ts b/templates/preview.test.ts index a157bd4..42fec66 100644 --- a/templates/preview.test.ts +++ b/templates/preview.test.ts @@ -56,10 +56,11 @@ describe("preview component contract", () => { expect(previewScript()).toContain("docker login"); }); - test("stop runs teardown at the project dir with no app_context coupling", () => { + test("stop runs teardown in app_context so seed tags resolve from the manifest", () => { const stop = stopScript(); expect(stop).toContain("sprout ci teardown"); - expect(stop).not.toContain("app_context"); + expect(stop).toContain('$[[ inputs.app_context ]]'); + expect(stop).toContain('\ncd "$APP_CONTEXT"'); }); test("all path-shaped inputs resolve project-root-relative, before cd into app_context", () => { diff --git a/templates/preview.yml b/templates/preview.yml index 30461e6..3cec4f8 100644 --- a/templates/preview.yml +++ b/templates/preview.yml @@ -124,6 +124,8 @@ sprout-stop-preview: script: - | set -eu + APP_CONTEXT="$[[ inputs.app_context ]]" + cd "$APP_CONTEXT" sprout ci teardown sprout-reset: