import { env, RpcTarget } from "cloudflare:workers"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import type { GatekeeperVendor } from "../src/worker/index.ts"; import type { ApprovalQueue, GitCache, GatekeeperConnectCallback } from "@gadgets/workshop-shared/gatekeeper"; import type { AgentForkSession } from "../src/fork-types.d.ts"; import type { FixtureWorkspace } from "./worker.ts"; import { encodePktLine, FLUSH_PKT } from "@gadgets/gatekeeper-kit/git-transport"; import { fixtureState } from "../../forkhorse-dashboard/test/fixtures.ts"; import brand from "../../../brand.json"; import { markIconUrl } from "../../forkhorse-dashboard/src/mark.ts"; declare global { namespace Cloudflare { interface Env { VENDOR: Service; VENDOR_HTTP: Fetcher; CONNECT_CALLBACK: Service; WORKSPACES: DurableObjectNamespace; } } } const ORIGIN = "https://core.fixture.idiot.tax"; const REMOTE = "https://git.fixture.idiot.tax/fixture--alpha-1.git"; const OLD = "a".repeat(40), NEXT = "b".repeat(40); const CREDENTIAL = "fixture-agent-credential-only"; let head = OLD, role = "agent", agent = "alpha", scopes: string[], pushes: string[], unauthorized = false; let moveDuringPush = false, badGrant = false, redirectCore = false, redirectGit = false; let pulls: string[] = []; let workflowCalls: { path: string; method: string; body: unknown }[] = []; let pushFailure: "applied" | "absent" | null = null; let workflowMode: "standard" | "race" = "standard"; let workflowFailure = false; let coreReads: string[] = []; let discoveredForks: { repoName: string; remote: string; head: string; createdAt: string }[] = []; let packetReply: unknown; let revokeAfterPackets = false; const state = () => { const value = fixtureState("fixture"); value.forks.push({ repoName: "fixture--alpha-1", agent: "alpha", remote: REMOTE, head, createdAt: "2026-01-01" }); value.packets.push({ id: "workflow-packet", mode: workflowMode, title: "Workflow fixture", goal: "Fixture", paths: [], acceptance: [] }); return { ...value, races: [] }; }; function packets(lines: string[]): string { const chunks = [...lines.map(encodePktLine), FLUSH_PKT]; return chunks.map(c => new TextDecoder().decode(c)).join(""); } beforeEach(() => { workflowCalls = []; workflowMode = "standard"; workflowFailure = false; pushFailure = null; head = OLD; role = "agent"; agent = "alpha"; scopes = []; pushes = []; unauthorized = false; moveDuringPush = false; badGrant = false; redirectCore = false; redirectGit = false; pulls = []; coreReads = []; packetReply = undefined; revokeAfterPackets = false; discoveredForks = [{ repoName: "fixture--alpha-1", remote: REMOTE, head: OLD, createdAt: "2026-01-01T00:00:00Z" }]; vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => { const request = new Request(input, init); const url = new URL(request.url); if (url.origin === ORIGIN) { expect(request.redirect).toBe("manual"); if (redirectCore) return new Response(null, { status: 302, headers: { location: "https://foreign.idiot.tax" } }); expect(request.headers.get("authorization")).toBe(`Bearer ${CREDENTIAL}`); if (request.method === "GET") coreReads.push(url.pathname); if (url.pathname.endsWith("/me")) return Response.json({ role, agent, forks: discoveredForks.map(fork => ({ ...fork, head: fork.repoName === "fixture--alpha-1" ? head : fork.head })), work: [], }, { status: unauthorized ? 401 : 200 }); if (url.pathname.endsWith("/state")) return Response.json(state()); if (url.pathname.endsWith("/packets") && request.method === "GET") { if (revokeAfterPackets) unauthorized = true; return Response.json(packetReply ?? { packets: state().packets }); } if (url.pathname.endsWith("/reviews/workflow-review") && request.method === "GET") { return Response.json({ review: { id: "workflow-review", receipt: null } }); } if (url.pathname.endsWith("/join") || url.pathname.endsWith("/packets/workflow-packet/claim") || url.pathname.endsWith("/reviews")) { const body = request.method === "DELETE" ? null : await request.json(); workflowCalls.push({ path: url.pathname, method: request.method, body }); if (workflowFailure) return new Response("fixture-secret-error", { status: 503 }); return Response.json({ token: "fixture-join-secret-never-return", repoName: "fixture--alpha-2", expiresAt: new Date(Date.now() + 60_000).toISOString() }); } if (url.pathname.endsWith("/forks/fixture--alpha-1/token")) { const requested = await request.json<{ scope: string; ttlSeconds: number }>(); scopes.push(requested.scope); expect(requested.ttlSeconds).toBe(60); return Response.json({ repoName: "fixture--alpha-1", remote: badGrant ? "https://other.idiot.tax/repo" : REMOTE, scope: requested.scope, token: "fixture-git-token?expires=fixture", expiresAt: new Date(Date.now() + 60_000).toISOString() }, { status: 201 }); } } if (request.url === `${REMOTE}/git-upload-pack`) { expect(request.headers.get("git-protocol")).toBe("version=2"); expect(request.headers.get("user-agent")).toBe("git/2.0 (gatekeeper)"); expect(request.headers.get("authorization")).toBe(`Basic ${btoa("x:fixture-git-token")}`); pulls.push(new TextDecoder().decode(await request.arrayBuffer())); return new Response(packets(["packfile", "\x01fixture-pack"])); } if (request.url === `${REMOTE}/git-receive-pack`) { expect(request.redirect).toBe("manual"); if (redirectGit) return new Response(null, { status: 307, headers: { location: "https://foreign.idiot.tax" } }); expect(request.headers.get("user-agent")).toBe("git/2.0 (gatekeeper)"); expect(request.headers.get("authorization")).toBe(`Basic ${btoa("x:fixture-git-token")}`); const body = new TextDecoder().decode(await request.arrayBuffer()); pushes.push(body); expect(body).toContain(`${OLD} ${NEXT} refs/heads/main`); if (moveDuringPush) return new Response(packets(["unpack ok", "ng refs/heads/main stale old sha"])); if (pushFailure === "absent") throw new Error("Fixture failed before push"); head = NEXT; if (pushFailure === "applied") throw new Error("Fixture lost successful push reply"); return new Response(packets(["unpack ok", "ok refs/heads/main"])); } throw new Error("Unexpected offline fixture request."); }); }); afterEach(() => { vi.unstubAllGlobals(); }); async function refuse(operation: () => PromiseLike, pattern: string) { try { await operation(); } catch (error) { expect(String(error)).toContain(pattern); return; } throw new Error("Expected refusal"); } async function begin() { return (await env.FIXTURE.begin()).url; } async function submit(url: string, credential = CREDENTIAL) { return env.VENDOR_HTTP.fetch(url, { method: "POST", headers: { origin: "https://os.fixture.idiot.tax", "content-type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ coreOrigin: ORIGIN, project: "fixture", agentCredential: credential }).toString() }); } async function connect() { const url = await begin(); const form = await env.VENDOR_HTTP.fetch(url); expect(form.status).toBe(200); expect(form.headers.get("referrer-policy")).toBe("same-origin"); await form.text(); const response = await submit(url); expect(response.status).toBe(200); const html = await response.text(); expect(html).toContain("fixture-handoff-ticket"); expect(html).not.toContain(CREDENTIAL); return { user: await env.FIXTURE.account(), url }; } class Cache extends RpcTarget { advertised: string[] = []; builds = 0; consumed = ""; async consumePack(pack: ReadableStream): Promise { this.consumed = new TextDecoder().decode(await new Response(pack).arrayBuffer()); return [OLD]; } ancestor = true; async advertiseCommit(sha: string) { this.advertised.push(sha); } async isAncestor(): Promise { return this.ancestor; } async buildPack(): Promise> { this.builds++; return new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode("fixture-pack")); c.close(); } }); } } class Queue extends RpcTarget { readonly cache = new Cache(); observations = 0; submitted: { id: number; description: any }[] = []; loseReply = false; async authorizeObservation() { this.observations++; } async getGitCache() { return this.cache; } async submitAction(id: number, description: unknown) { this.submitted.push({ id, description }); if (this.loseReply) throw new Error("Synthetic lost queue reply"); } } async function resource() { const { user } = await connect(); const workspace = env.WORKSPACES.getByName(crypto.randomUUID()); await workspace.bind(user as unknown as Parameters[0], `${ORIGIN}/projects/fixture/forks/fixture--alpha-1`); const gatekeeper = workspace; const queue = new Queue(); const session = await gatekeeper.startSession(queue as unknown as ApprovalQueue) as AgentForkSession; return { user, gatekeeper, queue, session }; } it("connects an enrolled agent, advertises only its owned resource and embeds the real sidebar", async () => { const icon = { url: markIconUrl(brand.mark) }; expect(await env.VENDOR.describe()).toMatchObject({ displayName: brand.name, logo: icon, providesAuth: false, autoProvisionsAccount: false }); expect(await env.VENDOR.getSupportedResources()).toMatchObject([{ title: "Agent fork", icon }]); const { user, url } = await connect(); expect(await user.describe()).toMatchObject({ displayName: `${brand.name} · alpha`, uniqueName: "alpha · fixture", providesUi: { title: brand.name } }); expect((await user.getSupportedResources())).toHaveLength(1); expect(await user.getSupportedResources()).toMatchObject([{ icon }]); expect((await submit(url)).status).toBe(400); await refuse(() => user.getGatekeeperClassFor(`${ORIGIN}/projects/fixture/forks/fixture--foreign-1`), "does not own"); await refuse(() => user.getGatekeeperClassFor(`${ORIGIN}/projects/other/forks/fixture--alpha-1`), "outside"); const frame = await user.startAppUi!({ isAdmin: true }); expect(frame.iframeHtml).toContain("Ask an agent"); expect(frame.iframeHtml.match(/