Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
pr-sandbox.test.ts12.0 KB · 381 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/**
 * Tests for src/lib/pr-sandbox.ts — per-PR runnable sandboxes (migration 0067).
 *
 * Two layers:
 *
 *   1. Pure helpers — sandbox URL building, status label mapping,
 *      expires-in formatting. No DB, no network. Always run.
 *
 *   2. DB-backed pipeline — gated on HAS_DB so the suite stays green
 *      on machines without Postgres. Covers:
 *        - provisioning lifecycle (status transitions)
 *        - auto-expire after the TTL
 *        - idempotent re-provision on the same PR replaces the row
 *        - destroy flips status
 */

import { afterEach, describe, expect, it } from "bun:test";
import {
  buildSandboxUrl,
  destroySandbox,
  expireOldSandboxes,
  formatSandboxExpiresIn,
  getSandboxForPr,
  markSandboxFailed,
  markSandboxReady,
  provisionSandbox,
  sandboxStatusLabel,
  SANDBOX_TTL_MS,
} from "../lib/pr-sandbox";
import { db } from "../db";
import {
  prSandboxes,
  pullRequests,
  repositories,
  users,
} from "../db/schema";
import { eq } from "drizzle-orm";

const HAS_DB = Boolean(process.env.DATABASE_URL);

// ---------------------------------------------------------------------------
// 1. Pure helpers
// ---------------------------------------------------------------------------

describe("pr-sandbox — buildSandboxUrl", () => {
  it("produces a wildcard subdomain URL with default domain", () => {
    const prev = process.env.PR_SANDBOX_DOMAIN;
    delete process.env.PR_SANDBOX_DOMAIN;
    try {
      const url = buildSandboxUrl(42, "alice", "site");
      expect(url).toBe("https://pr-42-alice-site.sandbox.gluecron.com");
    } finally {
      if (prev !== undefined) process.env.PR_SANDBOX_DOMAIN = prev;
    }
  });

  it("honours a custom PR_SANDBOX_DOMAIN env var", () => {
    const prev = process.env.PR_SANDBOX_DOMAIN;
    process.env.PR_SANDBOX_DOMAIN = "sandbox.acme.dev";
    try {
      const url = buildSandboxUrl(1, "a", "b");
      expect(url).toBe("https://pr-1-a-b.sandbox.acme.dev");
    } finally {
      if (prev === undefined) delete process.env.PR_SANDBOX_DOMAIN;
      else process.env.PR_SANDBOX_DOMAIN = prev;
    }
  });

  it("strips scheme from PR_SANDBOX_DOMAIN if accidentally included", () => {
    const prev = process.env.PR_SANDBOX_DOMAIN;
    process.env.PR_SANDBOX_DOMAIN = "https://sandbox.foo.com";
    try {
      const url = buildSandboxUrl(7, "a", "b");
      expect(url).toBe("https://pr-7-a-b.sandbox.foo.com");
    } finally {
      if (prev === undefined) delete process.env.PR_SANDBOX_DOMAIN;
      else process.env.PR_SANDBOX_DOMAIN = prev;
    }
  });

  it("clamps negative / NaN PR numbers to 0", () => {
    expect(buildSandboxUrl(-3, "a", "b")).toContain("pr-0-");
    expect(buildSandboxUrl(NaN, "a", "b")).toContain("pr-0-");
  });

  it("slugifies owner/repo into one DNS label", () => {
    const url = buildSandboxUrl(2, "Big Org", "My_Repo");
    expect(url).toContain("pr-2-big-org-my-repo.");
  });
});

describe("pr-sandbox — sandboxStatusLabel", () => {
  it("maps known statuses to human labels", () => {
    expect(sandboxStatusLabel("provisioning")).toBe("Provisioning");
    expect(sandboxStatusLabel("ready")).toBe("Ready");
    expect(sandboxStatusLabel("failed")).toBe("Failed");
    expect(sandboxStatusLabel("destroyed")).toBe("Destroyed");
  });

  it("passes through unknown statuses unchanged", () => {
    expect(sandboxStatusLabel("unknown")).toBe("unknown");
  });
});

describe("pr-sandbox — formatSandboxExpiresIn", () => {
  it("returns 'expired' for past timestamps", () => {
    const now = new Date("2026-01-01T12:00:00Z");
    const past = new Date("2026-01-01T11:00:00Z");
    expect(formatSandboxExpiresIn(past, now)).toBe("expired");
  });

  it("returns 'less than a minute' for sub-minute futures", () => {
    const now = new Date("2026-01-01T12:00:00Z");
    const soon = new Date("2026-01-01T12:00:30Z");
    expect(formatSandboxExpiresIn(soon, now)).toBe("less than a minute");
  });

  it("returns just minutes when under an hour away", () => {
    const now = new Date("2026-01-01T12:00:00Z");
    const future = new Date("2026-01-01T12:42:00Z");
    expect(formatSandboxExpiresIn(future, now)).toBe("42m");
  });

  it("returns hours + minutes when over an hour away", () => {
    const now = new Date("2026-01-01T12:00:00Z");
    const future = new Date("2026-01-01T14:30:00Z");
    expect(formatSandboxExpiresIn(future, now)).toBe("2h 30m");
  });

  it("returns em-dash for null", () => {
    expect(formatSandboxExpiresIn(null)).toBe("—");
  });
});

describe("pr-sandbox — TTL constant matches 4h", () => {
  it("SANDBOX_TTL_MS is exactly 4 hours", () => {
    expect(SANDBOX_TTL_MS).toBe(4 * 60 * 60 * 1000);
  });
});

// ---------------------------------------------------------------------------
// 2. Graceful no-ops without DB — must not throw on empty inputs
// ---------------------------------------------------------------------------

describe("pr-sandbox — graceful no-ops", () => {
  it("provisionSandbox returns null for empty PR id", async () => {
    expect(await provisionSandbox({ prId: "" })).toBeNull();
  });

  it("getSandboxForPr returns null for empty PR id", async () => {
    expect(await getSandboxForPr("")).toBeNull();
  });

  it("markSandboxReady / markSandboxFailed / destroySandbox swallow empty ids", async () => {
    await markSandboxReady("");
    await markSandboxFailed("", "err");
    await destroySandbox("");
    expect(true).toBe(true);
  });
});

// ---------------------------------------------------------------------------
// 3. DB-backed pipeline
// ---------------------------------------------------------------------------

const TEST_USER_PREFIX = "sandboxtest_";

async function seedPr(): Promise<{
  userId: string;
  repoId: string;
  prId: string;
  prNumber: number;
}> {
  const username =
    TEST_USER_PREFIX + Math.random().toString(36).slice(2, 10);
  const [user] = await db
    .insert(users)
    .values({
      username,
      email: `${username}@sandboxtest.local`,
      passwordHash: "$2b$10$" + "x".repeat(53),
    })
    .returning();
  const [repo] = await db
    .insert(repositories)
    .values({
      name: "sandbox-test-" + Math.random().toString(36).slice(2, 8),
      ownerId: user!.id,
      diskPath: "/tmp/sandbox-test-" + Math.random().toString(36).slice(2, 8),
    })
    .returning();
  const [pr] = await db
    .insert(pullRequests)
    .values({
      repositoryId: repo!.id,
      authorId: user!.id,
      title: "Test PR",
      body: "Test body",
      baseBranch: "main",
      headBranch: "feature/x",
    })
    .returning();
  return {
    userId: user!.id,
    repoId: repo!.id,
    prId: pr!.id,
    prNumber: pr!.number,
  };
}

async function cleanupUser(userId: string): Promise<void> {
  try {
    // Repositories CASCADE PRs which CASCADE pr_sandboxes — single delete OK.
    await db.delete(repositories).where(eq(repositories.ownerId, userId));
    await db.delete(users).where(eq(users.id, userId));
  } catch {
    /* best effort */
  }
}

describe.skipIf(!HAS_DB)("pr-sandbox — DB pipeline", () => {
  let userId = "";

  afterEach(async () => {
    if (userId) await cleanupUser(userId);
    userId = "";
  });

  it("provisioning lifecycle: provisioning → ready", async () => {
    const seeded = await seedPr();
    userId = seeded.userId;

    const row = await provisionSandbox({
      prId: seeded.prId,
      // Skip the AI generator path in tests.
      playgroundYml: "runtime: docker\nimage: node:20-alpine\n",
    });
    expect(row).not.toBeNull();
    expect(row!.status).toBe("provisioning");
    expect(row!.sandboxUrl).toContain(`pr-${seeded.prNumber}-`);
    expect(row!.sandboxUrl.startsWith("https://")).toBe(true);
    expect(row!.expiresAt instanceof Date).toBe(true);
    expect(row!.expiresAt.getTime()).toBeGreaterThan(Date.now());
    expect(row!.playgroundYml).toContain("docker");

    await markSandboxReady(row!.id, "ctr-abc123");
    const ready = await getSandboxForPr(seeded.prId);
    expect(ready!.status).toBe("ready");
    expect(ready!.containerId).toBe("ctr-abc123");
  });

  it("provisioning lifecycle: provisioning → failed records error", async () => {
    const seeded = await seedPr();
    userId = seeded.userId;

    const row = await provisionSandbox({
      prId: seeded.prId,
      playgroundYml: "runtime: docker\n",
    });
    expect(row).not.toBeNull();

    const longError = "boom\n".repeat(10_000);
    await markSandboxFailed(row!.id, longError);
    const after = await getSandboxForPr(seeded.prId);
    expect(after!.status).toBe("failed");
    expect(after!.errorMessage).not.toBeNull();
    expect(after!.errorMessage!.length).toBeLessThanOrEqual(2_000);
  });

  it("idempotent: re-provisioning on same PR replaces the row", async () => {
    const seeded = await seedPr();
    userId = seeded.userId;

    const first = await provisionSandbox({
      prId: seeded.prId,
      playgroundYml: "runtime: docker # v1\n",
    });
    expect(first).not.toBeNull();

    // Flip to ready so we can verify the upsert resets it.
    await markSandboxReady(first!.id);
    let row = await getSandboxForPr(seeded.prId);
    expect(row!.status).toBe("ready");

    // Re-provision (force-push scenario).
    const second = await provisionSandbox({
      prId: seeded.prId,
      playgroundYml: "runtime: docker # v2\n",
    });
    expect(second).not.toBeNull();
    expect(second!.id).toBe(first!.id); // same row
    expect(second!.status).toBe("provisioning"); // reset
    expect(second!.playgroundYml).toContain("v2");
    expect(second!.errorMessage).toBeNull();
    expect(second!.destroyedAt).toBeNull();

    // And only ONE row exists per PR (unique constraint).
    const all = await db
      .select()
      .from(prSandboxes)
      .where(eq(prSandboxes.prId, seeded.prId));
    expect(all.length).toBe(1);
  });

  it("destroySandbox flips status + records destroyed_at", async () => {
    const seeded = await seedPr();
    userId = seeded.userId;

    const row = await provisionSandbox({
      prId: seeded.prId,
      playgroundYml: "runtime: docker\n",
    });
    await markSandboxReady(row!.id);

    await destroySandbox(row!.id);
    const after = await getSandboxForPr(seeded.prId);
    expect(after!.status).toBe("destroyed");
    expect(after!.destroyedAt).not.toBeNull();
  });

  it("expireOldSandboxes transitions ready rows past expires_at to 'destroyed'", async () => {
    const seeded = await seedPr();
    userId = seeded.userId;

    const row = await provisionSandbox({
      prId: seeded.prId,
      playgroundYml: "runtime: docker\n",
    });
    await markSandboxReady(row!.id);

    // Force expires_at into the past.
    await db
      .update(prSandboxes)
      .set({ expiresAt: new Date(Date.now() - 60_000) })
      .where(eq(prSandboxes.id, row!.id));

    const flipped = await expireOldSandboxes();
    expect(flipped).toBeGreaterThanOrEqual(1);

    const after = await getSandboxForPr(seeded.prId);
    expect(after!.status).toBe("destroyed");
    expect(after!.destroyedAt).not.toBeNull();
  });

  it("expireOldSandboxes leaves fresh rows alone", async () => {
    const seeded = await seedPr();
    userId = seeded.userId;

    const row = await provisionSandbox({
      prId: seeded.prId,
      playgroundYml: "runtime: docker\n",
    });
    await markSandboxReady(row!.id);

    // Default expiresAt is now+4h → expire pass should ignore it.
    await expireOldSandboxes();
    const after = await getSandboxForPr(seeded.prId);
    expect(after!.status).toBe("ready");
  });

  it("expireOldSandboxes also sweeps stuck 'provisioning' rows", async () => {
    const seeded = await seedPr();
    userId = seeded.userId;

    const row = await provisionSandbox({
      prId: seeded.prId,
      playgroundYml: "runtime: docker\n",
    });
    // Leave status='provisioning' but force expires_at into the past.
    await db
      .update(prSandboxes)
      .set({ expiresAt: new Date(Date.now() - 60_000) })
      .where(eq(prSandboxes.id, row!.id));

    const flipped = await expireOldSandboxes();
    expect(flipped).toBeGreaterThanOrEqual(1);

    const after = await getSandboxForPr(seeded.prId);
    expect(after!.status).toBe("destroyed");
  });
});