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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
|
import { createHash } from "crypto";
import { and, desc, eq, gte, like } from "drizzle-orm";
import { db } from "../db";
import {
auditLog,
issueLabels,
issues,
labels,
repositories,
users,
} from "../db/schema";
import { platformDeploys } from "../db/schema-deploys";
import { workflowRuns } from "../db/schema";
import {
MODEL_SONNET,
extractText,
getAnthropic,
isAiAvailable,
parseJsonResponse,
} from "./ai-client";
import { audit } from "./notify";
export const DEFAULT_SELF_HOST_REPO = "ccantynz-alt/Gluecron.com";
export const PROACTIVE_LABEL_NAME = "ai:proactive-finding";
export const PROACTIVE_DEDUPE_MARKER_PREFIX =
"<!-- gluecron:ai-proactive:dedupe=";
export const PROACTIVE_DEDUPE_MARKER_SUFFIX = " -->";
export const PROACTIVE_LOOKBACK_HOURS = 24;
const MAX_AUDIT_ROWS = 200;
const MAX_DEPLOY_ROWS = 50;
const MAX_WORKFLOW_RUN_ROWS = 200;
const MAX_FINDINGS_PER_TICK = 5;
export type ProactiveSeverity = "info" | "warning" | "critical";
export interface ProactiveFinding {
title: string;
severity: ProactiveSeverity;
body_markdown: string;
target_url?: string | null;
}
export interface ProactiveTelemetry {
auditLog: Array<{
action: string;
targetType: string | null;
targetId: string | null;
userId: string | null;
repositoryId: string | null;
createdAt: Date;
}>;
platformDeploys: Array<{
runId: string;
sha: string;
status: string;
durationMs: number | null;
error: string | null;
startedAt: Date;
finishedAt: Date | null;
}>;
workflowRuns: Array<{
id: string;
status: string;
conclusion: string | null;
event: string;
queuedAt: Date;
startedAt: Date | null;
finishedAt: Date | null;
}>;
}
export interface ProactiveMonitorDeps {
loadTelemetry?: (lookbackHours: number) => Promise<ProactiveTelemetry>;
askClaude?: (
telemetry: ProactiveTelemetry
) => Promise<ProactiveFinding[]>;
resolveSelfHostRepo?: () => Promise<{
repositoryId: string;
ownerId: string;
} | null>;
isDuplicate?: (
repositoryId: string,
dedupeKey: string,
lookbackHours: number
) => Promise<boolean>;
createFindingIssue?: (args: {
repositoryId: string;
authorId: string;
title: string;
body: string;
}) => Promise<number | null>;
recordAudit?: (
finding: ProactiveFinding,
repositoryId: string | null,
issueNumber: number | null,
dedupeKey: string
) => Promise<void>;
now?: () => Date;
aiAvailable?: () => boolean;
maxFindings?: number;
}
export interface ProactiveMonitorSummary {
considered: number;
opened: number;
skippedDedupe: number;
skippedSeverity: number;
errors: number;
}
export function dedupeKeyForTitle(title: string): string {
return createHash("sha256")
.update(title.trim().toLowerCase())
.digest("hex")
.slice(0, 32);
}
function dedupeMarker(key: string): string {
return `${PROACTIVE_DEDUPE_MARKER_PREFIX}${key}${PROACTIVE_DEDUPE_MARKER_SUFFIX}`;
}
function summariseTelemetryForPrompt(t: ProactiveTelemetry): string {
const auditByAction = new Map<string, number>();
for (const row of t.auditLog) {
auditByAction.set(row.action, (auditByAction.get(row.action) || 0) + 1);
}
const auditLines = Array.from(auditByAction.entries())
.sort((a, b) => b[1] - a[1])
.slice(0, 30)
.map(([action, count]) => `- ${action}: ${count}`)
.join("\n");
const deployLines = t.platformDeploys
.slice(0, 30)
.map((d) => {
const dur = d.durationMs !== null ? `${d.durationMs}ms` : "n/a";
const err = d.error ? ` error="${d.error.slice(0, 120)}"` : "";
return `- run=${d.runId} sha=${d.sha.slice(0, 7)} status=${d.status} dur=${dur}${err}`;
})
.join("\n");
const wfStatusCounts = new Map<string, number>();
let durSum = 0;
let durCount = 0;
for (const r of t.workflowRuns) {
const key = `${r.status}/${r.conclusion ?? "n/a"}`;
wfStatusCounts.set(key, (wfStatusCounts.get(key) || 0) + 1);
if (r.startedAt && r.finishedAt) {
durSum += r.finishedAt.getTime() - r.startedAt.getTime();
durCount += 1;
}
}
const wfLines = Array.from(wfStatusCounts.entries())
.sort((a, b) => b[1] - a[1])
.map(([k, v]) => `- ${k}: ${v}`)
.join("\n");
const avgWfDuration =
durCount > 0 ? `${Math.round(durSum / durCount)}ms (n=${durCount})` : "n/a";
return [
`## Audit log (${t.auditLog.length} rows, top actions)`,
auditLines || "(none)",
"",
`## Platform deploys (${t.platformDeploys.length} rows, most recent first)`,
deployLines || "(none)",
"",
`## Workflow runs (${t.workflowRuns.length} rows, avg duration ${avgWfDuration})`,
wfLines || "(none)",
].join("\n");
}
async function defaultLoadTelemetry(
lookbackHours: number
): Promise<ProactiveTelemetry> {
const cutoff = new Date(Date.now() - lookbackHours * 60 * 60 * 1000);
const empty: ProactiveTelemetry = {
auditLog: [],
platformDeploys: [],
workflowRuns: [],
};
try {
const [audits, deploys, runs] = await Promise.all([
db
.select({
action: auditLog.action,
targetType: auditLog.targetType,
targetId: auditLog.targetId,
userId: auditLog.userId,
repositoryId: auditLog.repositoryId,
createdAt: auditLog.createdAt,
})
.from(auditLog)
.where(gte(auditLog.createdAt, cutoff))
.orderBy(desc(auditLog.createdAt))
.limit(MAX_AUDIT_ROWS)
.catch(() => [] as ProactiveTelemetry["auditLog"]),
db
.select({
runId: platformDeploys.runId,
sha: platformDeploys.sha,
status: platformDeploys.status,
durationMs: platformDeploys.durationMs,
error: platformDeploys.error,
startedAt: platformDeploys.startedAt,
finishedAt: platformDeploys.finishedAt,
})
.from(platformDeploys)
.where(gte(platformDeploys.startedAt, cutoff))
.orderBy(desc(platformDeploys.startedAt))
.limit(MAX_DEPLOY_ROWS)
.catch(() => [] as ProactiveTelemetry["platformDeploys"]),
db
.select({
id: workflowRuns.id,
status: workflowRuns.status,
conclusion: workflowRuns.conclusion,
event: workflowRuns.event,
queuedAt: workflowRuns.queuedAt,
startedAt: workflowRuns.startedAt,
finishedAt: workflowRuns.finishedAt,
})
.from(workflowRuns)
.where(gte(workflowRuns.queuedAt, cutoff))
.orderBy(desc(workflowRuns.queuedAt))
.limit(MAX_WORKFLOW_RUN_ROWS)
.catch(() => [] as ProactiveTelemetry["workflowRuns"]),
]);
return { auditLog: audits, platformDeploys: deploys, workflowRuns: runs };
} catch (err) {
console.error("[ai-proactive] telemetry load failed:", err);
return empty;
}
}
async function defaultAskClaude(
telemetry: ProactiveTelemetry
): Promise<ProactiveFinding[]> {
try {
const client = getAnthropic();
const message = await client.messages.create({
model: MODEL_SONNET,
max_tokens: 2048,
messages: [
{
role: "user",
content: `You are monitoring Gluecron's own platform health. Here is the last ${PROACTIVE_LOOKBACK_HOURS}h of telemetry. Spot anomalies — degraded deploy times, recurring failures, suspicious audit patterns, memory-leak suspects in long-running workers, abnormal workflow run durations, repeated permission denials, etc.
For each finding, return an entry in a JSON array of the form:
{"findings": [
{
"title": "<one-line problem summary, prefixed with the affected subsystem>",
"severity": "info" | "warning" | "critical",
"body_markdown": "<2-6 paragraphs of markdown: what you saw, why it might matter, suggested next step>",
"target_url": "<optional admin URL the operator should visit, or null>"
}
]}
Return ONLY the JSON. If nothing looks anomalous, return {"findings": []}. Do not invent findings — silence is the correct answer for a healthy platform.
Telemetry follows:
${summariseTelemetryForPrompt(telemetry)}`,
},
],
});
const parsed = parseJsonResponse<{ findings: ProactiveFinding[] }>(
extractText(message)
);
if (!parsed || !Array.isArray(parsed.findings)) return [];
return parsed.findings.filter(
(f) =>
typeof f.title === "string" &&
f.title.trim().length > 0 &&
typeof f.body_markdown === "string" &&
(f.severity === "info" ||
f.severity === "warning" ||
f.severity === "critical")
);
} catch (err) {
console.error("[ai-proactive] Claude call failed:", err);
return [];
}
}
async function defaultResolveSelfHostRepo(): Promise<{
repositoryId: string;
ownerId: string;
} | null> {
const fullName = process.env.SELF_HOST_REPO || DEFAULT_SELF_HOST_REPO;
const [ownerName, repoName] = fullName.includes("/")
? fullName.split("/")
: [fullName, "Gluecron.com"];
try {
const [row] = await db
.select({
repositoryId: repositories.id,
ownerId: repositories.ownerId,
})
.from(repositories)
.innerJoin(users, eq(users.id, repositories.ownerId))
.where(and(eq(users.username, ownerName), eq(repositories.name, repoName)))
.limit(1);
return row || null;
} catch (err) {
console.error("[ai-proactive] self-host repo resolve failed:", err);
return null;
}
}
async function defaultIsDuplicate(
repositoryId: string,
dedupeKey: string,
lookbackHours: number
): Promise<boolean> {
const cutoff = new Date(Date.now() - lookbackHours * 60 * 60 * 1000);
try {
const [row] = await db
.select({ id: issues.id })
.from(issues)
.where(
and(
eq(issues.repositoryId, repositoryId),
gte(issues.createdAt, cutoff),
like(issues.body, `%${dedupeMarker(dedupeKey)}%`)
)
)
.limit(1);
return !!row;
} catch (err) {
console.error("[ai-proactive] dedupe lookup failed:", err);
return true;
}
}
async function ensureProactiveLabel(
repositoryId: string
): Promise<string | null> {
try {
const [existing] = await db
.select({ id: labels.id })
.from(labels)
.where(
and(
eq(labels.repositoryId, repositoryId),
eq(labels.name, PROACTIVE_LABEL_NAME)
)
)
.limit(1);
if (existing) return existing.id;
const [inserted] = await db
.insert(labels)
.values({
repositoryId,
name: PROACTIVE_LABEL_NAME,
color: "#a371f7",
description: "Auto-filed by the AI proactive monitor.",
})
.returning({ id: labels.id });
return inserted?.id ?? null;
} catch (err) {
console.error("[ai-proactive] label ensure failed:", err);
return null;
}
}
async function defaultCreateFindingIssue(args: {
repositoryId: string;
authorId: string;
title: string;
body: string;
}): Promise<number | null> {
try {
const [inserted] = await db
.insert(issues)
.values({
repositoryId: args.repositoryId,
authorId: args.authorId,
title: args.title,
body: args.body,
state: "open",
})
.returning({ id: issues.id, number: issues.number });
if (!inserted) return null;
const labelId = await ensureProactiveLabel(args.repositoryId);
if (labelId) {
await db
.insert(issueLabels)
.values({ issueId: inserted.id, labelId })
.catch(() => {
});
}
return inserted.number ?? null;
} catch (err) {
console.error("[ai-proactive] issue insert failed:", err);
return null;
}
}
async function defaultRecordAudit(
finding: ProactiveFinding,
repositoryId: string | null,
issueNumber: number | null,
dedupeKey: string
): Promise<void> {
await audit({
repositoryId: repositoryId ?? undefined,
action: "ai.proactive.finding",
targetType: issueNumber !== null ? "issue" : undefined,
targetId: issueNumber !== null ? String(issueNumber) : undefined,
metadata: {
title: finding.title,
severity: finding.severity,
dedupeKey,
targetUrl: finding.target_url ?? null,
},
});
}
export async function aiProactiveMonitorTick(
deps: ProactiveMonitorDeps = {}
): Promise<ProactiveMonitorSummary> {
const aiAvailable = deps.aiAvailable ?? isAiAvailable;
const summary: ProactiveMonitorSummary = {
considered: 0,
opened: 0,
skippedDedupe: 0,
skippedSeverity: 0,
errors: 0,
};
if (!aiAvailable()) {
return summary;
}
const loadTelemetry = deps.loadTelemetry ?? defaultLoadTelemetry;
const askClaude = deps.askClaude ?? defaultAskClaude;
const resolveSelfHostRepo =
deps.resolveSelfHostRepo ?? defaultResolveSelfHostRepo;
const isDuplicate = deps.isDuplicate ?? defaultIsDuplicate;
const createFindingIssue =
deps.createFindingIssue ?? defaultCreateFindingIssue;
const recordAudit = deps.recordAudit ?? defaultRecordAudit;
const maxFindings = deps.maxFindings ?? MAX_FINDINGS_PER_TICK;
let repo: { repositoryId: string; ownerId: string } | null = null;
try {
repo = await resolveSelfHostRepo();
} catch (err) {
console.error("[ai-proactive] resolveSelfHostRepo threw:", err);
summary.errors += 1;
return summary;
}
if (!repo) {
console.warn(
"[ai-proactive] self-host repo not found; skipping tick (set SELF_HOST_REPO to the owner/name of the platform repo)"
);
return summary;
}
let telemetry: ProactiveTelemetry;
try {
telemetry = await loadTelemetry(PROACTIVE_LOOKBACK_HOURS);
} catch (err) {
console.error("[ai-proactive] loadTelemetry threw:", err);
summary.errors += 1;
return summary;
}
let findings: ProactiveFinding[] = [];
try {
findings = await askClaude(telemetry);
} catch (err) {
console.error("[ai-proactive] askClaude threw:", err);
summary.errors += 1;
return summary;
}
for (const finding of findings.slice(0, maxFindings)) {
summary.considered += 1;
try {
if (finding.severity === "info") {
summary.skippedSeverity += 1;
continue;
}
const dedupeKey = dedupeKeyForTitle(finding.title);
const dup = await isDuplicate(
repo.repositoryId,
dedupeKey,
PROACTIVE_LOOKBACK_HOURS
);
if (dup) {
summary.skippedDedupe += 1;
continue;
}
const body = renderFindingBody(finding, dedupeKey);
const issueNumber = await createFindingIssue({
repositoryId: repo.repositoryId,
authorId: repo.ownerId,
title: finding.title.slice(0, 200),
body,
});
if (issueNumber !== null) {
summary.opened += 1;
} else {
summary.errors += 1;
}
await recordAudit(finding, repo.repositoryId, issueNumber, dedupeKey);
} catch (err) {
summary.errors += 1;
console.error(
`[ai-proactive] per-finding failure for "${finding.title}":`,
err
);
}
}
if (findings.length > maxFindings) {
summary.skippedSeverity += findings.length - maxFindings;
}
console.log(
`[ai-proactive] tick considered=${summary.considered} opened=${summary.opened} dedup=${summary.skippedDedupe} skipped=${summary.skippedSeverity} errors=${summary.errors}`
);
return summary;
}
export function renderFindingBody(
finding: ProactiveFinding,
dedupeKey: string
): string {
const sevBadge =
finding.severity === "critical"
? "**Severity:** :rotating_light: critical"
: finding.severity === "warning"
? "**Severity:** :warning: warning"
: "**Severity:** :information_source: info";
const target = finding.target_url
? `**Suggested admin URL:** ${finding.target_url}`
: "";
return [
dedupeMarker(dedupeKey),
"_Filed automatically by the GlueCron AI proactive monitor._",
"",
sevBadge,
target,
"",
finding.body_markdown.trim(),
"",
"---",
`_Dedupe key: \`${dedupeKey}\`. The same finding will not be re-filed for ${PROACTIVE_LOOKBACK_HOURS}h._`,
]
.filter((line) => line !== "")
.join("\n");
}
export const __test = {
summariseTelemetryForPrompt,
defaultLoadTelemetry,
defaultResolveSelfHostRepo,
defaultIsDuplicate,
defaultCreateFindingIssue,
defaultRecordAudit,
dedupeMarker,
ensureProactiveLabel,
MAX_FINDINGS_PER_TICK,
};
|