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
environments.tsx19.4 KB · 619 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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/**
 * Environments settings + approval routes (Block C4).
 *
 *   GET  /:owner/:repo/settings/environments           list + create form (owner-only)
 *   POST /:owner/:repo/settings/environments           create
 *   POST /:owner/:repo/settings/environments/:envId    update
 *   POST /:owner/:repo/settings/environments/:envId/delete
 *
 *   POST /:owner/:repo/deployments/:deploymentId/approve  approve a pending deploy
 *   POST /:owner/:repo/deployments/:deploymentId/reject   reject a pending deploy
 *
 * Approve/reject live under /deployments/:id/... so they don't collide with
 * the existing `GET /:owner/:repo/deployments/:id` detail page.
 */

import { Hono } from "hono";
import type { Context } from "hono";
import { and, eq, inArray } from "drizzle-orm";
import { db } from "../db";
import {
  environments,
  deployments,
  repositories,
  users,
} from "../db/schema";
import type { Environment } from "../db/schema";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { Layout } from "../views/layout";
import { RepoHeader, RepoNav } from "../views/components";
import { getUnreadCount } from "../lib/unread";
import { audit, notify } from "../lib/notify";
import {
  allowedBranchesOf,
  computeApprovalState,
  getEnvironmentById,
  getEnvironmentByName,
  isReviewer,
  listEnvironments,
  recordApproval,
  reviewerIdsOf,
} from "../lib/environments";

const r = new Hono<AuthEnv>();
r.use("*", softAuth);

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

async function loadRepo(owner: string, repo: string) {
  try {
    const [row] = await db
      .select({
        id: repositories.id,
        name: repositories.name,
        defaultBranch: repositories.defaultBranch,
        ownerId: repositories.ownerId,
        starCount: repositories.starCount,
        forkCount: repositories.forkCount,
      })
      .from(repositories)
      .innerJoin(users, eq(repositories.ownerId, users.id))
      .where(and(eq(users.username, owner), eq(repositories.name, repo)))
      .limit(1);
    return row || null;
  } catch (err) {
    console.error("[environments] loadRepo failed:", err);
    return null;
  }
}

function splitCsv(raw: unknown): string[] {
  if (typeof raw !== "string") return [];
  return raw
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean);
}

async function resolveUsernamesToIds(usernames: string[]): Promise<string[]> {
  if (usernames.length === 0) return [];
  try {
    const rows = await db
      .select({ id: users.id, username: users.username })
      .from(users)
      .where(inArray(users.username, usernames));
    return rows.map((r) => r.id);
  } catch (err) {
    console.error("[environments] resolve usernames failed:", err);
    return [];
  }
}

async function idsToUsernames(ids: string[]): Promise<string[]> {
  if (ids.length === 0) return [];
  try {
    const rows = await db
      .select({ id: users.id, username: users.username })
      .from(users)
      .where(inArray(users.id, ids));
    const map = new Map(rows.map((r) => [r.id, r.username]));
    return ids.map((id) => map.get(id) || id);
  } catch {
    return ids;
  }
}

// ---------------------------------------------------------------------------
// GET /:owner/:repo/settings/environments
// ---------------------------------------------------------------------------

r.get("/:owner/:repo/settings/environments", requireAuth, async (c) => {
  const user = c.get("user")!;
  const { owner, repo } = c.req.param();
  const repoRow = await loadRepo(owner, repo);
  if (!repoRow) return c.notFound();
  if (repoRow.ownerId !== user.id) {
    return c.redirect(`/${owner}/${repo}`);
  }

  const envs = await listEnvironments(repoRow.id);
  const unread = await getUnreadCount(user.id);
  const success = c.req.query("success");
  const err = c.req.query("error");

  // Resolve reviewer IDs → usernames per env for display.
  const envUsernames: Record<string, string[]> = {};
  for (const env of envs) {
    envUsernames[env.id] = await idsToUsernames(reviewerIdsOf(env));
  }

  return c.html(
    <Layout
      title={`Environments — ${owner}/${repo}`}
      user={user}
      notificationCount={unread}
    >
      <RepoHeader
        owner={owner}
        repo={repo}
        starCount={repoRow.starCount}
        forkCount={repoRow.forkCount}
        currentUser={user.username}
      />
      <RepoNav owner={owner} repo={repo} active="code" />
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px">
        <h3>Environments</h3>
        <a href={`/${owner}/${repo}/deployments`} class="btn btn-sm">
          Back to deployments
        </a>
      </div>
      {success && <div class="auth-success">{decodeURIComponent(success)}</div>}
      {err && <div class="auth-error">{decodeURIComponent(err)}</div>}

      <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 16px">
        Require human approval before a deploy to this environment runs.
        Branch patterns restrict which refs may target the environment.
      </p>

      <div class="panel" style="margin-bottom: 24px">
        {envs.length === 0 ? (
          <div class="panel-empty">No environments yet.</div>
        ) : (
          envs.map((env) => {
            const reviewers = envUsernames[env.id] || [];
            const branches = allowedBranchesOf(env);
            return (
              <form
                method="post"
                action={`/${owner}/${repo}/settings/environments/${env.id}`}
                class="panel-item"
                style="flex-direction: column; align-items: stretch; gap: 8px"
              >
                <div
                  style="display: flex; justify-content: space-between; align-items: center"
                >
                  <strong style="font-size: 15px">{env.name}</strong>
                  <div style="display: flex; gap: 6px">
                    <button type="submit" class="btn btn-sm btn-primary">
                      Save
                    </button>
                  </div>
                </div>
                <div class="form-group" style="margin: 0">
                  <label style="display: flex; align-items: center; gap: 6px">
                    <input
                      type="checkbox"
                      name="requireApproval"
                      value="1"
                      checked={env.requireApproval}
                    />
                    Require approval before deploy
                  </label>
                </div>
                <div class="form-group" style="margin: 0">
                  <label>Reviewers (comma-separated usernames)</label>
                  <input
                    type="text"
                    name="reviewers"
                    value={reviewers.join(", ")}
                    placeholder="alice, bob"
                    aria-label="Reviewers"
                  />
                </div>
                <div class="form-group" style="margin: 0">
                  <label>Wait timer (minutes)</label>
                  <input
                    type="number"
                    name="waitTimerMinutes"
                    min="0"
                    max="1440"
                    value={String(env.waitTimerMinutes)}
                    aria-label="Wait timer in minutes"
                    style="width: 120px"
                  />
                </div>
                <div class="form-group" style="margin: 0">
                  <label>Allowed branches (comma-separated glob patterns)</label>
                  <input
                    type="text"
                    name="allowedBranches"
                    value={branches.join(", ")}
                    placeholder="main, release/*"
                    aria-label="Allowed branches"
                  />
                </div>
                <div style="display: flex; justify-content: flex-end">
                  <button
                    type="submit"
                    formaction={`/${owner}/${repo}/settings/environments/${env.id}/delete`}
                    class="btn btn-sm btn-danger"
                    onclick="return confirm('Delete this environment?')"
                  >
                    Delete
                  </button>
                </div>
              </form>
            );
          })
        )}
      </div>

      <h3 style="margin-top: 24px; margin-bottom: 12px">New environment</h3>
      <form
        method="post"
        action={`/${owner}/${repo}/settings/environments`}
        class="panel"
        style="padding: 16px"
      >
        <div class="form-group">
          <label>Name</label>
          <input
            type="text"
            name="name"
            required
            placeholder="production"
            aria-label="Environment name"
          />
        </div>
        <div class="form-group">
          <label style="display: flex; align-items: center; gap: 6px">
            <input
              type="checkbox"
              name="requireApproval"
              value="1"
              checked
            />
            Require approval
          </label>
        </div>
        <div class="form-group">
          <label>Reviewers (comma-separated usernames)</label>
          <input type="text" name="reviewers" placeholder="alice, bob" aria-label="Reviewers" />
        </div>
        <div class="form-group">
          <label>Wait timer (minutes)</label>
          <input
            type="number"
            name="waitTimerMinutes"
            min="0"
            max="1440"
            value="0"
            aria-label="Wait timer in minutes"
            style="width: 120px"
          />
        </div>
        <div class="form-group">
          <label>Allowed branches (comma-separated glob patterns)</label>
          <input
            type="text"
            name="allowedBranches"
            placeholder="main, release/*"
            aria-label="Allowed branches"
          />
        </div>
        <button type="submit" class="btn btn-primary">
          Create environment
        </button>
      </form>
    </Layout>
  );
});

// ---------------------------------------------------------------------------
// POST /:owner/:repo/settings/environments      (create)
// ---------------------------------------------------------------------------

r.post("/:owner/:repo/settings/environments", requireAuth, async (c) => {
  const user = c.get("user")!;
  const { owner, repo } = c.req.param();
  const repoRow = await loadRepo(owner, repo);
  if (!repoRow) return c.notFound();
  if (repoRow.ownerId !== user.id) {
    return c.redirect(`/${owner}/${repo}`);
  }

  const body = await c.req.parseBody();
  const name = String(body.name || "").trim();
  if (!name) {
    return c.redirect(
      `/${owner}/${repo}/settings/environments?error=${encodeURIComponent(
        "Name required"
      )}`
    );
  }
  const requireApproval = body.requireApproval === "1" || body.requireApproval === "on";
  const reviewers = await resolveUsernamesToIds(splitCsv(body.reviewers));
  const waitTimerMinutes = Math.max(
    0,
    Math.min(1440, parseInt(String(body.waitTimerMinutes || "0"), 10) || 0)
  );
  const allowedBranches = splitCsv(body.allowedBranches);

  try {
    await db.insert(environments).values({
      repositoryId: repoRow.id,
      name,
      requireApproval,
      reviewers: JSON.stringify(reviewers),
      waitTimerMinutes,
      allowedBranches: JSON.stringify(allowedBranches),
    });
  } catch (err) {
    console.error("[environments] create failed:", err);
    return c.redirect(
      `/${owner}/${repo}/settings/environments?error=${encodeURIComponent(
        "Could not create (duplicate name?)"
      )}`
    );
  }

  await audit({
    userId: user.id,
    repositoryId: repoRow.id,
    action: "environment.create",
    targetType: "environment",
    metadata: { name, requireApproval, reviewers, allowedBranches },
  });

  return c.redirect(
    `/${owner}/${repo}/settings/environments?success=${encodeURIComponent(
      "Environment created"
    )}`
  );
});

// ---------------------------------------------------------------------------
// POST /:owner/:repo/settings/environments/:envId  (update)
// ---------------------------------------------------------------------------

r.post("/:owner/:repo/settings/environments/:envId", requireAuth, async (c) => {
  const user = c.get("user")!;
  const { owner, repo, envId } = c.req.param();
  const repoRow = await loadRepo(owner, repo);
  if (!repoRow) return c.notFound();
  if (repoRow.ownerId !== user.id) {
    return c.redirect(`/${owner}/${repo}`);
  }

  const env = await getEnvironmentById(repoRow.id, envId);
  if (!env) return c.notFound();

  const body = await c.req.parseBody();
  const requireApproval =
    body.requireApproval === "1" || body.requireApproval === "on";
  const reviewers = await resolveUsernamesToIds(splitCsv(body.reviewers));
  const waitTimerMinutes = Math.max(
    0,
    Math.min(1440, parseInt(String(body.waitTimerMinutes || "0"), 10) || 0)
  );
  const allowedBranches = splitCsv(body.allowedBranches);

  try {
    await db
      .update(environments)
      .set({
        requireApproval,
        reviewers: JSON.stringify(reviewers),
        waitTimerMinutes,
        allowedBranches: JSON.stringify(allowedBranches),
        updatedAt: new Date(),
      })
      .where(
        and(
          eq(environments.id, envId),
          eq(environments.repositoryId, repoRow.id)
        )
      );
  } catch (err) {
    console.error("[environments] update failed:", err);
  }

  await audit({
    userId: user.id,
    repositoryId: repoRow.id,
    action: "environment.update",
    targetType: "environment",
    targetId: envId,
    metadata: { requireApproval, reviewers, allowedBranches, waitTimerMinutes },
  });

  return c.redirect(
    `/${owner}/${repo}/settings/environments?success=${encodeURIComponent(
      "Environment updated"
    )}`
  );
});

// ---------------------------------------------------------------------------
// POST /:owner/:repo/settings/environments/:envId/delete
// ---------------------------------------------------------------------------

r.post(
  "/:owner/:repo/settings/environments/:envId/delete",
  requireAuth,
  async (c) => {
    const user = c.get("user")!;
    const { owner, repo, envId } = c.req.param();
    const repoRow = await loadRepo(owner, repo);
    if (!repoRow) return c.notFound();
    if (repoRow.ownerId !== user.id) {
      return c.redirect(`/${owner}/${repo}`);
    }

    try {
      await db
        .delete(environments)
        .where(
          and(
            eq(environments.id, envId),
            eq(environments.repositoryId, repoRow.id)
          )
        );
    } catch (err) {
      console.error("[environments] delete failed:", err);
    }

    await audit({
      userId: user.id,
      repositoryId: repoRow.id,
      action: "environment.delete",
      targetType: "environment",
      targetId: envId,
    });

    return c.redirect(
      `/${owner}/${repo}/settings/environments?success=${encodeURIComponent(
        "Environment removed"
      )}`
    );
  }
);

// ---------------------------------------------------------------------------
// Approve/reject a pending deployment
// ---------------------------------------------------------------------------

async function loadDeployment(repositoryId: string, deploymentId: string) {
  try {
    const [row] = await db
      .select()
      .from(deployments)
      .where(
        and(
          eq(deployments.id, deploymentId),
          eq(deployments.repositoryId, repositoryId)
        )
      )
      .limit(1);
    return row || null;
  } catch (err) {
    console.error("[environments] loadDeployment failed:", err);
    return null;
  }
}

async function decide(
  c: Context<AuthEnv>,
  decision: "approved" | "rejected"
) {
  const user = c.get("user")!;
  const { owner, repo, deploymentId } = c.req.param();
  const repoRow = await loadRepo(owner, repo);
  if (!repoRow) return c.notFound();

  const deployment = await loadDeployment(repoRow.id, deploymentId);
  if (!deployment) return c.notFound();

  const envName = deployment.environment;
  const env = await getEnvironmentByName(repoRow.id, envName);
  if (!env) {
    // No env configured — nothing to approve. Treat as 404 for safety.
    return c.notFound();
  }

  const allowed = await isReviewer(env, user.id);
  if (!allowed) {
    return c.redirect(
      `/${owner}/${repo}/deployments/${deploymentId}?error=${encodeURIComponent(
        "Not a reviewer"
      )}`
    );
  }

  const body = await c.req.parseBody().catch(() => ({} as Record<string, unknown>));
  const comment = typeof body.comment === "string" ? body.comment : undefined;

  const inserted = await recordApproval({
    deploymentId,
    userId: user.id,
    decision,
    comment,
  });

  // Re-read state and flip the deployment row accordingly. When the env
  // carries a wait timer and the timer hasn't elapsed yet, we hold the
  // deploy in status="waiting_timer" with `readyAfter` populated; the
  // autopilot ticker (`releaseExpiredWaitTimers`) flips it later.
  const state = await computeApprovalState(deploymentId, env);
  let newStatus: string | null = null;
  let readyAfter: Date | null = null;
  let blockedReason: string | null = null;
  if (state.rejected) {
    newStatus = "rejected";
    blockedReason = "rejected by reviewer";
  } else if (state.approved && deployment.status === "pending_approval") {
    const now = new Date();
    if (state.readyAfter && state.readyAfter.getTime() > now.getTime()) {
      newStatus = "waiting_timer";
      readyAfter = state.readyAfter;
      blockedReason = `wait_timer until ${state.readyAfter.toISOString()}`;
    } else {
      newStatus = "pending"; // hand off to existing deployer
    }
  }

  if (newStatus) {
    try {
      await db
        .update(deployments)
        .set({
          status: newStatus,
          blockedReason,
          // Always overwrite readyAfter — clears any prior value when the
          // status flips to anything other than waiting_timer.
          readyAfter,
        })
        .where(eq(deployments.id, deploymentId));
    } catch (err) {
      console.error("[environments] deployment status flip failed:", err);
    }
  }

  await audit({
    userId: user.id,
    repositoryId: repoRow.id,
    action: decision === "approved" ? "deployment.approve" : "deployment.reject",
    targetType: "deployment",
    targetId: deploymentId,
    metadata: { recorded: !!inserted, newStatus },
  });

  if (deployment.triggeredBy && deployment.triggeredBy !== user.id) {
    try {
      await notify(deployment.triggeredBy, {
        kind: "deployment_approval",
        title:
          decision === "approved"
            ? `Deploy to ${envName} approved`
            : `Deploy to ${envName} rejected`,
        body:
          decision === "approved"
            ? `${user.username} approved the deploy of ${deployment.commitSha.slice(0, 7)}.`
            : `${user.username} rejected the deploy of ${deployment.commitSha.slice(0, 7)}.`,
        url: `/${owner}/${repo}/deployments/${deploymentId}`,
        repositoryId: repoRow.id,
      });
    } catch (err) {
      console.error("[environments] notify triggeredBy failed:", err);
    }
  }

  return c.redirect(`/${owner}/${repo}/deployments/${deploymentId}`);
}

r.post(
  "/:owner/:repo/deployments/:deploymentId/approve",
  requireAuth,
  async (c) => decide(c, "approved")
);

r.post(
  "/:owner/:repo/deployments/:deploymentId/reject",
  requireAuth,
  async (c) => decide(c, "rejected")
);

export default r;