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
org-insights.tsx10.4 KB · 346 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
/**
 * Block F2 — Org-wide insights.
 *
 *   GET /orgs/:slug/insights  — rollup across every repo owned by the org:
 *                               gate green-rate, open/merged PR counts, open
 *                               issue count, recent gate activity, per-repo
 *                               rows sorted by activity.
 *
 * No new tables — computed live from existing `repositories`, `gate_runs`,
 * `pull_requests`, `issues`.
 */

import { Hono } from "hono";
import { and, desc, eq, gte, sql } from "drizzle-orm";
import { db } from "../db";
import {
  gateRuns,
  issues,
  organizations,
  orgMembers,
  pullRequests,
  repositories,
} from "../db/schema";
import { Layout } from "../views/layout";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";

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

export interface OrgInsightsSummary {
  repoCount: number;
  gateRunsTotal: number;
  gatePassed: number;
  gateFailed: number;
  gateRepaired: number;
  greenRate: number; // 0..1
  openIssues: number;
  openPrs: number;
  mergedPrs30d: number;
  perRepo: Array<{
    id: string;
    name: string;
    runs: number;
    greenRate: number;
    openPrs: number;
    openIssues: number;
  }>;
}

export async function computeOrgInsights(
  orgId: string
): Promise<OrgInsightsSummary> {
  const empty: OrgInsightsSummary = {
    repoCount: 0,
    gateRunsTotal: 0,
    gatePassed: 0,
    gateFailed: 0,
    gateRepaired: 0,
    greenRate: 0,
    openIssues: 0,
    openPrs: 0,
    mergedPrs30d: 0,
    perRepo: [],
  };

  try {
    const repos = await db
      .select({ id: repositories.id, name: repositories.name })
      .from(repositories)
      .where(eq(repositories.orgId, orgId));
    if (repos.length === 0) return empty;

    const repoIds = repos.map((r) => r.id);
    const idList = sql.raw(
      repoIds.map((id) => `'${id.replace(/'/g, "''")}'`).join(",")
    );

    // Aggregate gate runs across repos
    const gateRows = await db
      .select({
        repoId: gateRuns.repositoryId,
        status: gateRuns.status,
        n: sql<number>`count(*)::int`,
      })
      .from(gateRuns)
      .where(sql`${gateRuns.repositoryId} IN (${idList})`)
      .groupBy(gateRuns.repositoryId, gateRuns.status);

    const totals = {
      passed: 0,
      failed: 0,
      repaired: 0,
      skipped: 0,
    } as Record<string, number>;
    const byRepo = new Map<
      string,
      { runs: number; passed: number; failed: number; repaired: number }
    >();
    for (const r of gateRows) {
      const n = Number(r.n);
      totals[r.status] = (totals[r.status] || 0) + n;
      const b = byRepo.get(r.repoId) || {
        runs: 0,
        passed: 0,
        failed: 0,
        repaired: 0,
      };
      b.runs += n;
      if (r.status === "passed") b.passed += n;
      else if (r.status === "failed") b.failed += n;
      else if (r.status === "repaired") b.repaired += n;
      byRepo.set(r.repoId, b);
    }
    const gateRunsTotal = Object.values(totals).reduce((a, b) => a + b, 0);
    const gatePassed = totals.passed || 0;
    const gateFailed = totals.failed || 0;
    const gateRepaired = totals.repaired || 0;
    const greenRate = gateRunsTotal
      ? (gatePassed + gateRepaired) / gateRunsTotal
      : 0;

    // Open issues/PRs across org repos
    const issueRows = await db
      .select({
        repoId: issues.repositoryId,
        state: issues.state,
        n: sql<number>`count(*)::int`,
      })
      .from(issues)
      .where(sql`${issues.repositoryId} IN (${idList})`)
      .groupBy(issues.repositoryId, issues.state);

    const openIssuesByRepo = new Map<string, number>();
    let openIssues = 0;
    for (const r of issueRows) {
      if (r.state === "open") {
        openIssuesByRepo.set(r.repoId, Number(r.n));
        openIssues += Number(r.n);
      }
    }

    const prRows = await db
      .select({
        repoId: pullRequests.repositoryId,
        state: pullRequests.state,
        n: sql<number>`count(*)::int`,
      })
      .from(pullRequests)
      .where(sql`${pullRequests.repositoryId} IN (${idList})`)
      .groupBy(pullRequests.repositoryId, pullRequests.state);

    const openPrsByRepo = new Map<string, number>();
    let openPrs = 0;
    for (const r of prRows) {
      if (r.state === "open") {
        openPrsByRepo.set(r.repoId, Number(r.n));
        openPrs += Number(r.n);
      }
    }

    // Merged PRs in last 30d
    const since = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const [mergedRow] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(pullRequests)
      .where(
        and(
          sql`${pullRequests.repositoryId} IN (${idList})`,
          eq(pullRequests.state, "merged"),
          gte(pullRequests.mergedAt, since)
        )
      );

    const perRepo = repos.map((r) => {
      const b = byRepo.get(r.id) || {
        runs: 0,
        passed: 0,
        failed: 0,
        repaired: 0,
      };
      const green = b.runs
        ? (b.passed + b.repaired) / b.runs
        : 0;
      return {
        id: r.id,
        name: r.name,
        runs: b.runs,
        greenRate: green,
        openPrs: openPrsByRepo.get(r.id) || 0,
        openIssues: openIssuesByRepo.get(r.id) || 0,
      };
    });
    perRepo.sort((a, b) => b.runs - a.runs);

    return {
      repoCount: repos.length,
      gateRunsTotal,
      gatePassed,
      gateFailed,
      gateRepaired,
      greenRate,
      openIssues,
      openPrs,
      mergedPrs30d: Number(mergedRow?.n || 0),
      perRepo,
    };
  } catch {
    return empty;
  }
}

async function loadOrg(slug: string) {
  try {
    const [o] = await db
      .select()
      .from(organizations)
      .where(eq(organizations.slug, slug))
      .limit(1);
    return o || null;
  } catch {
    return null;
  }
}

async function isOrgMember(orgId: string, userId: string): Promise<boolean> {
  try {
    const [row] = await db
      .select({ id: orgMembers.id })
      .from(orgMembers)
      .where(and(eq(orgMembers.orgId, orgId), eq(orgMembers.userId, userId)))
      .limit(1);
    return !!row;
  } catch {
    return false;
  }
}

orgInsights.get("/orgs/:slug/insights", requireAuth, async (c) => {
  const user = c.get("user")!;
  const slug = c.req.param("slug");
  const org = await loadOrg(slug);
  if (!org) return c.notFound();
  const member = await isOrgMember(org.id, user.id);
  if (!member) return c.redirect(`/orgs/${slug}`);

  const summary = await computeOrgInsights(org.id);
  const pct = (n: number) => Math.round(n * 100);

  return c.html(
    <Layout title={`${org.name} — Insights`} user={user}>
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
        <h2>{org.name} · Insights</h2>
        <a href={`/orgs/${slug}`} class="btn btn-sm">
          Back to {slug}
        </a>
      </div>

      <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px">
        <div class="panel" style="padding:12px;text-align:center">
          <div style="font-size:22px;font-weight:700">{summary.repoCount}</div>
          <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase">
            Repos
          </div>
        </div>
        <div class="panel" style="padding:12px;text-align:center">
          <div style="font-size:22px;font-weight:700;color:var(--green)">
            {pct(summary.greenRate)}%
          </div>
          <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase">
            Green rate
          </div>
        </div>
        <div class="panel" style="padding:12px;text-align:center">
          <div style="font-size:22px;font-weight:700;color:#79c0ff">
            {summary.openPrs}
          </div>
          <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase">
            Open PRs
          </div>
        </div>
        <div class="panel" style="padding:12px;text-align:center">
          <div style="font-size:22px;font-weight:700;color:#d2a8ff">
            {summary.mergedPrs30d}
          </div>
          <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase">
            Merged 30d
          </div>
        </div>
      </div>

      <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px">
        <div class="panel" style="padding:12px;text-align:center">
          <div style="font-size:18px;font-weight:600">{summary.gateRunsTotal}</div>
          <div style="font-size:11px;color:var(--text-muted)">Total gate runs</div>
        </div>
        <div class="panel" style="padding:12px;text-align:center">
          <div style="font-size:18px;font-weight:600;color:var(--green)">
            {summary.gatePassed}
          </div>
          <div style="font-size:11px;color:var(--text-muted)">Passed</div>
        </div>
        <div class="panel" style="padding:12px;text-align:center">
          <div style="font-size:18px;font-weight:600;color:#bc8cff">
            {summary.gateRepaired}
          </div>
          <div style="font-size:11px;color:var(--text-muted)">Repaired</div>
        </div>
        <div class="panel" style="padding:12px;text-align:center">
          <div style="font-size:18px;font-weight:600;color:var(--red)">
            {summary.gateFailed}
          </div>
          <div style="font-size:11px;color:var(--text-muted)">Failed</div>
        </div>
      </div>

      <h3>Per-repo breakdown</h3>
      <div class="panel" style="margin-bottom:20px">
        {summary.perRepo.length === 0 ? (
          <div class="panel-empty">This org has no repositories yet.</div>
        ) : (
          summary.perRepo.map((r) => (
            <div class="panel-item" style="justify-content:space-between">
              <div style="flex:1;min-width:0">
                <a href={`/${slug}/${r.name}`} style="font-weight:600">
                  {slug}/{r.name}
                </a>
                <div style="font-size:12px;color:var(--text-muted);margin-top:2px">
                  {r.runs} runs · {r.openPrs} open PRs · {r.openIssues} open
                  issues
                </div>
              </div>
              <span
                style={`font-family:var(--font-mono);color:${r.greenRate >= 0.9 ? "var(--green)" : r.greenRate >= 0.7 ? "#f0b72f" : "var(--red)"}`}
              >
                {r.runs > 0 ? `${pct(r.greenRate)}%` : "—"}
              </span>
            </div>
          ))
        )}
      </div>
    </Layout>
  );
});

export default orgInsights;