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
autopilot.ts54.2 KB · 1612 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
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
/**
 * Autopilot — self-sufficiency loop.
 *
 * Runs existing platform-maintenance tasks (mirror sync, merge queue progress,
 * weekly digests, advisory rescans) on an interval so the host runs itself
 * without an external cron. All sub-tasks are injected so tests can stub them
 * without touching the DB; the default task set wires real helpers from the
 * locked libs. Nothing here throws — every sub-task and the outer tick are
 * try/caught so a single failure never blocks the others.
 */

import { and, eq, gte, sql } from "drizzle-orm";
import { db } from "../db";
import {
  mergeQueueEntries,
  prComments,
  pullRequests,
  repoDependencies,
  repositories,
  users,
} from "../db/schema";
import { syncAllDue } from "./mirrors";
import { peekHead } from "./merge-queue";
import { sendDigestsToAll } from "./email-digest";
import { scanRepositoryForAlerts } from "./advisories";
import { releaseExpiredWaitTimers } from "./environments";
import { runScheduledWorkflowsTick } from "./scheduled-workflows";
import {
  evaluateAutoMerge,
  recordAutoMergeAttempt,
  type AutoMergeContext,
  type AutoMergeDecision,
} from "./auto-merge";
import { matchProtection } from "./branch-protection";
import { performMerge, type PerformMergeResult } from "./pr-merge";
import { audit } from "./notify";
import { runAiBuildTaskOnce } from "./ai-build-tasks";
import {
  sendSleepModeDigestForUser,
  SLEEP_MODE_USER_CAP_PER_TICK,
  SLEEP_MODE_COOLDOWN_HOURS,
} from "./sleep-mode";
import {
  runStalePrSweepOnce,
  runStaleIssueSweepOnce,
} from "./stale-sweep";
import { computePrRiskForPullRequest } from "./pr-risk";
import { prRiskScores } from "../db/schema";
import { purgeScheduledAccounts } from "./account-deletion";
import { purgeExpiredPlaygroundAccounts } from "./playground";
import {
  runSyntheticChecks,
  persistChecks,
  latestStatusByCheck,
  type SyntheticCheckResult,
} from "./synthetic-monitor";
import { aiProactiveMonitorTick } from "./ai-proactive-monitor";
import { runCiHealerTick } from "./ai-ci-healer";
import {
  runDailyStandupTaskOnce,
  runWeeklyStandupTaskOnce,
} from "./ai-standup";
import { runSpecToPrTaskOnce } from "./autopilot-spec-to-pr";
import { runMigrationWatcherTaskOnce } from "./migration-assistant";
import { sweepStale as sweepStalePrLive } from "./pr-live";
import { runAutoReleaseNotesTaskOnce } from "./ai-release-notes";
import { runPrTestGeneratorTaskOnce } from "./autopilot-pr-test-generator";
import { runAdvancementScan } from "./advancement-scanner";
import { expireOldSandboxes } from "./pr-sandbox";
import { expireIdleEnvs } from "./dev-env";
import { expireOldPreviews } from "./branch-previews";
import { getBotUserIdOrFallback } from "./bot-user";
import { runOnboardingDripTaskOnce } from "./onboarding-drip";
import { sendSmartDigestsToAll } from "./smart-digest";

export interface AutopilotTaskResult {
  name: string;
  ok: boolean;
  durationMs: number;
  error?: string;
}

export interface AutopilotTickResult {
  startedAt: string;
  finishedAt: string;
  tasks: AutopilotTaskResult[];
}

export interface AutopilotTask {
  name: string;
  run: () => Promise<void>;
}

export interface StartAutopilotOpts {
  intervalMs?: number;
  now?: () => number;
  tasks?: AutopilotTask[];
}

export interface RunTickOpts {
  tasks?: AutopilotTask[];
  now?: () => number;
}

const DEFAULT_INTERVAL_MS = 5 * 60 * 1000;
const ADVISORY_RESCAN_BATCH = 5;
/** K3 — recency window for auto-merge candidate selection. */
const AUTO_MERGE_LOOKBACK_HOURS = 24;
/** K3 — hard cap on PRs evaluated per tick (runaway protection). */
const AUTO_MERGE_MAX_PER_TICK = 50;
/** K3 — stable marker for the auto-merge audit comment. */
const AUTO_MERGE_COMMENT_MARKER = "<!-- gluecron:auto-merge:v1 -->";
/** M3 — hard cap on PRs scored per tick (runaway protection). */
const PR_RISK_RESCORE_MAX_PER_TICK = 20;
/** M3 — recency window for the pr-risk-rescore sweep. */
const PR_RISK_RESCORE_LOOKBACK_HOURS = 1;
/** Proactive monitor cadence — Claude scans platform telemetry hourly. */
const PROACTIVE_MONITOR_INTERVAL_MS = 60 * 60 * 1000;
let _lastProactiveMonitorAt = 0;
/** Spec-to-PR cadence — autopilot scans `.gluecron/specs/*.md` every 2 minutes. */
const SPEC_TO_PR_INTERVAL_MS = 2 * 60 * 1000;
let _lastSpecToPrAt = 0;
/**
 * Migration watcher cadence. The lookup is cheap (registry calls per
 * declared dep) but we still throttle to every 6 hours so we don't hammer
 * npm and don't propose more than ~one PR per repo per day.
 */
const MIGRATION_WATCHER_INTERVAL_MS = 6 * 60 * 60 * 1000;
let _lastMigrationWatcherAt = 0;
/**
 * Auto-release-notes cadence. Cheap once tags are rare; we still throttle
 * to every 10 minutes so freshly-pushed tags (whose release row was just
 * created by `POST /:owner/:repo/releases`) get notes within ~one tick
 * without us scanning the table every 5 minutes.
 */
const AUTO_RELEASE_NOTES_INTERVAL_MS = 10 * 60 * 1000;
let _lastAutoReleaseNotesAt = 0;
/**
 * PR test generator cadence. Cheap when opted-in repos are quiet; the
 * task itself short-circuits via the per-PR `ai:added-tests` marker so
 * we never re-process the same PR. 5-minute cadence aligns with the
 * "freshly opened PR" window the task uses for candidate selection.
 */
const PR_TEST_GENERATOR_INTERVAL_MS = 5 * 60 * 1000;
let _lastPrTestGeneratorAt = 0;
/**
 * PR sandbox cleanup cadence (migration 0067). Runs every 30 minutes —
 * sandboxes default to a 4h TTL so finer-grained cleanup isn't needed,
 * and skipping most of the 5-min outer ticks keeps the loop cheap.
 */
const PR_SANDBOX_CLEANUP_INTERVAL_MS = 30 * 60 * 1000;
let _lastPrSandboxCleanupAt = 0;
/**
 * Dev-env idle sweep cadence (migration 0072). Runs on every autopilot
 * tick (5 minutes) because per-env idle timeouts can be as short as a
 * few minutes — we don't want a 30-min cleanup window stranding a user
 * who set idle_minutes=5. The lib itself is a single SQL UPDATE so this
 * is cheap regardless of repo count.
 */
const DEV_ENV_IDLE_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
let _lastDevEnvIdleSweepAt = 0;
/**
 * AI dependency auto-updater cadence (migration 0077). Once per day is
 * plenty — the task itself caps at 10 repos and 2 candidates per repo,
 * keeping npm registry traffic low. Skips when DEP_UPDATER_ENABLED env
 * flag is not set to "1".
 */
const DEP_UPDATE_SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000;
let _lastDepUpdateSweepAt = 0;
/**
 * Advancement scanner cadence. Designed to run weekly on Mondays at
 * 08:00 UTC. The task itself is the cheap gate (checks both day-of-week
 * and minimum interval since last run) so we don't bake any cron-style
 * triggers into the autopilot loop. Each tick (5min) probes the gate;
 * the gate is satisfied at most once per 6 days, keeping the cadence
 * effectively weekly even if Monday-08:00 happens to be missed.
 */
const ADVANCEMENT_SCAN_MIN_INTERVAL_MS = 6 * 24 * 60 * 60 * 1000;
let _lastAdvancementScanAt = 0;
/** Hour of day (UTC) the advancement scan prefers. Configurable via env. */
function advancementScanHourUtc(): number {
  const raw = process.env.ADVANCEMENT_SCAN_HOUR_UTC;
  if (!raw) return 8;
  const n = Number(raw);
  if (!Number.isFinite(n) || n < 0 || n > 23) return 8;
  return Math.floor(n);
}
/** Day of week (0=Sun..6=Sat, UTC) the advancement scan prefers. */
function advancementScanDayOfWeek(): number {
  const raw = process.env.ADVANCEMENT_SCAN_DOW_UTC;
  if (!raw) return 1; // Monday
  const n = Number(raw);
  if (!Number.isFinite(n) || n < 0 || n > 6) return 1;
  return Math.floor(n);
}

/**
 * Smart-digest cadence. Designed to run once per day at 07:00 UTC.
 * The task itself checks `lastSmartDigestSentAt` per user (20h cooldown),
 * so even if the outer loop fires multiple times near 07:00, only one
 * digest is ever sent per day per user.
 */
const SMART_DIGEST_INTERVAL_MS = 22 * 60 * 60 * 1000; // 22h between outer checks
let _lastSmartDigestAt = 0;

/**
 * Default task set. Each task is a thin wrapper around an existing locked
 * helper — no gate/merge logic is duplicated here.
 */
export function defaultTasks(): AutopilotTask[] {
  return [
    {
      name: "mirror-sync",
      run: async () => {
        await syncAllDue();
      },
    },
    {
      name: "merge-queue",
      run: async () => {
        await processMergeQueues();
      },
    },
    {
      name: "weekly-digest",
      run: async () => {
        await sendDigestsToAll();
      },
    },
    {
      name: "advisory-rescan",
      run: async () => {
        await rescanAdvisoriesBatch(ADVISORY_RESCAN_BATCH);
      },
    },
    {
      name: "wait-timer-release",
      run: async () => {
        await releaseExpiredWaitTimers();
      },
    },
    {
      name: "scheduled-workflows",
      run: async () => {
        await runScheduledWorkflowsTick();
      },
    },
    {
      name: "auto-merge-sweep",
      run: async () => {
        await runAutoMergeSweep();
      },
    },
    {
      name: "ai-build-from-issues",
      run: async () => {
        const summary = await runAiBuildTaskOnce();
        console.log(
          `[autopilot] ai-build: queued=${summary.queued} skipped=${summary.skipped}`
        );
      },
    },
    {
      name: "sleep-mode-digest",
      run: async () => {
        const summary = await runSleepModeDigestTaskOnce();
        console.log(
          `[autopilot] sleep-mode-digest: sent=${summary.sent} skipped=${summary.skipped}`
        );
      },
    },
    {
      name: "stale-pr-sweep",
      run: async () => {
        // Two-stage gate: poke at 7d stale, close at 14d after poke
        // (when the repo opts in via `auto_close_stale_prs`).
        // Wrapped in try/catch so a finder crash never wedges the tick.
        try {
          const summary = await runStalePrSweepOnce();
          console.log(
            `[autopilot] stale-pr-sweep: poked=${summary.poked} closed=${summary.closed}`
          );
        } catch (err) {
          console.error("[autopilot] stale-pr-sweep: threw:", err);
        }
      },
    },
    {
      name: "stale-issue-sweep",
      run: async () => {
        // Mirror of stale-pr-sweep with the issue thresholds (30d/60d).
        try {
          const summary = await runStaleIssueSweepOnce();
          console.log(
            `[autopilot] stale-issue-sweep: poked=${summary.poked} closed=${summary.closed}`
          );
        } catch (err) {
          console.error("[autopilot] stale-issue-sweep: threw:", err);
        }
      },
    },
    {
      name: "pr-risk-rescore",
      run: async () => {
        const summary = await runPrRiskRescoreTaskOnce();
        console.log(
          `[autopilot] pr-risk-rescore: scored=${summary.scored} skipped=${summary.skipped}`
        );
      },
    },

    {
      // Block P5 — Hard-delete users whose 30-day grace period expired.
      name: "account-purge",
      run: async () => {
        try {
          const summary = await purgeScheduledAccounts({ cap: 50 });
          console.log(
            `[autopilot] account-purge: purged=${summary.purged} errors=${summary.errors}`
          );
        } catch (err) {
          console.error("[autopilot] account-purge: threw:", err);
        }
      },
    },
    {
      // Block Q3 — Hard-delete anonymous playground accounts past their
      // 24h TTL. CASCADE handles repos, sessions, issues. Per-user
      // try/catch in the lib so one FK violation can't stall the queue.
      name: "playground-purge",
      run: async () => {
        try {
          const summary = await purgeExpiredPlaygroundAccounts({ cap: 50 });
          console.log(
            `[autopilot] playground-purge: purged=${summary.purged} errors=${summary.errors}`
          );
        } catch (err) {
          console.error("[autopilot] playground-purge: threw:", err);
        }
      },
    },
    {
      // Proactive AI monitor — hourly. Claude reads 24h of audit_log +
      // platformDeploys + workflowRuns and opens issues on anomalies
      // (degraded deploy times, recurring failures, suspicious audit
      // patterns). Skips when ANTHROPIC_API_KEY is unset (the lib
      // itself short-circuits, but the cadence gate avoids redundant
      // work on every 5-min tick too).
      name: "ai-proactive-monitor",
      run: async () => {
        if (!process.env.ANTHROPIC_API_KEY) return;
        const now = Date.now();
        if (now - _lastProactiveMonitorAt < PROACTIVE_MONITOR_INTERVAL_MS) {
          return;
        }
        _lastProactiveMonitorAt = now;
        try {
          const summary = await aiProactiveMonitorTick();
          console.log(
            `[autopilot] ai-proactive-monitor: opened=${summary.opened} considered=${summary.considered} dedup=${summary.skippedDedupe}`
          );
        } catch (err) {
          console.error("[autopilot] ai-proactive-monitor: threw:", err);
        }
      },
    },
    {
      // AI CI Healer — autonomous CI failure → root-cause → patch PR loop.
      // Polls every tick (5 min) for failed workflow_runs that finished
      // at least HEAL_MIN_AGE_MS ago and haven't been processed yet.
      // Skips when ANTHROPIC_API_KEY is unset.
      name: "ci-healer",
      run: async () => {
        if (!process.env.ANTHROPIC_API_KEY) return;
        try {
          const summary = await runCiHealerTick();
          console.log(
            `[autopilot] ci-healer: considered=${summary.considered} healed=${summary.healed} gaveUp=${summary.gaveUp} skipped=${summary.skipped}`
          );
        } catch (err) {
          console.error("[autopilot] ci-healer: threw:", err);
        }
      },
    },
    {
      // Spec-to-PR autopilot — picks up `.gluecron/specs/*.md` files whose
      // front-matter status is `ready`, asks Claude to implement the spec,
      // opens a draft PR tagged `ai:spec-implementation`. Cadence-gated
      // to every 2 minutes.
      name: "spec-to-pr",
      run: async () => {
        if (!process.env.ANTHROPIC_API_KEY) return;
        const now = Date.now();
        if (now - _lastSpecToPrAt < SPEC_TO_PR_INTERVAL_MS) return;
        _lastSpecToPrAt = now;
        try {
          const summary = await runSpecToPrTaskOnce();
          console.log(
            `[autopilot] spec-to-pr: considered=${summary.considered} dispatched=${summary.dispatched} skipped=${summary.skipped} failed=${summary.failed}`
          );
        } catch (err) {
          console.error("[autopilot] spec-to-pr: threw:", err);
        }
      },
    },
    {
      // BLOCK S4 — Synthetic monitor.
      //
      // Runs the URL-only smoke suite (see src/lib/synthetic-monitor.ts),
      // records the outcome into `synthetic_checks`, and on a
      // green->red transition fires a webhook to MONITOR_ALERT_WEBHOOK_URL
      // (when configured) so the owner finds out instantly that the live
      // site is broken. Wrapped in try/catch — the monitor must never
      // wedge the tick.
      name: "synthetic-monitor",
      run: async () => {
        try {
          const summary = await runSyntheticMonitorTaskOnce();
          console.log(
            `[autopilot] synthetic-monitor: green=${summary.green} red=${summary.red} transitions=${summary.transitions}`
          );
        } catch (err) {
          console.error("[autopilot] synthetic-monitor: threw:", err);
        }
      },
    },
    {
      // Migration watcher — scans each repo's package.json for deps that
      // are at least one major version behind and asks Claude to draft an
      // upgrade PR. Cadence-gated to every 6 hours; the lib itself
      // enforces a per-repo + per-{dep,version} 7-day dedupe so we never
      // re-propose the same migration twice in a single window. Skips
      // entirely when ANTHROPIC_API_KEY is unset OR the
      // MIGRATION_WATCHER_ENABLED env flag is off.
      name: "migration-watcher",
      run: async () => {
        if (!process.env.ANTHROPIC_API_KEY) return;
        const now = Date.now();
        if (now - _lastMigrationWatcherAt < MIGRATION_WATCHER_INTERVAL_MS) {
          return;
        }
        _lastMigrationWatcherAt = now;
        try {
          const summary = await runMigrationWatcherTaskOnce();
          console.log(
            `[autopilot] migration-watcher: considered=${summary.considered} proposed=${summary.proposed} throttled=${summary.skippedThrottle} disabled=${summary.skippedNotEnabled} errors=${summary.errors}`
          );
        } catch (err) {
          console.error("[autopilot] migration-watcher: threw:", err);
        }
      },
    },
    {
      // AI Standup — daily Claude-generated team brief.
      // Fires at the user's configured UTC hour (default 09:00). Skips
      // entirely when ANTHROPIC_API_KEY is unset (the lib still has a
      // deterministic fallback, but we keep this task quiet unless the
      // operator has wired AI). Per-user dedupe via `hasStandupForToday`.
      name: "daily-standup",
      run: async () => {
        if (!process.env.ANTHROPIC_API_KEY) return;
        try {
          const summary = await runDailyStandupTaskOnce();
          console.log(
            `[autopilot] daily-standup: sent=${summary.sent} skipped=${summary.skipped} errors=${summary.errors}`
          );
        } catch (err) {
          console.error("[autopilot] daily-standup: threw:", err);
        }
      },
    },
    {
      // PR live co-editing — transition stale `pr_live_sessions` rows
      // to 'idle' (>60s) and 'left' (>5m) so the presence pill on the
      // PR detail page never claims a ghost user is still editing.
      // Cheap pure-SQL UPDATE; runs every tick.
      name: "pr-live-cleanup",
      run: async () => {
        try {
          const summary = await sweepStalePrLive();
          if (summary.idled > 0 || summary.left > 0) {
            console.log(
              `[autopilot] pr-live-cleanup: idled=${summary.idled} left=${summary.left}`
            );
          }
        } catch (err) {
          console.error("[autopilot] pr-live-cleanup: threw:", err);
        }
      },
    },
    {
      // AI Standup — weekly Claude-generated team brief. Mondays only.
      name: "weekly-standup",
      run: async () => {
        if (!process.env.ANTHROPIC_API_KEY) return;
        try {
          const summary = await runWeeklyStandupTaskOnce();
          console.log(
            `[autopilot] weekly-standup: sent=${summary.sent} skipped=${summary.skipped} errors=${summary.errors}`
          );
        } catch (err) {
          console.error("[autopilot] weekly-standup: threw:", err);
        }
      },
    },
    {
      // PR test generator — when a fresh PR opens against a repo that's
      // opted in (`autoGenerateTests=true`) and is not itself AI-generated,
      // ask Claude to write tests for the new code and push a commit onto
      // the same branch. Skips PRs without source-file changes; idempotent
      // via the `ai:added-tests` marker comment. Skips entirely when
      // ANTHROPIC_API_KEY is unset.
      name: "pr-test-generator",
      run: async () => {
        if (!process.env.ANTHROPIC_API_KEY) return;
        const now = Date.now();
        if (now - _lastPrTestGeneratorAt < PR_TEST_GENERATOR_INTERVAL_MS) {
          return;
        }
        _lastPrTestGeneratorAt = now;
        try {
          const summary = await runPrTestGeneratorTaskOnce();
          if (summary.considered > 0) {
            console.log(
              `[autopilot] pr-test-generator: considered=${summary.considered} dispatched=${summary.dispatched} skipped=${summary.skipped} failed=${summary.failed}`
            );
          }
        } catch (err) {
          console.error("[autopilot] pr-test-generator: threw:", err);
        }
      },
    },
    {
      // Advancement scanner — weekly Claude-driven scan for "what we
      // should ship next". Probes:
      //   1. Newer Claude models vs the one wired in ai-client.ts
      //   2. Stack dependencies that are at least one major behind
      //   3. Self-improvement opportunities in the last 7d of telemetry
      //   4. Trending dev-platform features competitors shipped
      // Cadence-gated to Mondays 08:00 UTC (configurable via
      // ADVANCEMENT_SCAN_HOUR_UTC + ADVANCEMENT_SCAN_DOW_UTC) and
      // throttled to at most one scan per 6 days. Skips entirely when
      // ANTHROPIC_API_KEY is unset — the offline probes are still
      // useful but most of the value comes from the Claude calls.
      // The lib itself enforces per-finding (sha256 of title) dedupe
      // for 30 days so repeated runs never re-file the same advancement.
      name: "advancement-scanner",
      run: async () => {
        if (!process.env.ANTHROPIC_API_KEY) return;
        if (process.env.ADVANCEMENT_SCAN_DISABLED === "1") return;
        const now = new Date();
        const nowMs = now.getTime();
        const targetHour = advancementScanHourUtc();
        const targetDow = advancementScanDayOfWeek();
        const dueByCadence =
          nowMs - _lastAdvancementScanAt >= ADVANCEMENT_SCAN_MIN_INTERVAL_MS;
        const dueByClock =
          now.getUTCDay() === targetDow &&
          now.getUTCHours() === targetHour;
        if (!dueByCadence || !dueByClock) return;
        _lastAdvancementScanAt = nowMs;
        try {
          const summary = await runAdvancementScan();
          console.log(
            `[autopilot] advancement-scanner: findings=${summary.findings.length} issues=${summary.openedIssues} prs=${summary.openedPrs} dedup=${summary.skippedDedupe} errors=${summary.errors}`
          );
        } catch (err) {
          console.error("[autopilot] advancement-scanner: threw:", err);
        }
      },
    },
    {
      // Auto-release-notes — backfills `releases.body` with Claude-generated
      // polished changelogs for any semver-tagged release whose body is
      // empty / too short. Cadence-gated to every 10 minutes; the lib
      // itself caps the per-tick batch and is no-op when no candidates
      // exist. Falls back to a deterministic bucketed summary when
      // ANTHROPIC_API_KEY is unset, so the body still ends up populated.
      name: "auto-release-notes",
      run: async () => {
        const now = Date.now();
        if (now - _lastAutoReleaseNotesAt < AUTO_RELEASE_NOTES_INTERVAL_MS) {
          return;
        }
        _lastAutoReleaseNotesAt = now;
        try {
          const summary = await runAutoReleaseNotesTaskOnce();
          if (summary.considered > 0 || summary.filled > 0) {
            console.log(
              `[autopilot] auto-release-notes: considered=${summary.considered} filled=${summary.filled} skipped=${summary.skipped} errors=${summary.errors}`
            );
          }
        } catch (err) {
          console.error("[autopilot] auto-release-notes: threw:", err);
        }
      },
    },
    {
      // PR sandbox cleanup — migration 0067. Tears down every PR sandbox
      // whose `expires_at` has passed. Cadence-gated to every 30 minutes
      // so the every-5-min outer loop doesn't pay the cost on most ticks.
      // The lib itself is a pure SQL UPDATE — safe + cheap to call even
      // when there's nothing to do.
      name: "pr-sandbox-cleanup",
      run: async () => {
        const now = Date.now();
        if (now - _lastPrSandboxCleanupAt < PR_SANDBOX_CLEANUP_INTERVAL_MS) {
          return;
        }
        _lastPrSandboxCleanupAt = now;
        try {
          const expired = await expireOldSandboxes();
          if (expired > 0) {
            console.log(`[autopilot] pr-sandbox-cleanup: expired=${expired}`);
          }
        } catch (err) {
          console.error("[autopilot] pr-sandbox-cleanup: threw:", err);
        }
      },
    },
    {
      // Dev-env idle sweep — migration 0072. Stops every dev env whose
      // `last_active_at + idle_minutes` has slipped into the past. Runs
      // on every tick (cadence-gated to 5min so a faster outer loop
      // doesn't hammer it). The lib itself is fail-soft + per-row idle
      // aware, so this is cheap + correct even when half the rows are
      // already 'stopped'.
      name: "dev-env-idle-sweep",
      run: async () => {
        const now = Date.now();
        if (now - _lastDevEnvIdleSweepAt < DEV_ENV_IDLE_SWEEP_INTERVAL_MS) {
          return;
        }
        _lastDevEnvIdleSweepAt = now;
        try {
          const stopped = await expireIdleEnvs();
          if (stopped > 0) {
            console.log(`[autopilot] dev-env-idle-sweep: stopped=${stopped}`);
          }
        } catch (err) {
          console.error("[autopilot] dev-env-idle-sweep: threw:", err);
        }
      },
    },
    {
      // Preview expiry — migration 0062. Flips every branch-preview row
      // whose `expires_at` is in the past to status='expired'. Runs on
      // every tick; the lib itself is a cheap SQL UPDATE and is a no-op
      // when there's nothing to expire, so this never adds meaningful
      // overhead.
      name: "preview-expiry",
      run: async () => {
        try {
          const expired = await expireOldPreviews();
          if (expired > 0) {
            console.log(`[autopilot] preview-expiry: expired=${expired}`);
          }
        } catch (err) {
          console.error("[autopilot] preview-expiry: threw:", err);
        }
      },
    },
    {
      // Onboarding drip — sends pending T+1d and T+3d drip emails to new
      // users. The T+0 "welcome" email is sent immediately at registration
      // via src/routes/auth.tsx. This task handles the delayed emails.
      // Idempotent via the per-user `onboarding_emails_sent` jsonb column
      // (migration 0081). Silently skips when email is not configured.
      name: "onboarding-drip",
      run: async () => {
        try {
          const summary = await runOnboardingDripTaskOnce();
          if (summary.sent > 0 || summary.errors > 0) {
            console.log(
              `[autopilot] onboarding-drip: sent=${summary.sent} skipped=${summary.skipped} errors=${summary.errors}`
            );
          }
        } catch (err) {
          console.error("[autopilot] onboarding-drip: threw:", err);
        }
      },
    },
    {
      // Smart morning digest — AI-curated daily developer queue.
      // Fires once per day at 07:00 UTC (or whenever the 22h outer gate
      // next opens after 07:00). Per-user 20h cooldown in sendSmartDigest
      // ensures no user receives more than one digest per day even if the
      // outer gate fires multiple times. Requires ANTHROPIC_API_KEY but
      // degrades gracefully to a rule-based prioritisation when unset.
      name: "smart-digest",
      run: async () => {
        const now = Date.now();
        const nowDate = new Date(now);
        // Only fire at hour=7 UTC or if last run was >22h ago (catch-up)
        const isDigestHour = nowDate.getUTCHours() === 7;
        const pastCooldown = now - _lastSmartDigestAt >= SMART_DIGEST_INTERVAL_MS;
        if (!isDigestHour && !pastCooldown) return;
        _lastSmartDigestAt = now;
        try {
          await sendSmartDigestsToAll();
          console.log("[autopilot] smart-digest: completed");
        } catch (err) {
          console.error("[autopilot] smart-digest: threw:", err);
        }
      },
    },
  ];
}

// ---------------------------------------------------------------------------
// BLOCK S4 — synthetic-monitor task
// ---------------------------------------------------------------------------

export interface SyntheticMonitorTaskDeps {
  /** Override the suite runner (DI for tests). */
  runChecks?: () => Promise<SyntheticCheckResult[]>;
  /** Override the persistence step (DI for tests). */
  persist?: (results: SyntheticCheckResult[]) => Promise<void>;
  /** Override the previous-state loader (DI for tests). */
  loadPrevious?: () => Promise<Record<string, SyntheticCheckResult>>;
  /** Override the webhook poster (DI for tests). */
  postAlert?: (url: string, payload: unknown) => Promise<void>;
  /** Override the alert-webhook URL lookup (defaults to env). */
  alertUrl?: () => string;
}

export interface SyntheticMonitorTaskSummary {
  green: number;
  red: number;
  yellow: number;
  transitions: number;
}

async function defaultPostAlert(
  url: string,
  payload: unknown
): Promise<void> {
  try {
    await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
  } catch (err) {
    console.error("[autopilot] synthetic-monitor: alert webhook failed:", err);
  }
}

/**
 * One iteration of the synthetic-monitor task. Runs the checks, persists
 * them, compares against the prior state, and fires a webhook on each
 * green->red transition (red->red repeats stay quiet so we don't spam
 * the channel). Never throws.
 */
export async function runSyntheticMonitorTaskOnce(
  deps: SyntheticMonitorTaskDeps = {}
): Promise<SyntheticMonitorTaskSummary> {
  const runChecks = deps.runChecks ?? (() => runSyntheticChecks());
  const persist = deps.persist ?? persistChecks;
  const loadPrevious =
    deps.loadPrevious ??
    (async () => {
      const latest = await latestStatusByCheck();
      // Strip the `checkedAt` from the result shape so the diff loop
      // compares the canonical SyntheticCheckResult fields only.
      const out: Record<string, SyntheticCheckResult> = {};
      for (const [k, v] of Object.entries(latest)) {
        const { checkedAt: _unused, ...rest } = v;
        void _unused;
        out[k] = rest;
      }
      return out;
    });
  const postAlert = deps.postAlert ?? defaultPostAlert;
  const alertUrl =
    deps.alertUrl ?? (() => process.env.MONITOR_ALERT_WEBHOOK_URL || "");

  let previous: Record<string, SyntheticCheckResult> = {};
  try {
    previous = await loadPrevious();
  } catch (err) {
    console.error(
      "[autopilot] synthetic-monitor: loadPrevious threw:",
      err
    );
    previous = {};
  }

  const results = await runChecks();
  await persist(results);

  let green = 0;
  let red = 0;
  let yellow = 0;
  let transitions = 0;
  const url = alertUrl();

  for (const r of results) {
    if (r.status === "green") green += 1;
    else if (r.status === "red") red += 1;
    else yellow += 1;

    const prior = previous[r.name];
    // green->red transition: prior was green (or absent and current is red
    // after a green is also a transition — but absent-before is treated as
    // green to avoid spamming on a fresh DB). We only alert on the
    // green->red edge so red->red doesn't re-fire.
    const priorWasGreen = !prior || prior.status === "green";
    if (priorWasGreen && r.status === "red") {
      transitions += 1;
      if (url) {
        await postAlert(url, {
          check: r.name,
          status: r.status,
          statusCode: r.statusCode ?? null,
          durationMs: r.durationMs,
          error: r.error ?? null,
          checkedAt: new Date().toISOString(),
        });
      }
    }
  }

  return { green, red, yellow, transitions };
}

// ---------------------------------------------------------------------------
// L1 — sleep-mode-digest
// ---------------------------------------------------------------------------

export interface SleepModeDigestCandidate {
  userId: string;
  digestHourUtc: number;
  /** Independent cooldown anchor for the sleep-mode digest (migration 0077). */
  lastSleepDigestSentAt: Date | null;
}

export interface SleepModeDigestTaskDeps {
  /** Override the candidate finder. */
  findCandidates?: (cap: number) => Promise<SleepModeDigestCandidate[]>;
  /** Override the send-one-user helper (DI for tests). */
  sendOne?: (userId: string) => Promise<{ ok: boolean; reason?: string }>;
  /** Override the wall clock (DI for tests). */
  now?: () => Date;
  /** Override the per-tick cap. */
  cap?: number;
  /** Override the cooldown hours. */
  cooldownHours?: number;
}

export interface SleepModeDigestTaskSummary {
  sent: number;
  skipped: number;
}

/**
 * Default candidate-finder. Returns enabled users whose
 * `lastSleepDigestSentAt` is older than the cooldown OR null. The hour-match
 * filter is applied in JS by `runSleepModeDigestTaskOnce` so it stays
 * timezone-independent of any SQL `extract(hour ...)` behaviour.
 * Uses the dedicated `last_sleep_digest_sent_at` column (migration 0077) so
 * the cooldown is independent of the weekly digest timer.
 */
async function defaultFindSleepModeCandidates(
  cap: number
): Promise<SleepModeDigestCandidate[]> {
  try {
    const rows = await db
      .select({
        userId: users.id,
        digestHourUtc: users.sleepModeDigestHourUtc,
        lastSleepDigestSentAt: users.lastSleepDigestSentAt,
      })
      .from(users)
      .where(eq(users.sleepModeEnabled, true))
      .limit(cap);
    return rows.map((r) => ({
      userId: r.userId,
      digestHourUtc: r.digestHourUtc,
      lastSleepDigestSentAt: r.lastSleepDigestSentAt,
    }));
  } catch (err) {
    console.error("[autopilot] sleep-mode-digest: candidate query failed:", err);
    return [];
  }
}

/**
 * One iteration of the sleep-mode-digest task. Never throws.
 *
 * Per-user filters (applied in JS so we can DI a clock):
 *   1. `lastSleepDigestSentAt` is null OR older than cooldown (23h).
 *   2. `now.getUTCHours() === digestHourUtc` — fires once at the user's
 *      configured local UTC hour.
 *
 * Caps at `SLEEP_MODE_USER_CAP_PER_TICK` (100) users per tick.
 */
export async function runSleepModeDigestTaskOnce(
  deps: SleepModeDigestTaskDeps = {}
): Promise<SleepModeDigestTaskSummary> {
  const findCandidates =
    deps.findCandidates ?? defaultFindSleepModeCandidates;
  const sendOne = deps.sendOne ?? sendSleepModeDigestForUser;
  const now = deps.now ?? (() => new Date());
  const cap = deps.cap ?? SLEEP_MODE_USER_CAP_PER_TICK;
  const cooldownHours = deps.cooldownHours ?? SLEEP_MODE_COOLDOWN_HOURS;

  let candidates: SleepModeDigestCandidate[] = [];
  try {
    candidates = await findCandidates(cap);
  } catch (err) {
    console.error("[autopilot] sleep-mode-digest: findCandidates threw:", err);
    return { sent: 0, skipped: 0 };
  }

  const nowDate = now();
  const currentHour = nowDate.getUTCHours();
  const cooldownMs = cooldownHours * 60 * 60 * 1000;

  let sent = 0;
  let skipped = 0;

  for (const cand of candidates) {
    try {
      // Hour-match: must equal the user's configured UTC delivery hour.
      if (cand.digestHourUtc !== currentHour) {
        skipped += 1;
        continue;
      }
      // Cooldown: skip if we sent within the last cooldown window.
      if (
        cand.lastSleepDigestSentAt &&
        nowDate.getTime() - new Date(cand.lastSleepDigestSentAt).getTime() <
          cooldownMs
      ) {
        skipped += 1;
        continue;
      }
      const result = await sendOne(cand.userId);
      if (result.ok) sent += 1;
      else skipped += 1;
    } catch (err) {
      skipped += 1;
      console.error(
        `[autopilot] sleep-mode-digest: per-user failure for user=${cand.userId}:`,
        err
      );
    }
  }

  return { sent, skipped };
}

// ---------------------------------------------------------------------------
// M3 — pr-risk-rescore
// ---------------------------------------------------------------------------

export interface PrRiskRescoreCandidate {
  pullRequestId: string;
  headBranch: string;
  updatedAt: Date;
}

export interface PrRiskRescoreTaskDeps {
  /** Override candidate finder for tests. */
  findCandidates?: (
    lookbackHours: number,
    cap: number
  ) => Promise<PrRiskRescoreCandidate[]>;
  /** Override score computation for tests. */
  scoreOne?: (prId: string) => Promise<{ ok: boolean }>;
  /** Override per-tick cap. */
  cap?: number;
  /** Override lookback. */
  lookbackHours?: number;
}

export interface PrRiskRescoreTaskSummary {
  scored: number;
  skipped: number;
}

/**
 * Default candidate-finder. Returns open, non-draft PRs from non-archived
 * repos whose `updated_at` falls inside the lookback window. The "scored
 * at all" filter is applied as a second pass via `defaultFilterNeedsScoring`.
 */
async function defaultFindPrRiskCandidates(
  lookbackHours: number,
  cap: number
): Promise<PrRiskRescoreCandidate[]> {
  const cutoff = new Date(Date.now() - lookbackHours * 60 * 60 * 1000);
  try {
    const rows = await db
      .select({
        pullRequestId: pullRequests.id,
        headBranch: pullRequests.headBranch,
        updatedAt: pullRequests.updatedAt,
      })
      .from(pullRequests)
      .innerJoin(
        repositories,
        eq(repositories.id, pullRequests.repositoryId)
      )
      .where(
        and(
          eq(pullRequests.state, "open"),
          eq(pullRequests.isDraft, false),
          eq(repositories.isArchived, false),
          gte(pullRequests.updatedAt, cutoff)
        )
      )
      .orderBy(sql`${pullRequests.updatedAt} DESC`)
      .limit(cap);
    return rows.map((r) => ({
      pullRequestId: r.pullRequestId,
      headBranch: r.headBranch,
      updatedAt: r.updatedAt,
    }));
  } catch (err) {
    console.error("[autopilot] pr-risk-rescore: candidate query failed:", err);
    return [];
  }
}

/**
 * Drop candidates that already have ANY cached score row. The unique
 * constraint on (pull_request_id, commit_sha) handles the "score-the-
 * same-SHA-twice" case at persist time; this filter just keeps the work
 * list small enough to fit under the per-tick cap when many PRs are
 * being pushed concurrently.
 */
async function defaultFilterNeedsScoring(
  candidates: PrRiskRescoreCandidate[]
): Promise<PrRiskRescoreCandidate[]> {
  if (candidates.length === 0) return [];
  try {
    const rows = await db
      .select({ pullRequestId: prRiskScores.pullRequestId })
      .from(prRiskScores);
    const scoredIds = new Set(rows.map((r) => r.pullRequestId));
    return candidates.filter((c) => !scoredIds.has(c.pullRequestId));
  } catch (err) {
    console.error("[autopilot] pr-risk-rescore: filter query failed:", err);
    // Fail-open: better to score everything than silently skip.
    return candidates;
  }
}

/**
 * One iteration of the pr-risk-rescore task. Never throws. Compute risk
 * for up to `cap` recently-touched open PRs that have no cached score
 * yet, so reviewers usually see a populated card on first visit.
 */
export async function runPrRiskRescoreTaskOnce(
  deps: PrRiskRescoreTaskDeps = {}
): Promise<PrRiskRescoreTaskSummary> {
  const findCandidates = deps.findCandidates ?? defaultFindPrRiskCandidates;
  const scoreOne =
    deps.scoreOne ??
    (async (prId: string) => {
      try {
        const result = await computePrRiskForPullRequest(prId);
        return { ok: result !== null };
      } catch {
        return { ok: false };
      }
    });
  const cap = deps.cap ?? PR_RISK_RESCORE_MAX_PER_TICK;
  const lookbackHours =
    deps.lookbackHours ?? PR_RISK_RESCORE_LOOKBACK_HOURS;

  let candidates: PrRiskRescoreCandidate[] = [];
  try {
    candidates = await findCandidates(lookbackHours, cap);
  } catch (err) {
    console.error("[autopilot] pr-risk-rescore: findCandidates threw:", err);
    return { scored: 0, skipped: 0 };
  }

  // Only score PRs missing a cached row. Skip filter when the caller
  // injected a custom finder (tests pass already-filtered lists).
  const needsScoring =
    deps.findCandidates === undefined
      ? await defaultFilterNeedsScoring(candidates)
      : candidates;

  let scored = 0;
  let skipped = 0;
  for (const cand of needsScoring.slice(0, cap)) {
    try {
      const result = await scoreOne(cand.pullRequestId);
      if (result.ok) scored += 1;
      else skipped += 1;
    } catch (err) {
      skipped += 1;
      console.error(
        `[autopilot] pr-risk-rescore: per-PR failure for pr=${cand.pullRequestId}:`,
        err
      );
    }
  }
  if (needsScoring.length > cap) {
    skipped += needsScoring.length - cap;
  }

  return { scored, skipped };
}

// ---------------------------------------------------------------------------
// K3 — auto-merge-sweep
// ---------------------------------------------------------------------------

interface SweepCandidate {
  prId: string;
  prNumber: number;
  prTitle: string;
  prBody: string | null;
  baseBranch: string;
  headBranch: string;
  isDraft: boolean;
  repositoryId: string;
  authorUserId: string;
  ownerUsername: string | null;
  repoName: string;
  state: string;
}

export interface AutoMergeSweepDeps {
  /** Inject candidate-finder for tests. */
  findCandidates?: (lookbackHours: number, limit: number) => Promise<SweepCandidate[]>;
  /** Inject evaluator for tests. */
  evaluate?: (ctx: AutoMergeContext) => Promise<AutoMergeDecision>;
  /** Inject the merge executor for tests. */
  merge?: (cand: SweepCandidate) => Promise<PerformMergeResult>;
  /** Inject the audit-recording side-effect for tests. */
  recordAttempt?: (
    repoId: string,
    prId: string,
    decision: AutoMergeDecision
  ) => Promise<void>;
  /** Inject the audit/comment side-effects for the merged path (tests). */
  onMerged?: (
    cand: SweepCandidate,
    result: PerformMergeResult
  ) => Promise<void>;
  /** Inject the audit side-effect for the merge-failed path (tests). */
  onMergeFailed?: (cand: SweepCandidate, error: string) => Promise<void>;
  /** Inject the AI-key short-circuit signal for tests. */
  shouldShortCircuitAi?: (cand: SweepCandidate) => Promise<boolean>;
}

export interface AutoMergeSweepSummary {
  evaluated: number;
  merged: number;
  blocked: number;
}

/**
 * Default candidate-finder. Selects open, non-draft PRs from non-archived
 * repos whose `updated_at` is within the lookback window. Joins repo +
 * owner so the merge executor doesn't need extra round trips. Cap is
 * enforced at the SQL layer.
 */
async function defaultFindAutoMergeCandidates(
  lookbackHours: number,
  limit: number
): Promise<SweepCandidate[]> {
  const cutoff = new Date(Date.now() - lookbackHours * 60 * 60 * 1000);
  try {
    const rows = await db
      .select({
        prId: pullRequests.id,
        prNumber: pullRequests.number,
        prTitle: pullRequests.title,
        prBody: pullRequests.body,
        baseBranch: pullRequests.baseBranch,
        headBranch: pullRequests.headBranch,
        isDraft: pullRequests.isDraft,
        repositoryId: pullRequests.repositoryId,
        authorUserId: pullRequests.authorId,
        ownerUsername: users.username,
        repoName: repositories.name,
        state: pullRequests.state,
      })
      .from(pullRequests)
      .innerJoin(
        repositories,
        eq(repositories.id, pullRequests.repositoryId)
      )
      .leftJoin(users, eq(users.id, repositories.ownerId))
      .where(
        and(
          eq(pullRequests.state, "open"),
          eq(pullRequests.isDraft, false),
          eq(repositories.isArchived, false),
          gte(pullRequests.updatedAt, cutoff)
        )
      )
      .limit(limit);
    return rows.map((r) => ({
      prId: r.prId,
      prNumber: r.prNumber,
      prTitle: r.prTitle,
      prBody: r.prBody,
      baseBranch: r.baseBranch,
      headBranch: r.headBranch,
      isDraft: r.isDraft,
      repositoryId: r.repositoryId,
      authorUserId: r.authorUserId,
      ownerUsername: r.ownerUsername ?? null,
      repoName: r.repoName,
      state: r.state,
    }));
  } catch (err) {
    console.error("[autopilot] auto-merge: candidate query failed:", err);
    return [];
  }
}

/**
 * Determine whether the matched branch_protection rule on this PR
 * requires AI approval but no `ANTHROPIC_API_KEY` is configured. In that
 * case the AI-approval check would inevitably fail downstream, so we
 * short-circuit to a "blocked" decision without invoking `evaluateAutoMerge`
 * — keeps the log readable and prevents misleading "AI review unavailable"
 * lines in the audit trail.
 */
async function defaultShouldShortCircuitAi(
  cand: SweepCandidate
): Promise<boolean> {
  if (process.env.ANTHROPIC_API_KEY) return false;
  try {
    const rule = await matchProtection(cand.repositoryId, cand.baseBranch);
    return !!(rule && rule.requireAiApproval);
  } catch {
    return false;
  }
}

/**
 * Default success-path: post an `auto_merge.merged` audit row + a stable
 * marker comment on the PR so a partial-merge retry doesn't double-post.
 * Both are best-effort; failures are logged not thrown.
 */
async function defaultOnMerged(
  cand: SweepCandidate,
  result: PerformMergeResult
): Promise<void> {
  try {
    await audit({
      repositoryId: cand.repositoryId,
      action: "auto_merge.merged",
      targetType: "pull_request",
      targetId: cand.prId,
      metadata: {
        prNumber: cand.prNumber,
        baseBranch: cand.baseBranch,
        headBranch: cand.headBranch,
        closedIssueNumbers: result.closedIssueNumbers,
        resolvedFiles: result.resolvedFiles,
      },
    });
  } catch (err) {
    console.error("[autopilot] auto-merge: merged audit failed:", err);
  }
  try {
    const commentAuthorId = await getBotUserIdOrFallback(cand.authorUserId);
    await db.insert(prComments).values({
      pullRequestId: cand.prId,
      authorId: commentAuthorId,
      isAiReview: true,
      body: `${AUTO_MERGE_COMMENT_MARKER}\nAuto-merged by Gluecron autopilot — branch protection conditions satisfied.`,
    });
  } catch (err) {
    console.error("[autopilot] auto-merge: comment insert failed:", err);
  }
}

/** Default failure-path: only an audit row; no comment (we may retry). */
async function defaultOnMergeFailed(
  cand: SweepCandidate,
  error: string
): Promise<void> {
  try {
    await audit({
      repositoryId: cand.repositoryId,
      action: "auto_merge.merge_failed",
      targetType: "pull_request",
      targetId: cand.prId,
      metadata: {
        prNumber: cand.prNumber,
        baseBranch: cand.baseBranch,
        headBranch: cand.headBranch,
        error,
      },
    });
  } catch (err) {
    console.error("[autopilot] auto-merge: merge_failed audit failed:", err);
  }
}

/**
 * Execute one sweep over recently-updated open PRs. For each, evaluate
 * with K2's `evaluateAutoMerge`; on `merge: true`, call `performMerge` and
 * record the merged/merge-failed audit row + comment. Always record the
 * `auto_merge.evaluated` audit row via `recordAutoMergeAttempt`.
 *
 * Returns a counts summary that the autopilot prints as the tick log line.
 * Never throws.
 */
export async function runAutoMergeSweep(
  deps: AutoMergeSweepDeps = {}
): Promise<AutoMergeSweepSummary> {
  const findCandidates = deps.findCandidates ?? defaultFindAutoMergeCandidates;
  const evaluate =
    deps.evaluate ?? ((ctx) => evaluateAutoMerge(ctx, {}));
  const merge =
    deps.merge ??
    (async (cand) => {
      if (!cand.ownerUsername) {
        return {
          ok: false,
          error: "owner username unresolved",
          closedIssueNumbers: [],
          resolvedFiles: [],
        };
      }
      return performMerge({
        pr: {
          id: cand.prId,
          number: cand.prNumber,
          title: cand.prTitle,
          body: cand.prBody,
          baseBranch: cand.baseBranch,
          headBranch: cand.headBranch,
          repositoryId: cand.repositoryId,
          authorId: cand.authorUserId,
          state: cand.state as "open",
          isDraft: cand.isDraft,
        },
        ownerName: cand.ownerUsername,
        repoName: cand.repoName,
        actorUserId: cand.authorUserId,
      });
    });
  const recordAttempt = deps.recordAttempt ?? recordAutoMergeAttempt;
  const onMerged = deps.onMerged ?? defaultOnMerged;
  const onMergeFailed = deps.onMergeFailed ?? defaultOnMergeFailed;
  const shouldShortCircuitAi =
    deps.shouldShortCircuitAi ?? defaultShouldShortCircuitAi;

  let candidates: SweepCandidate[] = [];
  try {
    candidates = await findCandidates(
      AUTO_MERGE_LOOKBACK_HOURS,
      AUTO_MERGE_MAX_PER_TICK
    );
  } catch (err) {
    console.error("[autopilot] auto-merge: findCandidates threw:", err);
    return { evaluated: 0, merged: 0, blocked: 0 };
  }

  let evaluated = 0;
  let merged = 0;
  let blocked = 0;

  for (const cand of candidates) {
    try {
      evaluated += 1;

      // AI-key short-circuit: if the rule requires AI approval and we have
      // no key, treat as blocked without calling the evaluator (which would
      // log a misleading "AI review unavailable").
      let decision: AutoMergeDecision;
      if (await shouldShortCircuitAi(cand)) {
        decision = {
          merge: false,
          reason:
            "Branch protection requires AI approval but ANTHROPIC_API_KEY is unset.",
          blocking: [
            "ANTHROPIC_API_KEY missing; AI approval cannot be sourced.",
          ],
        };
      } else {
        decision = await evaluate({
          pullRequestId: cand.prId,
          repositoryId: cand.repositoryId,
          baseBranch: cand.baseBranch,
          isDraft: cand.isDraft,
          authorUserId: cand.authorUserId,
        });
      }

      // Always record the evaluation, regardless of outcome.
      try {
        await recordAttempt(cand.repositoryId, cand.prId, decision);
      } catch (err) {
        console.error(
          `[autopilot] auto-merge: recordAttempt failed for pr=${cand.prId}:`,
          err
        );
      }

      if (!decision.merge) {
        blocked += 1;
        continue;
      }

      // Perform the actual merge.
      const result = await merge(cand);
      if (result.ok) {
        merged += 1;
        await onMerged(cand, result);
      } else {
        blocked += 1;
        await onMergeFailed(cand, result.error || "unknown merge error");
      }
    } catch (err) {
      blocked += 1;
      console.error(
        `[autopilot] auto-merge: per-PR failure for pr=${cand.prId}:`,
        err
      );
    }
  }

  console.log(
    `[autopilot] auto-merge: evaluated=${evaluated} merged=${merged} blocked=${blocked}`
  );

  return { evaluated, merged, blocked };
}

/**
 * Visits each distinct (repo, base_branch) that has queued rows and logs a
 * stub depth line. The actual gate-running + merge happens in the pulls
 * route; this tick is just a heartbeat so we can wire per-queue progress
 * through without duplicating merge logic.
 */
async function processMergeQueues(): Promise<void> {
  let distinct: Array<{ repositoryId: string; baseBranch: string }> = [];
  try {
    const rows = await db
      .selectDistinct({
        repositoryId: mergeQueueEntries.repositoryId,
        baseBranch: mergeQueueEntries.baseBranch,
      })
      .from(mergeQueueEntries)
      .where(sql`${mergeQueueEntries.state} IN ('queued','running')`);
    distinct = rows;
  } catch (err) {
    console.error("[autopilot] merge-queue: distinct query failed:", err);
    return;
  }
  for (const d of distinct) {
    try {
      const head = await peekHead(d.repositoryId, d.baseBranch);
      if (head) {
        console.log(
          `[autopilot] merge queue depth head=${head.id.slice(0, 8)} repo=${d.repositoryId.slice(0, 8)} base=${d.baseBranch}`
        );
      }
    } catch (err) {
      console.error(
        `[autopilot] merge-queue: peek failed for repo=${d.repositoryId}:`,
        err
      );
    }
  }
}

/**
 * Pick a small batch of repos that actually have dep rows and re-run
 * advisory scan against them. Cheap — one SELECT DISTINCT with LIMIT.
 */
async function rescanAdvisoriesBatch(limit: number): Promise<void> {
  let repoIds: string[] = [];
  try {
    const rows = await db
      .selectDistinct({ repositoryId: repoDependencies.repositoryId })
      .from(repoDependencies)
      .limit(limit);
    repoIds = rows.map((r) => r.repositoryId);
  } catch (err) {
    console.error("[autopilot] advisory-rescan: query failed:", err);
    return;
  }
  for (const id of repoIds) {
    try {
      await scanRepositoryForAlerts(id);
    } catch (err) {
      console.error(
        `[autopilot] advisory-rescan: scan failed for repo=${id}:`,
        err
      );
    }
  }
}

/** Resolve the tick interval from env → opts → default. */
function resolveIntervalMs(optsMs?: number): number {
  if (typeof optsMs === "number" && optsMs > 0) return optsMs;
  const raw = process.env.AUTOPILOT_INTERVAL_MS;
  if (raw) {
    const parsed = Number(raw);
    if (Number.isFinite(parsed) && parsed > 0) return parsed;
  }
  return DEFAULT_INTERVAL_MS;
}

/**
 * Start the recurring autopilot loop. No-op when AUTOPILOT_DISABLED=1.
 * The first tick fires after `intervalMs`, not immediately, to keep boot
 * fast. Returns a `stop()` that clears the interval.
 */
export function startAutopilot(opts?: StartAutopilotOpts): { stop: () => void } {
  if (process.env.AUTOPILOT_DISABLED === "1") {
    return { stop: () => {} };
  }
  const intervalMs = resolveIntervalMs(opts?.intervalMs);
  const tasks = opts?.tasks ?? defaultTasks();
  let running = false;
  const handle = setInterval(() => {
    if (running) return;
    running = true;
    void runAutopilotTick({ tasks, now: opts?.now })
      .catch(() => {
        // runAutopilotTick already never throws, but belt-and-braces.
      })
      .finally(() => {
        running = false;
      });
  }, intervalMs);
  return {
    stop: () => clearInterval(handle),
  };
}

/** Last tick snapshot for observability. Module-level, swap-on-complete. */
let lastTick: AutopilotTickResult | null = null;
let tickCount = 0;

/** Return the most recent completed tick, or null if autopilot hasn't run yet. */
export function getLastTick(): AutopilotTickResult | null {
  return lastTick;
}

/** Return the total number of completed ticks in this process. */
export function getTickCount(): number {
  return tickCount;
}

/**
 * Run one tick: invokes every sub-task with its own try/catch, records a
 * per-task result, and emits a single summary line. Never throws.
 */
export async function runAutopilotTick(
  opts?: RunTickOpts
): Promise<AutopilotTickResult> {
  const now = opts?.now ?? Date.now;
  const tasks = opts?.tasks ?? defaultTasks();
  const startedAt = new Date(now()).toISOString();
  const results: AutopilotTaskResult[] = [];
  for (const t of tasks) {
    const t0 = now();
    try {
      await t.run();
      results.push({ name: t.name, ok: true, durationMs: now() - t0 });
    } catch (err) {
      const message =
        err instanceof Error ? err.message : String(err ?? "unknown error");
      console.error(`[autopilot] ${t.name}: ${message}`);
      results.push({
        name: t.name,
        ok: false,
        durationMs: now() - t0,
        error: message,
      });
    }
  }
  const finishedAt = new Date(now()).toISOString();
  const totalMs = results.reduce((a, r) => a + r.durationMs, 0);
  const okCount = results.filter((r) => r.ok).length;
  console.log(
    `[autopilot] tick ok tasks=${okCount}/${results.length} ms=${totalMs}`
  );
  const result: AutopilotTickResult = { startedAt, finishedAt, tasks: results };
  lastTick = result;
  tickCount += 1;
  return result;
}

/** Exposed for unit tests. */
export const __test = {
  resolveIntervalMs,
  processMergeQueues,
  rescanAdvisoriesBatch,
  DEFAULT_INTERVAL_MS,
  ADVISORY_RESCAN_BATCH,
  AUTO_MERGE_LOOKBACK_HOURS,
  AUTO_MERGE_MAX_PER_TICK,
  AUTO_MERGE_COMMENT_MARKER,
  PR_RISK_RESCORE_MAX_PER_TICK,
  PR_RISK_RESCORE_LOOKBACK_HOURS,
  defaultFindAutoMergeCandidates,
  defaultOnMerged,
  defaultOnMergeFailed,
  defaultShouldShortCircuitAi,
  defaultFindPrRiskCandidates,
  defaultFilterNeedsScoring,
};