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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
|
import { createHmac } from "crypto";
import { and, eq } from "drizzle-orm";
import { config } from "../lib/config";
import { autoRepair } from "../lib/autorepair";
import { notifyGateTestOfPush } from "../lib/gate";
import { analyzePush, computeHealthScore } from "../lib/intelligence";
import { db } from "../db";
import { deployments, repositories, users } from "../db/schema";
import { onDeployFailure } from "../lib/ai-incident";
import {
commitsBetween,
getDefaultBranch,
getRepoPath,
} from "../git/repository";
import { indexChangedFiles } from "../lib/semantic-index";
import { scanDiffForIssues } from "../lib/ai-auto-issues";
import { enqueuePreviewBuild } from "../lib/branch-previews";
import { scanDependencies } from "../lib/dependency-scanner";
import { runDocDriftCheckForRepo } from "../lib/ai-doc-updater";
import {
findTargetsForPush,
finishDeployRow,
resolveEnv,
startDeployRow,
} from "../lib/server-target-store";
import { deployToTarget } from "../lib/server-targets";
interface PushRef {
oldSha: string;
newSha: string;
refName: string;
}
export async function onPostReceive(
owner: string,
repo: string,
refs: PushRef[],
pusherUserId: string = ""
): Promise<void> {
for (const ref of refs) {
if (ref.newSha.startsWith("0000")) continue;
const branchName = ref.refName.replace("refs/heads/", "");
try {
const repair = await autoRepair(owner, repo, branchName);
if (repair.repaired) {
console.log(
`[autorepair] ${owner}/${repo}@${branchName}: ${repair.repairs.length} repairs committed`
);
}
} catch (err) {
console.error(`[autorepair] error:`, err);
}
try {
const analysis = await analyzePush(owner, repo, ref.oldSha, ref.newSha);
console.log(
`[push-analysis] ${owner}/${repo}: ${analysis.summary}`
);
if (analysis.riskScore > 50) {
console.warn(
`[push-analysis] HIGH RISK push detected (score: ${analysis.riskScore})`
);
}
if (analysis.breakingChangeSignals.length > 0) {
console.warn(
`[push-analysis] Breaking changes: ${analysis.breakingChangeSignals.join("; ")}`
);
}
} catch (err) {
console.error(`[push-analysis] error:`, err);
}
computeHealthScore(owner, repo).then((report) => {
console.log(
`[health] ${owner}/${repo}: ${report.grade} (${report.score}/100)`
);
}).catch((err) => {
console.error(`[health] error:`, err);
});
}
for (const ref of refs) {
if (ref.newSha.startsWith("0000")) continue;
notifyGateTestOfPush(owner, repo, ref.refName, ref.newSha).catch((err) =>
console.warn("[gatetest] notify error:", err)
);
}
for (const ref of refs) {
if (ref.newSha.startsWith("0000")) continue;
void fireSemanticIndex(owner, repo, ref.oldSha, ref.newSha).catch((err) =>
console.warn("[semantic-index] dispatch error:", err)
);
}
void firePreviewBuilds(owner, repo, refs).catch((err) =>
console.warn("[branch-previews] dispatch error:", err)
);
for (const ref of refs) {
if (ref.newSha.startsWith("0000")) continue;
scanDiffForIssues(owner, repo, ref.oldSha, ref.newSha, pusherUserId).catch(
(err) => console.warn("[ai-auto-issues] dispatch error:", err)
);
}
if (config.dependencyScanEnabled) {
void fireDependencyScan(owner, repo, refs).catch((err) =>
console.warn("[dependency-scanner] dispatch error:", err)
);
}
void fireDocDriftCheck(owner, repo).catch((err) =>
console.warn("[ai-doc-updater] dispatch error:", err)
);
if (`${owner}/${repo}` === config.crontechRepo) {
let defaultBranch =
(await getDefaultBranch(owner, repo).catch((err) => {
console.warn(
`[post-receive] getDefaultBranch failed for ${owner}/${repo}, defaulting to "main":`,
err instanceof Error ? err.message : err
);
return null;
})) || "main";
const targetRef = `refs/heads/${defaultBranch}`;
const deployPush = refs.find(
(r) => r.refName === targetRef && !r.newSha.startsWith("0000")
);
if (deployPush) {
let repositoryId = "";
try {
const [row] = await db
.select({ id: repositories.id })
.from(repositories)
.innerJoin(users, eq(repositories.ownerId, users.id))
.where(and(eq(users.username, owner), eq(repositories.name, repo)))
.limit(1);
repositoryId = row?.id || "";
} catch {
}
if (repositoryId) {
triggerCrontechDeploy({
owner,
repo,
before: deployPush.oldSha,
after: deployPush.newSha,
ref: targetRef,
branch: defaultBranch,
repositoryId,
}).catch((err: unknown) => console.error(`[crontech] error:`, err));
}
}
}
void fireServerTargetDeploys(owner, repo, refs).catch((err) =>
console.warn("[server-targets] dispatch error:", err)
);
const selfHostRepo = process.env.SELF_HOST_REPO;
if (selfHostRepo && `${owner}/${repo}` === selfHostRepo) {
const mainRef = refs.find(
(r) => r.refName === "refs/heads/main" && !r.newSha.startsWith("0000")
);
if (mainRef) {
const scriptPath =
process.env.GLUECRON_SELF_DEPLOY_SCRIPT ||
"/opt/gluecron/scripts/self-deploy.sh";
try {
const child = __selfHostSpawn(
[scriptPath, mainRef.oldSha, mainRef.newSha],
{ stdout: "ignore", stderr: "ignore", stdin: "ignore" }
);
try {
(child as any)?.unref?.();
} catch {
}
console.log(
`[self-host] dispatched self-deploy for ${owner}/${repo}@${mainRef.newSha.slice(0, 7)}`
);
} catch (err) {
console.error(`[self-host] failed to spawn:`, err);
}
}
}
}
const __defaultSelfHostSpawn: (cmd: string[], opts: any) => any = (cmd, opts) =>
Bun.spawn(cmd, opts);
let __selfHostSpawn: (cmd: string[], opts: any) => any = __defaultSelfHostSpawn;
export function __setSelfHostSpawnForTests(
fn: typeof __selfHostSpawn | null
): void {
__selfHostSpawn = fn ?? __defaultSelfHostSpawn;
}
const RETRY_DELAYS_MS = [1_000, 4_000, 16_000, 64_000, 256_000];
interface TriggerArgs {
owner: string;
repo: string;
before: string;
after: string;
ref: string;
branch: string;
repositoryId: string;
}
interface TriggerOptions {
fetchImpl?: typeof fetch;
sleep?: (ms: number) => Promise<void>;
retryDelaysMs?: number[];
now?: () => Date;
}
function signBody(body: string, secret: string): string | null {
if (!secret) return null;
return "sha256=" + createHmac("sha256", secret).update(body).digest("hex");
}
async function buildPayload(args: TriggerArgs, now: Date): Promise<{
payload: Record<string, unknown>;
pusherName: string;
pusherEmail: string;
}> {
const fromSha = /^0+$/.test(args.before) ? null : args.before;
let commits: Array<{ id: string; message: string; timestamp: string }> = [];
let pusherName = "gluecron";
let pusherEmail = "noreply@gluecron.local";
try {
const list = await commitsBetween(args.owner, args.repo, fromSha, args.after);
commits = list.slice(0, 50).map((c) => ({
id: c.sha,
message: c.message,
timestamp: c.date,
}));
if (list[0]) {
pusherName = list[0].author || pusherName;
pusherEmail = list[0].authorEmail || pusherEmail;
}
} catch {
}
return {
payload: {
event: "push",
repository: { full_name: `${args.owner}/${args.repo}` },
ref: args.ref,
after: args.after,
before: args.before,
pusher: { name: pusherName, email: pusherEmail },
commits,
sent_at: now.toISOString(),
source: "gluecron",
},
pusherName,
pusherEmail,
};
}
async function triggerCrontechDeploy(
args: TriggerArgs,
opts: TriggerOptions = {}
): Promise<void> {
const fetchImpl = opts.fetchImpl ?? fetch;
const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
const delays = opts.retryDelaysMs ?? RETRY_DELAYS_MS;
const now = opts.now ?? (() => new Date());
let deployId = "";
try {
const [row] = await db
.insert(deployments)
.values({
repositoryId: args.repositoryId,
environment: "production",
commitSha: args.after,
ref: args.ref,
status: "pending",
target: "crontech",
})
.returning();
deployId = row?.id || "";
} catch {
}
const { payload } = await buildPayload(args, now());
const body = JSON.stringify(payload);
const signature = signBody(body, config.gluecronWebhookSecret);
const headers: Record<string, string> = {
"Content-Type": "application/json",
"User-Agent": "gluecron-webhook/1",
"X-Gluecron-Event": "push",
"X-Gluecron-Delivery": cryptoRandomId(),
};
if (signature) headers["X-Gluecron-Signature"] = signature;
let lastStatus = 0;
let lastError = "";
let success = false;
const totalAttempts = delays.length + 1;
for (let attempt = 0; attempt < totalAttempts; attempt++) {
try {
const response = await fetchImpl(config.crontechDeployUrl, {
method: "POST",
headers,
body,
});
lastStatus = response.status;
console.log(
`[crontech] attempt ${attempt + 1}/${totalAttempts} → ${lastStatus} for ${args.owner}/${args.repo}@${args.after.slice(0, 7)}`
);
if (response.ok) {
success = true;
break;
}
if (response.status >= 400 && response.status < 500 &&
response.status !== 408 && response.status !== 429) {
break;
}
} catch (err) {
lastError = err instanceof Error ? err.message : String(err);
console.error(
`[crontech] attempt ${attempt + 1}/${totalAttempts} failed: ${lastError}`
);
}
const nextDelay = delays[attempt];
if (nextDelay !== undefined && attempt < totalAttempts - 1) {
await sleep(nextDelay);
}
}
if (deployId) {
try {
await db
.update(deployments)
.set({
status: success ? "success" : "failed",
blockedReason: success
? null
: (lastError ? lastError : `HTTP ${lastStatus}`),
completedAt: new Date(),
})
.where(eq(deployments.id, deployId));
} catch {
}
}
if (!success && deployId) {
void onDeployFailure({
repositoryId: args.repositoryId,
deploymentId: deployId,
ref: args.ref,
commitSha: args.after,
target: "crontech",
errorMessage: lastError || `HTTP ${lastStatus}`,
}).catch((e) => console.error("[ai-incident]", e));
}
}
function cryptoRandomId(): string {
const bytes = new Uint8Array(8);
crypto.getRandomValues(bytes);
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
async function fireSemanticIndex(
owner: string,
repo: string,
oldSha: string,
newSha: string
): Promise<void> {
let repositoryId = "";
try {
const [row] = await db
.select({ id: repositories.id })
.from(repositories)
.innerJoin(users, eq(repositories.ownerId, users.id))
.where(and(eq(users.username, owner), eq(repositories.name, repo)))
.limit(1);
repositoryId = row?.id || "";
} catch {
return;
}
if (!repositoryId) return;
let changedPaths: string[] = [];
try {
changedPaths = await listChangedPaths(owner, repo, oldSha, newSha);
} catch {
return;
}
if (!changedPaths.length) return;
try {
const out = await indexChangedFiles({
repositoryId,
ownerName: owner,
repoName: repo,
commitSha: newSha,
changedPaths,
});
if (out.indexed > 0) {
console.log(
`[semantic-index] ${owner}/${repo}@${newSha.slice(0, 7)}: indexed ${out.indexed} file(s) via ${out.model}`
);
}
} catch (err) {
console.warn("[semantic-index] indexChangedFiles error:", err);
}
}
async function listChangedPaths(
owner: string,
repo: string,
oldSha: string,
newSha: string
): Promise<string[]> {
const cwd = getRepoPath(owner, repo);
const allZero = /^0+$/.test(oldSha);
const cmd = allZero
? ["git", "ls-tree", "-r", "--name-only", newSha]
: ["git", "diff", "--name-only", oldSha, newSha];
try {
const proc = Bun.spawn(cmd, {
cwd,
stdout: "pipe",
stderr: "pipe",
});
const text = await new Response(proc.stdout).text();
await proc.exited;
return text
.split("\n")
.map((s) => s.trim())
.filter((s) => s.length > 0);
} catch {
return [];
}
}
async function firePreviewBuilds(
owner: string,
repo: string,
refs: PushRef[]
): Promise<void> {
const branchRefs = refs.filter(
(r) =>
r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
);
if (branchRefs.length === 0) return;
let repoRow: { id: string; previewBuildsEnabled: boolean; defaultBranch: string } | null = null;
try {
const [row] = await db
.select({
id: repositories.id,
previewBuildsEnabled: repositories.previewBuildsEnabled,
defaultBranch: repositories.defaultBranch,
})
.from(repositories)
.innerJoin(users, eq(repositories.ownerId, users.id))
.where(and(eq(users.username, owner), eq(repositories.name, repo)))
.limit(1);
repoRow = row || null;
} catch {
return;
}
if (!repoRow) return;
if (!repoRow.previewBuildsEnabled) return;
for (const ref of branchRefs) {
const branchName = ref.refName.replace("refs/heads/", "");
if (branchName === repoRow.defaultBranch) continue;
try {
await enqueuePreviewBuild({
repositoryId: repoRow.id,
ownerName: owner,
repoName: repo,
branchName,
commitSha: ref.newSha,
});
} catch (err) {
console.warn(
`[branch-previews] enqueue failed for ${owner}/${repo}@${branchName}:`,
err instanceof Error ? err.message : err
);
}
}
}
async function fireDocDriftCheck(owner: string, repo: string): Promise<void> {
let repositoryId = "";
try {
const [row] = await db
.select({ id: repositories.id })
.from(repositories)
.innerJoin(users, eq(repositories.ownerId, users.id))
.where(and(eq(users.username, owner), eq(repositories.name, repo)))
.limit(1);
repositoryId = row?.id || "";
} catch {
return;
}
if (!repositoryId) return;
try {
const out = await runDocDriftCheckForRepo(repositoryId);
if (out.docs > 0 || out.proposed > 0) {
console.log(
`[ai-doc-updater] ${owner}/${repo}: docs=${out.docs} proposed=${out.proposed}`
);
}
} catch (err) {
console.warn("[ai-doc-updater] runDocDriftCheckForRepo error:", err);
}
}
async function fireServerTargetDeploys(
owner: string,
repo: string,
refs: PushRef[]
): Promise<void> {
const liveRefs = refs.filter(
(r) => r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
);
if (liveRefs.length === 0) return;
let repositoryId = "";
try {
const [row] = await db
.select({ id: repositories.id })
.from(repositories)
.innerJoin(users, eq(repositories.ownerId, users.id))
.where(and(eq(users.username, owner), eq(repositories.name, repo)))
.limit(1);
repositoryId = row?.id || "";
} catch {
return;
}
if (!repositoryId) return;
await Promise.all(
liveRefs.map(async (ref) => {
const branch = ref.refName.replace("refs/heads/", "");
let targets;
try {
targets = await findTargetsForPush({ repositoryId, branch });
} catch {
return;
}
if (!targets.length) return;
await Promise.all(
targets.map(async (target) => {
try {
const env = await resolveEnv(target.id);
const deployId = await startDeployRow({
targetId: target.id,
commitSha: ref.newSha,
ref: ref.refName,
triggerSource: "push",
});
const result = await deployToTarget(target, {
commitSha: ref.newSha,
ref: ref.refName,
env,
});
if (deployId) {
await finishDeployRow({
id: deployId,
exitCode: result.exitCode,
stdout: result.stdout,
stderr: result.stderr,
});
}
console.log(
`[server-targets] ${target.name} @ ${ref.newSha.slice(0, 7)}: exit ${result.exitCode}`
);
} catch (err) {
console.warn(
`[server-targets] ${target.name}: deploy threw — ${err instanceof Error ? err.message : err}`
);
}
})
);
})
);
}
async function fireDependencyScan(
owner: string,
repo: string,
refs: PushRef[]
): Promise<void> {
const liveRefs = refs.filter(
(r) => r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000")
);
if (liveRefs.length === 0) return;
let repoRow: { id: string; ownerId: string } | null = null;
try {
const [row] = await db
.select({ id: repositories.id, ownerId: repositories.ownerId })
.from(repositories)
.innerJoin(users, eq(repositories.ownerId, users.id))
.where(and(eq(users.username, owner), eq(repositories.name, repo)))
.limit(1);
repoRow = row || null;
} catch {
return;
}
if (!repoRow) return;
for (const ref of liveRefs) {
try {
const findings = await scanDependencies(
repoRow.id,
owner,
repo,
ref.newSha,
ref.oldSha,
repoRow.ownerId
);
if (findings.length > 0) {
console.log(
`[dependency-scanner] ${owner}/${repo}@${ref.newSha.slice(0, 7)}: ${findings.length} finding(s)`
);
}
} catch (err) {
console.warn(
`[dependency-scanner] scan threw for ${owner}/${repo}@${ref.newSha.slice(0, 7)}:`,
err instanceof Error ? err.message : err
);
}
}
}
export const __test = {
triggerCrontechDeploy,
signBody,
buildPayload,
RETRY_DELAYS_MS,
listChangedPaths,
fireSemanticIndex,
firePreviewBuilds,
fireDocDriftCheck,
fireServerTargetDeploys,
fireDependencyScan,
};
|