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
ai-ci-healer.ts21.2 KB · 701 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
/**
 * AI CI Healer — autonomous failure → root-cause → patch PR loop.
 *
 * When a `workflow_runs` row lands in status="failure", this module:
 *   1. Pulls the run + all its `workflow_jobs` (especially the failed ones'
 *      `logs` column).
 *   2. Asks Claude to identify the root cause + whether it's fixable from
 *      inside this repo.
 *   3. If patchable, hands the suggested fixes off to the existing
 *      `generatePatchForGateTestFinding` (the finding-shape maps cleanly
 *      onto its `GateTestFinding[]` API — both surfaces want
 *      `{ path, description, severity }`).
 *   4. Records an `ai.ci.healed` or `ai.ci.gave_up` audit row keyed on the
 *      run id so the autopilot poller doesn't re-process the same failure
 *      every 5 minutes.
 *
 * Degrades silently when ANTHROPIC_API_KEY is unset (autopilot also gates
 * on the env var, but the lib double-checks so it's safe to call directly).
 * Everything is wrapped in try/catch — `analyzeFailedWorkflowRun` returns
 * `null` rather than throwing on any failure.
 *
 * Marker convention:
 *   - Successful patch open  → audit action `ai.ci.healed`, targetId = runId.
 *   - Claude says unfixable  → audit action `ai.ci.gave_up`, targetId = runId.
 * The autopilot poller skips any run that already has either marker, so we
 * never retry forever.
 */

import { and, desc, eq, gte, lt, sql } from "drizzle-orm";
import type Anthropic from "@anthropic-ai/sdk";
import { db } from "../db";
import {
  auditLog,
  repositories,
  workflowJobs,
  workflowRuns,
  workflows,
} from "../db/schema";
import {
  MODEL_SONNET,
  extractText,
  getAnthropic,
  isAiAvailable,
  parseJsonResponse,
} from "./ai-client";
import { audit } from "./notify";
import {
  generatePatchForGateTestFinding,
  type GateTestFinding,
} from "./ai-patch-generator";
import { assertAiQuota, AiQuotaExceededError } from "./billing";

// ---------------------------------------------------------------------------
// Tunables
// ---------------------------------------------------------------------------

/** Cap per-job log slice we ship to Claude — protect the prompt budget. */
const LOG_SNIPPET_BYTES = 8 * 1024;

/** Hard cap on runs processed per autopilot tick — runaway protection. */
const HEAL_CAP_PER_TICK = 5;

/** Only consider runs that finished at least this long ago. Gives the
 *  workflow runner time to flush logs + final job rows before we sample. */
const HEAL_MIN_AGE_MS = 60 * 1_000;

/** Don't bother healing ancient failures — older than this and we assume
 *  the human has already triaged or the SHA has been rewritten. */
const HEAL_MAX_AGE_MS = 24 * 60 * 60 * 1_000;

// ---------------------------------------------------------------------------
// Public surface
// ---------------------------------------------------------------------------

export interface SuggestedFix {
  /** Relative path inside the repo that the AI thinks needs touching. */
  path: string;
  /** What's wrong / what the fix should look like (one-liner). */
  description: string;
  /** Severity inherited from the AI's confidence call. */
  severity?: "low" | "medium" | "high" | "critical";
}

export interface CiHealAnalysis {
  /** Plain-English root cause, 1-3 sentences. */
  rootCause: string;
  /** Concrete fix proposals (may be empty if Claude can't pinpoint files). */
  suggestedFixes: SuggestedFix[];
  /** Convenience: the paths from `suggestedFixes` deduped. */
  patchablePaths: string[];
}

export interface CiHealerTickSummary {
  considered: number;
  healed: number;
  gaveUp: number;
  skipped: number;
}

/**
 * Claude's response shape. Kept loose so we tolerate minor schema drift.
 */
interface ClaudeCiResponse {
  rootCause?: string;
  fixable?: boolean;
  suggestedFixes?: Array<{
    path?: string;
    description?: string;
    severity?: string;
  }>;
  /** Optional: Claude's reason it gave up. We just persist it for ops. */
  unfixableReason?: string;
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function truncate(s: string | null | undefined, max: number): string {
  if (!s) return "";
  if (s.length <= max) return s;
  return s.slice(0, max) + "\n…(truncated)";
}

function normaliseSeverity(s: unknown): SuggestedFix["severity"] | undefined {
  if (typeof s !== "string") return undefined;
  const v = s.toLowerCase();
  if (v === "low" || v === "medium" || v === "high" || v === "critical") {
    return v;
  }
  return undefined;
}

/**
 * Map our AI-derived `SuggestedFix` set onto the
 * `GateTestFinding[]` shape that `generatePatchForGateTestFinding`
 * already accepts. The patch generator only needs `{path, description,
 * severity}` — exactly what we already have. Each fix becomes one
 * candidate finding; the generator stops at the first one that produces a
 * non-empty patch set so a bad suggestion doesn't drown a good one.
 */
export function fixesToFindings(
  fixes: SuggestedFix[],
  runShortId: string
): GateTestFinding[] {
  return fixes
    .filter((f) => f.path && f.path.trim().length > 0)
    .map((f, i) => ({
      id: `ci-heal-${runShortId}-${i}`,
      ruleId: "ci-failure",
      path: f.path.trim(),
      severity: f.severity || "high",
      title: "CI failure auto-heal",
      description: f.description || "CI failure",
    }));
}

/**
 * Build the Claude prompt. Pure function so tests can pin the shape.
 */
export function buildCiHealPrompt(args: {
  repoFullName: string;
  commitSha: string;
  workflowYaml: string;
  failedJobs: Array<{ name: string; conclusion: string | null; logs: string }>;
}): string {
  const jobsBlock = args.failedJobs
    .map(
      (j) =>
        `### Job: ${j.name} (${j.conclusion || "failure"})\n\`\`\`\n${truncate(
          j.logs,
          LOG_SNIPPET_BYTES
        )}\n\`\`\``
    )
    .join("\n\n");
  return [
    "You are GlueCron's CI healer. A workflow run just failed. Decide whether the failure is a code bug fixable in THIS repository, and if so propose concrete file edits.",
    "",
    `**Repository:** ${args.repoFullName}`,
    `**Commit:** ${args.commitSha.slice(0, 12)}`,
    "",
    "## Workflow YAML",
    "```yaml",
    truncate(args.workflowYaml, 4_000),
    "```",
    "",
    "## Failed job logs",
    jobsBlock || "(no failed-job logs available)",
    "",
    "Respond ONLY with JSON of this exact shape:",
    "{",
    '  "rootCause": "1-3 sentence diagnosis (what failed, why)",',
    '  "fixable": true | false,',
    '  "suggestedFixes": [',
    '    { "path": "src/foo.ts", "description": "what to change", "severity": "high" }',
    "  ],",
    '  "unfixableReason": "(only if fixable=false) why the human must intervene"',
    "}",
    "",
    "Rules:",
    "- `fixable` MUST be false if the failure is an env/infra/external-service problem (missing secret, registry down, network, GitHub Actions runner image, etc.) — anything you can't fix by editing files in this repo.",
    "- `suggestedFixes` must be empty when fixable=false.",
    "- Only suggest paths you can identify with high confidence from the logs or YAML. Do not guess at random files.",
    "- Keep `description` short — the patch generator will be invoked with this finding to produce the actual diff.",
  ].join("\n");
}

interface FailedJobRow {
  name: string;
  conclusion: string | null;
  logs: string;
}

async function loadFailedJobs(runId: string): Promise<FailedJobRow[]> {
  try {
    const rows = await db
      .select({
        name: workflowJobs.name,
        conclusion: workflowJobs.conclusion,
        logs: workflowJobs.logs,
        status: workflowJobs.status,
      })
      .from(workflowJobs)
      .where(eq(workflowJobs.runId, runId));
    return rows
      .filter((r) => r.status === "failure" || r.conclusion === "failure")
      .map((r) => ({
        name: r.name,
        conclusion: r.conclusion,
        logs: r.logs || "",
      }));
  } catch (err) {
    console.error("[ai-ci-healer] loadFailedJobs failed:", err);
    return [];
  }
}

/**
 * Has this run already been processed (success or give-up)? We use the
 * audit log as the marker store so we don't need a schema change.
 */
async function hasMarker(runId: string): Promise<boolean> {
  try {
    const [row] = await db
      .select({ id: auditLog.id })
      .from(auditLog)
      .where(
        and(
          eq(auditLog.targetType, "workflow_run"),
          eq(auditLog.targetId, runId),
          sql`${auditLog.action} IN ('ai.ci.healed', 'ai.ci.gave_up')`
        )
      )
      .limit(1);
    return !!row;
  } catch (err) {
    console.warn("[ai-ci-healer] hasMarker query failed:", err);
    // Fail closed — if we can't check, skip to avoid duplicate work.
    return true;
  }
}

// ---------------------------------------------------------------------------
// analyzeFailedWorkflowRun — public entry point #1
// ---------------------------------------------------------------------------

export interface AnalyzeOptions {
  /** Test-only Anthropic client injection. */
  client?: Pick<Anthropic, "messages">;
}

/**
 * Diagnose a failed run. Returns `null` when:
 *   - The run doesn't exist or isn't actually a failure.
 *   - ANTHROPIC_API_KEY is unset AND no client was injected.
 *   - Claude says the failure isn't fixable from this repo (env/infra).
 *   - Any DB / network step blows up (logged, swallowed).
 */
export async function analyzeFailedWorkflowRun(
  runId: string,
  opts: AnalyzeOptions = {}
): Promise<CiHealAnalysis | null> {
  // Resolve client lazily — tests inject, production reads env.
  let client: Pick<Anthropic, "messages">;
  if (opts.client) {
    client = opts.client;
  } else {
    if (!isAiAvailable()) return null;
    try {
      client = getAnthropic();
    } catch {
      return null;
    }
  }

  // Load run row.
  let run: typeof workflowRuns.$inferSelect | null = null;
  try {
    const [row] = await db
      .select()
      .from(workflowRuns)
      .where(eq(workflowRuns.id, runId))
      .limit(1);
    run = row || null;
  } catch (err) {
    console.error("[ai-ci-healer] loadRun failed:", err);
    return null;
  }
  if (!run || run.status !== "failure") return null;

  // Load workflow + repo (for YAML + naming context).
  let workflowYaml = "";
  let repoFullName = "unknown/unknown";
  try {
    const [w] = await db
      .select({ yaml: workflows.yaml })
      .from(workflows)
      .where(eq(workflows.id, run.workflowId))
      .limit(1);
    if (w?.yaml) workflowYaml = w.yaml;
  } catch (err) {
    console.warn("[ai-ci-healer] load workflow failed:", err);
  }
  try {
    const [r] = await db
      .select({
        name: repositories.name,
        ownerId: repositories.ownerId,
      })
      .from(repositories)
      .where(eq(repositories.id, run.repositoryId))
      .limit(1);
    if (r) {
      repoFullName = `${r.ownerId.slice(0, 8)}/${r.name}`;
    }
  } catch (err) {
    console.warn("[ai-ci-healer] load repo failed:", err);
  }

  const failedJobs = await loadFailedJobs(runId);

  // Ask Claude.
  let parsed: ClaudeCiResponse | null = null;
  try {
    const message = await client.messages.create({
      model: MODEL_SONNET,
      max_tokens: 2048,
      messages: [
        {
          role: "user",
          content: buildCiHealPrompt({
            repoFullName,
            commitSha: run.commitSha || "(unknown)",
            workflowYaml,
            failedJobs,
          }),
        },
      ],
    });
    try {
      const { recordAiCost, extractUsage } = await import("./ai-cost-tracker");
      const usage = extractUsage(message);
      await recordAiCost({
        repositoryId: run.repositoryId ?? null,
        model: MODEL_SONNET,
        inputTokens: usage.input,
        outputTokens: usage.output,
        category: "ci_healer",
        sourceId: runId,
        sourceKind: "workflow_run",
      });
    } catch {
      /* swallow — best-effort */
    }
    parsed = parseJsonResponse<ClaudeCiResponse>(extractText(message));
  } catch (err) {
    console.warn(
      "[ai-ci-healer] Claude call failed:",
      err instanceof Error ? err.message : err
    );
    return null;
  }
  if (!parsed) return null;

  const rootCause =
    typeof parsed.rootCause === "string" && parsed.rootCause.trim()
      ? parsed.rootCause.trim()
      : "(no root cause provided)";

  // "Not fixable" branch — return null so the caller can mark `ai.ci.gave_up`.
  if (parsed.fixable === false) {
    return null;
  }

  const rawFixes = Array.isArray(parsed.suggestedFixes)
    ? parsed.suggestedFixes
    : [];
  const suggestedFixes: SuggestedFix[] = rawFixes
    .filter(
      (f): f is { path: string; description?: string; severity?: string } =>
        !!f && typeof f.path === "string" && f.path.trim().length > 0
    )
    .map((f) => ({
      path: f.path.trim(),
      description:
        typeof f.description === "string" && f.description.trim()
          ? f.description.trim()
          : rootCause,
      severity: normaliseSeverity(f.severity),
    }));

  // Claude said fixable but produced zero usable paths → treat as
  // unfixable so we don't loop.
  if (suggestedFixes.length === 0) return null;

  const patchablePaths = Array.from(new Set(suggestedFixes.map((f) => f.path)));

  return { rootCause, suggestedFixes, patchablePaths };
}

// ---------------------------------------------------------------------------
// healOneRun — drives one run end-to-end. Public so callers (autopilot,
// tests, manual retrigger) share the same pipeline.
// ---------------------------------------------------------------------------

export interface HealOneOptions extends AnalyzeOptions {
  /** Test override — pin the patch generator output. */
  generatePatch?: typeof generatePatchForGateTestFinding;
}

export interface HealOneResult {
  outcome: "healed" | "gave_up" | "skipped";
  prNumber?: number;
  branch?: string;
  reason?: string;
}

export async function healOneRun(
  runId: string,
  opts: HealOneOptions = {}
): Promise<HealOneResult> {
  if (process.env.AUTOPILOT_DISABLED === "1") {
    return { outcome: "skipped", reason: "autopilot disabled" };
  }
  if (!opts.client && !isAiAvailable()) {
    return { outcome: "skipped", reason: "ANTHROPIC_API_KEY missing" };
  }

  // Skip if already processed (audit marker present).
  if (await hasMarker(runId)) {
    return { outcome: "skipped", reason: "already processed" };
  }

  // Look up the run for audit metadata (repo + sha) and owner for quota check.
  let repositoryId: string | null = null;
  let commitSha: string | null = null;
  let repoOwnerId: string | null = null;
  try {
    const [row] = await db
      .select({
        repositoryId: workflowRuns.repositoryId,
        commitSha: workflowRuns.commitSha,
      })
      .from(workflowRuns)
      .where(eq(workflowRuns.id, runId))
      .limit(1);
    if (row) {
      repositoryId = row.repositoryId;
      commitSha = row.commitSha;
    }
  } catch (err) {
    console.warn("[ai-ci-healer] post-analyze run lookup failed:", err);
  }

  // Resolve repo owner for the quota check.
  if (repositoryId) {
    try {
      const [repoRow] = await db
        .select({ ownerId: repositories.ownerId })
        .from(repositories)
        .where(eq(repositories.id, repositoryId))
        .limit(1);
      if (repoRow) repoOwnerId = repoRow.ownerId;
    } catch {
      /* tolerate */
    }
  }

  // Hard quota gate — skip silently when the repo owner's AI budget is
  // exhausted. We don't fail the CI run; the autopilot marker is not written
  // so the healer will retry on the next tick once budget resets.
  if (repoOwnerId) {
    try {
      await assertAiQuota(repoOwnerId);
    } catch (err) {
      if (err instanceof AiQuotaExceededError) {
        console.log(
          `[ai-ci-healer] skipping run=${runId}: AI quota exceeded for owner=${repoOwnerId}`
        );
        return { outcome: "skipped", reason: "AI quota exceeded" };
      }
      // Unexpected error — log and proceed (fail open).
      console.warn("[ai-ci-healer] assertAiQuota failed unexpectedly:", err);
    }
  }

  const analysis = await analyzeFailedWorkflowRun(runId, {
    client: opts.client,
  });

  if (!analysis) {
    await audit({
      userId: null,
      repositoryId,
      action: "ai.ci.gave_up",
      targetType: "workflow_run",
      targetId: runId,
      metadata: { commitSha, reason: "unfixable or analysis returned null" },
    });
    return { outcome: "gave_up", reason: "unfixable" };
  }

  if (!repositoryId || !commitSha) {
    // No base sha → can't seed a patch branch. Mark gave_up so we don't loop.
    await audit({
      userId: null,
      repositoryId,
      action: "ai.ci.gave_up",
      targetType: "workflow_run",
      targetId: runId,
      metadata: {
        commitSha,
        reason: "missing repositoryId or commitSha for patch branch",
      },
    });
    return { outcome: "gave_up", reason: "missing base sha" };
  }

  const generator = opts.generatePatch ?? generatePatchForGateTestFinding;
  const findings = fixesToFindings(analysis.suggestedFixes, runId.slice(0, 8));

  const patch = await generator({
    repositoryId,
    baseSha: commitSha,
    findings,
    client: opts.client,
  });

  if (!patch) {
    await audit({
      userId: null,
      repositoryId,
      action: "ai.ci.gave_up",
      targetType: "workflow_run",
      targetId: runId,
      metadata: {
        commitSha,
        reason: "patch generator returned null",
        rootCause: analysis.rootCause,
        patchablePaths: analysis.patchablePaths,
      },
    });
    return { outcome: "gave_up", reason: "patch generator returned null" };
  }

  await audit({
    userId: null,
    repositoryId,
    action: "ai.ci.healed",
    targetType: "workflow_run",
    targetId: runId,
    metadata: {
      commitSha,
      rootCause: analysis.rootCause,
      patchablePaths: analysis.patchablePaths,
      prNumber: patch.prNumber,
      branch: patch.branch,
    },
  });

  return {
    outcome: "healed",
    prNumber: patch.prNumber,
    branch: patch.branch,
  };
}

// ---------------------------------------------------------------------------
// runCiHealerTick — public autopilot entry point
// ---------------------------------------------------------------------------

export interface CiHealerTickDeps {
  /** Inject a candidate finder for tests. */
  findCandidates?: (limit: number) => Promise<{ id: string }[]>;
  /** Inject the per-run handler for tests. */
  healOne?: (runId: string) => Promise<HealOneResult>;
  /** Inject the per-tick cap. */
  cap?: number;
}

/**
 * Find failed workflow runs that:
 *   - finished at least HEAL_MIN_AGE_MS ago (let the runner flush logs)
 *   - finished less than HEAL_MAX_AGE_MS ago (don't chase ancient failures)
 *   - do NOT yet have an ai.ci.healed / ai.ci.gave_up audit marker
 *
 * The `hasMarker` filter is applied per-row in `healOneRun` rather than
 * the SQL select — keeps the query simple and the index on (status,
 * createdAt) doing most of the work.
 */
async function defaultFindCandidates(
  limit: number
): Promise<{ id: string }[]> {
  const now = Date.now();
  const cutoffNew = new Date(now - HEAL_MIN_AGE_MS);
  const cutoffOld = new Date(now - HEAL_MAX_AGE_MS);
  try {
    const rows = await db
      .select({ id: workflowRuns.id })
      .from(workflowRuns)
      .where(
        and(
          eq(workflowRuns.status, "failure"),
          lt(workflowRuns.createdAt, cutoffNew),
          gte(workflowRuns.createdAt, cutoffOld)
        )
      )
      .orderBy(desc(workflowRuns.createdAt))
      .limit(limit);
    return rows;
  } catch (err) {
    console.error("[ai-ci-healer] candidate query failed:", err);
    return [];
  }
}

/**
 * One autopilot tick: scan recent failures, heal what we can. Returns a
 * counts summary. Never throws.
 *
 * No-op when:
 *   - AUTOPILOT_DISABLED=1
 *   - ANTHROPIC_API_KEY is unset
 */
export async function runCiHealerTick(
  deps: CiHealerTickDeps = {}
): Promise<CiHealerTickSummary> {
  if (process.env.AUTOPILOT_DISABLED === "1") {
    return { considered: 0, healed: 0, gaveUp: 0, skipped: 0 };
  }
  if (!isAiAvailable()) {
    return { considered: 0, healed: 0, gaveUp: 0, skipped: 0 };
  }

  const findCandidates = deps.findCandidates ?? defaultFindCandidates;
  const healOne = deps.healOne ?? ((id: string) => healOneRun(id));
  const cap = deps.cap ?? HEAL_CAP_PER_TICK;

  let candidates: { id: string }[] = [];
  try {
    candidates = await findCandidates(cap);
  } catch (err) {
    console.error("[ai-ci-healer] findCandidates threw:", err);
    return { considered: 0, healed: 0, gaveUp: 0, skipped: 0 };
  }

  let healed = 0;
  let gaveUp = 0;
  let skipped = 0;
  for (const cand of candidates) {
    try {
      const res = await healOne(cand.id);
      if (res.outcome === "healed") healed += 1;
      else if (res.outcome === "gave_up") gaveUp += 1;
      else skipped += 1;
    } catch (err) {
      skipped += 1;
      console.error(
        `[ai-ci-healer] per-run failure for run=${cand.id}:`,
        err instanceof Error ? err.message : err
      );
    }
  }

  return { considered: candidates.length, healed, gaveUp, skipped };
}

// ---------------------------------------------------------------------------
// Test-only re-exports
// ---------------------------------------------------------------------------

export const __test = {
  loadFailedJobs,
  hasMarker,
  defaultFindCandidates,
  normaliseSeverity,
  truncate,
  HEAL_MIN_AGE_MS,
  HEAL_MAX_AGE_MS,
  HEAL_CAP_PER_TICK,
};