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
|
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";
export interface OrgRepoHealth {
repoId: string;
repoName: string;
ownerName: string;
score: number;
trend: "up" | "down" | "stable";
breakdown: HealthScoreBreakdown;
}
export interface OrgHealthReport {
orgSlug: string;
orgName: string;
avgScore: number;
repos: OrgRepoHealth[];
aiSummary: string;
generatedAt: Date;
}
interface OrgCacheEntry {
report: OrgHealthReport;
expiresAt: number;
}
const ORG_CACHE_TTL_MS = 60 * 60 * 1000;
const orgCache = new Map<string, OrgCacheEntry>();
export function invalidateOrgHealth(orgId: string): void {
orgCache.delete(orgId);
}
async function getTrendForRepo(
repoId: string,
currentScore: number
): Promise<"up" | "down" | "stable"> {
try {
const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
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";
}
}
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 "";
}
}
export async function computeOrgHealth(
orgId: string,
orgSlug: string
): Promise<OrgHealthReport> {
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 {
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;
}
const capped = repos.slice(0, 20);
const breakdowns = await Promise.all(
capped.map((r) => getHealthScore(r.id))
);
const trends = await Promise.all(
capped.map((r, i) => getTrendForRepo(r.id, breakdowns[i].total))
);
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],
}));
repoHealthList.sort((a, b) => a.score - b.score);
const sum = repoHealthList.reduce((acc, r) => acc + r.score, 0);
const avgScore = Math.round(sum / repoHealthList.length);
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;
}
}
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 {
}
}
|