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-health.ts7.2 KB · 248 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
/**
 * Org-level team health computation.
 *
 * Aggregates per-repo health scores across every active repo in an org,
 * produces a worst-first ranked list, and generates an AI summary.
 *
 * Cache: in-memory, 1h TTL per orgId. Call invalidateOrgHealth(orgId) to
 * force a fresh computation on the next request.
 */

import { eq, and, lt, sql } from "drizzle-orm";
import { db } from "../db";
import { repositories, repoHealthCache } from "../db/schema";
import { getHealthScore, invalidateHealthScore, type HealthScoreBreakdown } from "./repo-health";
import { getAnthropic, isAiAvailable, extractText, MODEL_SONNET } from "./ai-client";

// ---------------------------------------------------------------------------
// Public interface
// ---------------------------------------------------------------------------

export interface OrgRepoHealth {
  repoId: string;
  repoName: string;
  ownerName: string;
  score: number;            // 0-100
  trend: "up" | "down" | "stable";  // compare to last week's cached score
  breakdown: HealthScoreBreakdown;
}

export interface OrgHealthReport {
  orgSlug: string;
  orgName: string;
  avgScore: number;
  repos: OrgRepoHealth[];   // sorted by score asc (worst first)
  aiSummary: string;        // Claude paragraph: org health state + top 3 actions
  generatedAt: Date;
}

// ---------------------------------------------------------------------------
// In-memory cache
// ---------------------------------------------------------------------------

interface OrgCacheEntry {
  report: OrgHealthReport;
  expiresAt: number; // Date.now() ms
}

const ORG_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
const orgCache = new Map<string, OrgCacheEntry>();

export function invalidateOrgHealth(orgId: string): void {
  orgCache.delete(orgId);
}

// ---------------------------------------------------------------------------
// Trend detection: compare current score to last week's DB-cached score
// ---------------------------------------------------------------------------

async function getTrendForRepo(
  repoId: string,
  currentScore: number
): Promise<"up" | "down" | "stable"> {
  try {
    const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
    // Look for a cached entry computed more than 7 days ago as the prior-week baseline
    const rows = await db
      .select({ score: repoHealthCache.score, computedAt: repoHealthCache.computedAt })
      .from(repoHealthCache)
      .where(
        and(
          eq(repoHealthCache.repoId, repoId),
          lt(repoHealthCache.computedAt, oneWeekAgo)
        )
      )
      .limit(1);

    if (rows.length === 0) return "stable";

    const priorScore = rows[0].score;
    if (currentScore > priorScore + 2) return "up";
    if (currentScore < priorScore - 2) return "down";
    return "stable";
  } catch {
    return "stable";
  }
}

// ---------------------------------------------------------------------------
// AI summary generation
// ---------------------------------------------------------------------------

async function generateAiSummary(
  orgName: string,
  repos: OrgRepoHealth[]
): Promise<string> {
  if (!isAiAvailable() || repos.length === 0) return "";

  try {
    const repoLines = repos
      .map((r) => {
        const bd = r.breakdown;
        return (
          `${r.repoName}: ${r.score}/100 ` +
          `(CI:${bd.ciGreenRate.score}, BusFactor:${bd.busFactor.score}, ` +
          `CVEs:${bd.openCves.score}, ReviewSpeed:${bd.reviewVelocity.score}, Debt:${bd.techDebt.score})`
        );
      })
      .join("\n");

    const prompt =
      `You are an engineering manager. Given these repository health scores for org ${orgName}, ` +
      `write 2-3 sentences summarising the overall health and exactly 3 concrete action items ` +
      `numbered 1-3. Be direct. No fluff.\n\nRepos (worst first):\n${repoLines}`;

    const anthropic = getAnthropic();
    const message = await anthropic.messages.create({
      model: MODEL_SONNET,
      max_tokens: 512,
      messages: [{ role: "user", content: prompt }],
    });

    return extractText(message);
  } catch {
    return "";
  }
}

// ---------------------------------------------------------------------------
// Core computation
// ---------------------------------------------------------------------------

export async function computeOrgHealth(
  orgId: string,
  orgSlug: string
): Promise<OrgHealthReport> {
  // Check in-memory cache first
  const now = Date.now();
  const cached = orgCache.get(orgId);
  if (cached && cached.expiresAt > now) {
    return cached.report;
  }

  const emptyReport: OrgHealthReport = {
    orgSlug,
    orgName: orgSlug,
    avgScore: 0,
    repos: [],
    aiSummary: "",
    generatedAt: new Date(),
  };

  try {
    // 1. Load all non-archived repos in the org
    const repos = await db
      .select({ id: repositories.id, name: repositories.name })
      .from(repositories)
      .where(
        and(
          eq(repositories.orgId, orgId),
          eq(repositories.isArchived, false)
        )
      )
      .orderBy(repositories.name);

    if (repos.length === 0) {
      const report = { ...emptyReport };
      orgCache.set(orgId, { report, expiresAt: now + ORG_CACHE_TTL_MS });
      return report;
    }

    // 2. Compute health scores in parallel (cap at 20 repos)
    const capped = repos.slice(0, 20);
    const breakdowns = await Promise.all(
      capped.map((r) => getHealthScore(r.id))
    );

    // 3. Get trends in parallel
    const trends = await Promise.all(
      capped.map((r, i) => getTrendForRepo(r.id, breakdowns[i].total))
    );

    // 4. Build OrgRepoHealth array
    const repoHealthList: OrgRepoHealth[] = capped.map((r, i) => ({
      repoId: r.id,
      repoName: r.name,
      ownerName: orgSlug,
      score: breakdowns[i].total,
      trend: trends[i],
      breakdown: breakdowns[i],
    }));

    // 5. Sort by score ascending (worst first — action list)
    repoHealthList.sort((a, b) => a.score - b.score);

    // 6. Compute average score
    const sum = repoHealthList.reduce((acc, r) => acc + r.score, 0);
    const avgScore = Math.round(sum / repoHealthList.length);

    // 7. Generate AI summary
    const aiSummary = await generateAiSummary(orgSlug, repoHealthList);

    const report: OrgHealthReport = {
      orgSlug,
      orgName: orgSlug,
      avgScore,
      repos: repoHealthList,
      aiSummary,
      generatedAt: new Date(),
    };

    orgCache.set(orgId, { report, expiresAt: now + ORG_CACHE_TTL_MS });
    return report;
  } catch (err) {
    const errorSummary =
      err instanceof Error ? `Error computing org health: ${err.message}` : "Error computing org health.";
    const report: OrgHealthReport = {
      ...emptyReport,
      aiSummary: errorSummary,
    };
    return report;
  }
}

/**
 * Invalidate health caches for all repos in an org and clear the org cache.
 * Called from the POST /orgs/:slug/health/recompute endpoint.
 */
export async function invalidateOrgHealthAndRepos(
  orgId: string
): Promise<void> {
  invalidateOrgHealth(orgId);
  try {
    const repos = await db
      .select({ id: repositories.id })
      .from(repositories)
      .where(
        and(
          eq(repositories.orgId, orgId),
          eq(repositories.isArchived, false)
        )
      );
    for (const r of repos) {
      invalidateHealthScore(r.id);
    }
  } catch {
    // best effort
  }
}