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
cli-deploy.test.ts17.8 KB · 563 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/**
 * Block N4 — `gluecron deploy` CLI + /admin/deploys/trigger route tests.
 *
 * The CLI tests drive `triggerWorkflowDispatch`, `watchDeploy`, and the
 * `handleDeployCmd` glue with an injected `fetchImpl` — no network, no real
 * GitHub. They cover:
 *   - happy path: 204 dispatch → list-runs picks up the new run → exit 0
 *   - 401 / 422 friendly errors
 *   - --no-watch skips the polling loop entirely
 *
 * The /admin/deploys/trigger route test uses Bun's `mock.module` to stub
 * `../db` so the `softAuth → sessionCache` path can mint a fake admin user
 * without a real Neon connection. The K1-style spread-from-real pattern is
 * followed and the mock is restored in afterAll so this file never pollutes
 * the rest of the suite.
 */

import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";

import {
  triggerWorkflowDispatch,
  watchDeploy,
  handleDeployCmd,
  type FetchLike,
} from "../../cli/gluecron";

// ---------- helpers ---------------------------------------------------------

function jsonRes(status: number, body: any) {
  return {
    status,
    ok: status >= 200 && status < 300,
    text: async () => (typeof body === "string" ? body : JSON.stringify(body)),
  };
}

function noContent() {
  return {
    status: 204,
    ok: true,
    text: async () => "",
  };
}

function capture() {
  const lines: string[] = [];
  return {
    out: (s: string) => lines.push(s),
    text: () => lines.join("\n"),
    lines,
  };
}

// =============================================================================
// CLI — triggerWorkflowDispatch
// =============================================================================

describe("cli/deploy — triggerWorkflowDispatch", () => {
  it("POSTs to the right dispatch URL and resolves the latest run", async () => {
    const calls: Array<{ url: string; method: string; body?: string }> = [];
    const fakeRun = {
      id: 99887766,
      url: "https://api.github.com/repos/foo/bar/actions/runs/99887766",
      html_url: "https://github.com/foo/bar/actions/runs/99887766",
      created_at: new Date(Date.now()).toISOString(),
    };
    const fetchImpl: FetchLike = async (url, init) => {
      calls.push({ url, method: init?.method || "GET", body: init?.body });
      if (init?.method === "POST" && url.includes("/dispatches")) {
        return noContent();
      }
      if (url.includes("/runs?")) {
        return jsonRes(200, { workflow_runs: [fakeRun] });
      }
      throw new Error("unexpected fetch: " + url);
    };

    const result = await triggerWorkflowDispatch(
      {
        repo: "foo/bar",
        workflow: "hetzner-deploy.yml",
        ref: "main",
        githubToken: "ghp_test",
      },
      { fetchImpl, now: () => Date.now() }
    );

    expect(result.runId).toBe(99887766);
    expect(result.htmlUrl).toContain("/actions/runs/99887766");

    // First call is POST .../workflows/hetzner-deploy.yml/dispatches
    expect(calls[0].method).toBe("POST");
    expect(calls[0].url).toBe(
      "https://api.github.com/repos/foo/bar/actions/workflows/hetzner-deploy.yml/dispatches"
    );
    expect(calls[0].body).toBe(JSON.stringify({ ref: "main" }));
    // Second call is the runs query
    expect(calls[1].url).toContain(
      "/repos/foo/bar/actions/workflows/hetzner-deploy.yml/runs"
    );
    expect(calls[1].url).toContain("event=workflow_dispatch");
    expect(calls[1].url).toContain("branch=main");
  });

  it("maps 401 to a friendly error", async () => {
    const fetchImpl: FetchLike = async () =>
      jsonRes(401, { message: "Bad credentials" });
    await expect(
      triggerWorkflowDispatch(
        {
          repo: "foo/bar",
          workflow: "hetzner-deploy.yml",
          ref: "main",
          githubToken: "ghp_bad",
        },
        { fetchImpl }
      )
    ).rejects.toThrow(/GitHub auth failed \(401\)/);
  });

  it("maps 422 (bad ref) to a friendly error", async () => {
    const fetchImpl: FetchLike = async () =>
      jsonRes(422, { message: "No ref found for: nope" });
    await expect(
      triggerWorkflowDispatch(
        {
          repo: "foo/bar",
          workflow: "hetzner-deploy.yml",
          ref: "nope",
          githubToken: "ghp_test",
        },
        { fetchImpl }
      )
    ).rejects.toThrow(/422.*No ref found/);
  });

  it("rejects when no GitHub token is provided", async () => {
    await expect(
      triggerWorkflowDispatch(
        { repo: "foo/bar", workflow: "x.yml", ref: "main", githubToken: "" },
        { fetchImpl: async () => noContent() }
      )
    ).rejects.toThrow(/GLUECRON_GITHUB_TOKEN/);
  });

  it("rejects when --repo is not owner/name", async () => {
    await expect(
      triggerWorkflowDispatch(
        { repo: "no-slash", workflow: "x.yml", ref: "main", githubToken: "x" },
        { fetchImpl: async () => noContent() }
      )
    ).rejects.toThrow(/owner\/name/);
  });
});

// =============================================================================
// CLI — handleDeployCmd glue
// =============================================================================

describe("cli/deploy — handleDeployCmd", () => {
  it("--no-watch exits 0 immediately after dispatch (no polling)", async () => {
    let pollCalls = 0;
    const fakeRun = {
      id: 1,
      url: "u",
      html_url: "https://github.com/foo/bar/actions/runs/1",
      created_at: new Date().toISOString(),
    };
    const fetchImpl: FetchLike = async (url, init) => {
      if (init?.method === "POST" && url.includes("/dispatches")) return noContent();
      if (url.includes("/runs?")) return jsonRes(200, { workflow_runs: [fakeRun] });
      if (url.includes("/jobs")) {
        pollCalls++;
        return jsonRes(200, { jobs: [] });
      }
      throw new Error("unexpected: " + url);
    };
    const { out, text } = capture();
    const code = await handleDeployCmd(
      { host: "x" } as any,
      [
        "--repo",
        "foo/bar",
        "--gh-token",
        "ghp_x",
        "--no-watch",
      ],
      out,
      { fetchImpl }
    );
    expect(code).toBe(0);
    expect(pollCalls).toBe(0);
    expect(text()).toContain("Triggering hetzner-deploy.yml on foo/bar@main");
    expect(text()).toContain("Workflow run dispatched");
    expect(text()).not.toContain("Watching deploy status");
  });

  it("missing token prints a clear instructional error", async () => {
    const prevEnv = process.env.GLUECRON_GITHUB_TOKEN;
    delete process.env.GLUECRON_GITHUB_TOKEN;
    try {
      const { out, text } = capture();
      const code = await handleDeployCmd(
        { host: "x" } as any,
        ["--repo", "foo/bar"],
        out,
        { fetchImpl: async () => noContent() }
      );
      expect(code).toBe(1);
      expect(text()).toMatch(/GLUECRON_GITHUB_TOKEN/);
      expect(text()).toMatch(/config set github-token/);
    } finally {
      if (prevEnv !== undefined) process.env.GLUECRON_GITHUB_TOKEN = prevEnv;
    }
  });
});

// =============================================================================
// CLI — watchDeploy poll loop
// =============================================================================

describe("cli/deploy — watchDeploy", () => {
  it("logs step transitions and returns ok on success", async () => {
    const t0 = 1_700_000_000_000;
    const transcripts = [
      // poll 1: setup in progress
      {
        jobs: [
          {
            status: "in_progress",
            conclusion: null,
            steps: [
              {
                name: "Setup",
                status: "in_progress",
                conclusion: null,
                started_at: new Date(t0 + 5000).toISOString(),
                completed_at: null,
              },
            ],
          },
        ],
      },
      // poll 2: setup done, deploy in progress
      {
        jobs: [
          {
            status: "in_progress",
            conclusion: null,
            steps: [
              {
                name: "Setup",
                status: "completed",
                conclusion: "success",
                started_at: new Date(t0 + 5000).toISOString(),
                completed_at: new Date(t0 + 18000).toISOString(),
              },
              {
                name: "Deploy",
                status: "in_progress",
                conclusion: null,
                started_at: new Date(t0 + 18000).toISOString(),
                completed_at: null,
              },
            ],
          },
        ],
      },
      // poll 3: everything done, success
      {
        jobs: [
          {
            status: "completed",
            conclusion: "success",
            steps: [
              {
                name: "Setup",
                status: "completed",
                conclusion: "success",
                started_at: new Date(t0 + 5000).toISOString(),
                completed_at: new Date(t0 + 18000).toISOString(),
              },
              {
                name: "Deploy",
                status: "completed",
                conclusion: "success",
                started_at: new Date(t0 + 18000).toISOString(),
                completed_at: new Date(t0 + 42000).toISOString(),
              },
            ],
          },
        ],
      },
    ];
    let pollIdx = 0;
    const fetchImpl: FetchLike = async () =>
      jsonRes(200, transcripts[Math.min(pollIdx++, transcripts.length - 1)]);

    let nowMs = t0;
    const { out, lines } = capture();
    const res = await watchDeploy(
      { repo: "foo/bar", runId: 1, githubToken: "x", startedAt: t0 },
      out,
      {
        fetchImpl,
        pollMs: 0,
        maxPolls: 10,
        sleep: async () => {
          nowMs += 13_000;
        },
        now: () => nowMs,
      }
    );
    expect(res.ok).toBe(true);
    expect(res.conclusion).toBe("success");
    expect(lines.some((l) => l.includes("Setup (in progress)"))).toBe(true);
    expect(lines.some((l) => l.includes("Setup (completed in 13s)"))).toBe(true);
    expect(lines.some((l) => l.includes("Deploy (in progress)"))).toBe(true);
    expect(lines.some((l) => l.includes("Deploy (completed in 24s)"))).toBe(true);
  });

  it("returns ok:false when the run concludes with failure", async () => {
    const fetchImpl: FetchLike = async () =>
      jsonRes(200, {
        jobs: [
          {
            status: "completed",
            conclusion: "failure",
            steps: [
              {
                name: "Smoke test",
                status: "completed",
                conclusion: "failure",
                started_at: new Date().toISOString(),
                completed_at: new Date().toISOString(),
              },
            ],
          },
        ],
      });
    const { out } = capture();
    const res = await watchDeploy(
      { repo: "foo/bar", runId: 1, githubToken: "x", startedAt: Date.now() },
      out,
      { fetchImpl, pollMs: 0, maxPolls: 1, sleep: async () => {} }
    );
    expect(res.ok).toBe(false);
    expect(res.conclusion).toBe("failure");
  });
});

// =============================================================================
// /admin/deploys/trigger route
// =============================================================================
//
// We DI the github fetcher + GITHUB_TOKEN env via the test-only hooks on the
// route module so we never hit api.github.com. The session/auth path goes
// through softAuth + sessionCache, which we pre-warm with a fake user.

const _real_db = await import("../db");
const _schema = await import("../db/schema");

// Per-test row hooks (matching the layout-user-prop.test.ts pattern).
let _nextSessionRow: any = null;
let _nextUserRow: any = null;
let _nextAdminRow: any = null;
let _lastSelectFrom: any = null;

const tableName = (t: any): string => {
  // Identify by object identity against the real drizzle table objects.
  // Using `"propName" in table` (the previous approach) is unreliable
  // because drizzle's pgTable proxy doesn't always expose column names
  // via `has`. Identity comparison is rock-solid.
  if (t === _schema.sessions) return "sessions";
  if (t === _schema.users) return "users";
  if (t === _schema.siteAdmins) return "site_admins";
  return "?";
};

const _selectChain: any = {
  from: (t: any) => {
    _lastSelectFrom = t;
    return _selectChain;
  },
  innerJoin: () => _selectChain,
  leftJoin: () => _selectChain,
  where: () => _selectChain,
  orderBy: () => _selectChain,
  limit: async () => {
    const name = tableName(_lastSelectFrom);
    if (name === "sessions") return _nextSessionRow ? [_nextSessionRow] : [];
    if (name === "users") return _nextUserRow ? [_nextUserRow] : [];
    if (name === "site_admins") return _nextAdminRow ? [_nextAdminRow] : [];
    return [];
  },
  then: (resolve: (v: any) => void) => resolve([]),
};

const _fakeDb = {
  db: {
    select: () => _selectChain,
    insert: () => ({
      values: () => ({
        returning: async () => [],
        then: (r: (v: any) => void) => r(undefined),
      }),
    }),
    update: () => ({ set: () => ({ where: () => Promise.resolve() }) }),
    delete: () => ({ where: () => Promise.resolve() }),
  },
  getDb: () => _fakeDb.db,
};

mock.module("../db", () => ({ ..._real_db, ..._fakeDb }));

const { default: app } = await import("../app");
const { sessionCache } = await import("../lib/cache");
const adminDeploys = await import("../routes/admin-deploys");

const ADMIN_ID = "11111111-1111-1111-1111-111111111111";
const NON_ADMIN_ID = "22222222-2222-2222-2222-222222222222";
const ADMIN_TOKEN = "n4-admin-token";
const NON_ADMIN_TOKEN = "n4-nonadmin-token";

const ADMIN_USER = {
  id: ADMIN_ID,
  username: "admin_user",
  displayName: "Admin",
  email: "a@example.com",
  passwordHash: "x",
  createdAt: new Date(),
  updatedAt: new Date(),
};
const NON_ADMIN_USER = {
  id: NON_ADMIN_ID,
  username: "nobody",
  displayName: "Nobody",
  email: "n@example.com",
  passwordHash: "x",
  createdAt: new Date(),
  updatedAt: new Date(),
};

beforeEach(() => {
  // softAuth reads sessions+users from DB OR sessionCache. Pre-warming the
  // cache is enough; `isSiteAdmin` reads from `site_admins` table via _nextAdminRow.
  sessionCache.set(ADMIN_TOKEN, ADMIN_USER as any);
  sessionCache.set(NON_ADMIN_TOKEN, NON_ADMIN_USER as any);
  _nextSessionRow = null;
  _nextUserRow = null;
  _nextAdminRow = null;
});

afterAll(() => {
  sessionCache.invalidate(ADMIN_TOKEN);
  sessionCache.invalidate(NON_ADMIN_TOKEN);
  adminDeploys.__setGithubFetchForTests(null);
  adminDeploys.__setEnvForTests(null);
  mock.module("../db", () => _real_db);
});

// CSRF protection accepts a POST when either the Origin matches the host OR
// a CSRF token cookie+header is supplied. We use the Origin-match path — set
// `host: localhost` and `origin: http://localhost` and the middleware
// recognises it as a same-origin request.
const SAME_ORIGIN_HEADERS = {
  host: "localhost",
  origin: "http://localhost",
};

function authedPost(token: string, body: unknown): RequestInit {
  return {
    method: "POST",
    headers: {
      ...SAME_ORIGIN_HEADERS,
      cookie: `session=${token}`,
      "content-type": "application/json",
    },
    body: JSON.stringify(body),
  };
}

describe("/admin/deploys/trigger", () => {
  it("403s for an authed non-admin user", async () => {
    _nextAdminRow = null;
    adminDeploys.__setEnvForTests({ GITHUB_TOKEN: "ghp_admin" });
    adminDeploys.__setGithubFetchForTests(async () => noContent());

    const res = await app.request(
      "/admin/deploys/trigger",
      authedPost(NON_ADMIN_TOKEN, {})
    );
    expect(res.status).toBe(403);
  });

  it("401s when not authenticated", async () => {
    adminDeploys.__setEnvForTests({ GITHUB_TOKEN: "ghp_admin" });
    adminDeploys.__setGithubFetchForTests(async () => noContent());
    const res = await app.request("/admin/deploys/trigger", {
      method: "POST",
      headers: { ...SAME_ORIGIN_HEADERS, "content-type": "application/json" },
      body: JSON.stringify({}),
    });
    expect(res.status).toBe(401);
  });

  it("returns a helpful 400 when GITHUB_TOKEN is unset", async () => {
    _nextAdminRow = { userId: ADMIN_ID }; // site admin
    adminDeploys.__setEnvForTests({});       // no token
    let called = false;
    adminDeploys.__setGithubFetchForTests(async () => {
      called = true;
      return noContent();
    });
    const res = await app.request(
      "/admin/deploys/trigger",
      authedPost(ADMIN_TOKEN, {})
    );
    expect(res.status).toBe(400);
    const body = await res.json();
    expect(body.error).toMatch(/GITHUB_TOKEN/);
    expect(called).toBe(false);
  });

  it("200s for admin and POSTs the dispatch to GitHub", async () => {
    _nextAdminRow = { userId: ADMIN_ID };
    adminDeploys.__setEnvForTests({ GITHUB_TOKEN: "ghp_admin" });
    let captured: { url: string; body?: string; method?: string } | null = null;
    adminDeploys.__setGithubFetchForTests(async (url, init) => {
      captured = { url, body: init?.body, method: init?.method };
      return noContent();
    });
    const res = await app.request(
      "/admin/deploys/trigger",
      authedPost(ADMIN_TOKEN, {})
    );
    expect(res.status).toBe(200);
    const body = await res.json();
    expect(body.ok).toBe(true);
    expect(body.repo).toBe("ccantynz/Gluecron.com");
    expect(body.workflow).toBe("hetzner-deploy.yml");
    expect(body.ref).toBe("main");
    expect(captured).not.toBeNull();
    expect(captured!.method).toBe("POST");
    expect(captured!.url).toContain("/actions/workflows/hetzner-deploy.yml/dispatches");
    expect(JSON.parse(captured!.body!).ref).toBe("main");
  });

  it("502s when GitHub rejects the dispatch", async () => {
    _nextAdminRow = { userId: ADMIN_ID };
    adminDeploys.__setEnvForTests({ GITHUB_TOKEN: "ghp_admin" });
    adminDeploys.__setGithubFetchForTests(async () =>
      jsonRes(422, { message: "No ref found" })
    );
    const res = await app.request(
      "/admin/deploys/trigger",
      authedPost(ADMIN_TOKEN, { ref: "no-such-branch" })
    );
    expect(res.status).toBe(502);
    const body = await res.json();
    expect(body.error).toMatch(/422.*No ref found/);
  });
});