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-incident.ts11.6 KB · 393 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
/**
 * Block D4 — AI Incident Responder.
 *
 * When a deployment fails, this module automatically opens an issue with an
 * AI-generated root-cause analysis. Invoked by the post-receive hook (from
 * `triggerCrontechDeploy`) whenever the Crontech deploy call returns a non-2xx
 * response or throws. Also retriggerable via the deployments route.
 *
 * Everything here degrades gracefully:
 *   - Without `ANTHROPIC_API_KEY` we still open an issue, just with a
 *     deterministic fallback body saying "AI analysis unavailable".
 *   - Any DB/git/network failure is caught; the function never throws and
 *     returns `{ issueNumber: null, reason: <err.message> }` instead.
 */

import { and, desc, eq } from "drizzle-orm";
import { db } from "../db";
import {
  deployments,
  issueLabels,
  issues,
  labels,
  repositories,
  users,
} from "../db/schema";
import { getDefaultBranch, listCommits } from "../git/repository";
import {
  MODEL_SONNET,
  extractText,
  getAnthropic,
  isAiAvailable,
  parseJsonResponse,
} from "./ai-client";

export interface IncidentAnalysis {
  title: string;
  likelyCause: string;
  suspectedCommit: string | null;
  remediation: string;
}

export interface OnDeployFailureArgs {
  repositoryId: string;
  deploymentId: string;
  ref?: string | null;
  commitSha?: string | null;
  target?: string | null;
  errorMessage?: string | null;
}

export interface OnDeployFailureResult {
  issueNumber: number | null;
  reason: string;
}

/**
 * Format a list of commits for inclusion in the incident prompt / issue body.
 * Pure helper — kept separate so it can be unit-tested without any I/O.
 */
export function summariseCommitsForIncident(
  commits: { sha: string; message: string; author: string }[]
): string {
  return commits
    .map((c) => {
      const sha7 = (c.sha || "").slice(0, 7);
      const subject = (c.message || "").split("\n")[0] || "";
      const author = c.author || "unknown";
      return `- ${sha7} ${subject}${author}`;
    })
    .join("\n");
}

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 renderIssueBody(args: {
  deploymentId: string;
  ref: string;
  shortSha: string;
  target: string;
  errorMessage: string;
  likelyCause: string;
  suspectedCommit: string | null;
  remediation: string;
}): string {
  const suspected = args.suspectedCommit || "none";
  const safeError = args.errorMessage || "(no error message captured)";
  return [
    `Automated by GlueCron incident responder after deployment ${args.deploymentId} failed.`,
    "",
    `**Ref:** \`${args.ref}\` (sha \`${args.shortSha}\`)`,
    `**Target:** ${args.target}`,
    "",
    "## Error",
    "```",
    safeError,
    "```",
    "",
    "## Likely cause",
    args.likelyCause,
    "",
    "## Suspected commit",
    suspected,
    "",
    "## Suggested remediation",
    args.remediation,
    "",
    "---",
    "_This issue was auto-generated. Edit or close if the analysis is off._",
  ].join("\n");
}

async function askClaudeForAnalysis(
  repoFullName: string,
  ref: string,
  shortSha: string,
  errorMessage: string,
  commitSummary: string
): Promise<IncidentAnalysis | null> {
  try {
    const client = getAnthropic();
    const message = await client.messages.create({
      model: MODEL_SONNET,
      max_tokens: 1024,
      messages: [
        {
          role: "user",
          content: `You are GlueCron's incident responder. A deployment just failed. Respond ONLY with JSON of the form:

{"title": "...", "likelyCause": "...", "suspectedCommit": "<sha or null>", "remediation": "..."}

Repository: ${repoFullName}
Failing ref: ${ref} (sha ${shortSha})

Error message:
\`\`\`
${truncate(errorMessage, 4000)}
\`\`\`

Recent commits (most recent first):
${commitSummary || "(no commits available)"}

Write a crisp issue title (prefixed with "Deploy failed:"), a plausible likelyCause (2-4 sentences), a suspectedCommit sha (or null if unclear), and concrete remediation steps (bullet list as a single string with \\n separators).`,
        },
      ],
    });
    const parsed = parseJsonResponse<IncidentAnalysis>(extractText(message));
    if (!parsed) return null;
    const suspected =
      typeof parsed.suspectedCommit === "string" && parsed.suspectedCommit
        ? parsed.suspectedCommit
        : null;
    return {
      title:
        typeof parsed.title === "string" && parsed.title.trim()
          ? parsed.title.trim().slice(0, 200)
          : `Deploy failed: ${repoFullName} @ ${shortSha}`,
      likelyCause:
        typeof parsed.likelyCause === "string" && parsed.likelyCause.trim()
          ? parsed.likelyCause.trim()
          : "Unknown — see raw error above.",
      suspectedCommit: suspected,
      remediation:
        typeof parsed.remediation === "string" && parsed.remediation.trim()
          ? parsed.remediation.trim()
          : "Inspect logs manually and re-run the deployment.",
    };
  } catch (err) {
    console.error("[ai-incident] analysis request failed:", err);
    return null;
  }
}

/**
 * Entry point called by the post-receive hook and the retry-incident route.
 * Never throws.
 */
export async function onDeployFailure(
  args: OnDeployFailureArgs
): Promise<OnDeployFailureResult> {
  const ref = args.ref || "refs/heads/main";
  const commitSha = args.commitSha || "";
  const shortSha = commitSha ? commitSha.slice(0, 7) : "unknown";
  const target = args.target || "unknown";
  const errorMessage = args.errorMessage || "";

  try {
    // 1. Load repository + owner username for nice issue attribution.
    const [repoRow] = await db
      .select()
      .from(repositories)
      .where(eq(repositories.id, args.repositoryId))
      .limit(1);
    if (!repoRow) {
      return { issueNumber: null, reason: "repository not found" };
    }
    const [ownerRow] = await db
      .select()
      .from(users)
      .where(eq(users.id, repoRow.ownerId))
      .limit(1);
    if (!ownerRow) {
      return { issueNumber: null, reason: "repository owner not found" };
    }
    const repoFullName = `${ownerRow.username}/${repoRow.name}`;

    // 2. Load up to ~10 recent commits leading to commitSha, with a fallback
    //    to the default branch tip if the sha is missing / unresolvable.
    let commits: Array<{ sha: string; message: string; author: string }> = [];
    try {
      const refForLog =
        commitSha ||
        (await getDefaultBranch(ownerRow.username, repoRow.name)) ||
        repoRow.defaultBranch ||
        "main";
      const raw = await listCommits(
        ownerRow.username,
        repoRow.name,
        refForLog,
        10,
        0
      ).catch(() => [] as Awaited<ReturnType<typeof listCommits>>);
      commits = raw.map((c) => ({
        sha: c.sha,
        message: c.message,
        author: c.author,
      }));
    } catch {
      commits = [];
    }
    const commitSummary = summariseCommitsForIncident(commits);

    // 3. Ask Claude for an analysis, or fall back to a deterministic body.
    let analysis: IncidentAnalysis;
    if (isAiAvailable()) {
      const ai = await askClaudeForAnalysis(
        repoFullName,
        ref,
        shortSha,
        errorMessage,
        commitSummary
      );
      analysis = ai || {
        title: `Deploy failed: ${repoFullName} @ ${shortSha}`,
        likelyCause:
          "AI analysis unavailable — inspect logs manually.\n\nRecent commits:\n" +
          commitSummary,
        suspectedCommit: commits[0]?.sha || null,
        remediation:
          "Inspect deployment logs and recent commits. Re-run the deploy once fixed.",
      };
    } else {
      analysis = {
        title: `Deploy failed: ${repoFullName} @ ${shortSha}`,
        likelyCause:
          "AI analysis unavailable — inspect logs manually.\n\nRecent commits:\n" +
          (commitSummary || "(none)"),
        suspectedCommit: commits[0]?.sha || null,
        remediation:
          "Inspect deployment logs and recent commits. Re-run the deploy once fixed.",
      };
    }

    // 4. Render the Markdown issue body.
    const body = renderIssueBody({
      deploymentId: args.deploymentId,
      ref,
      shortSha,
      target,
      errorMessage,
      likelyCause: analysis.likelyCause,
      suspectedCommit: analysis.suspectedCommit,
      remediation: analysis.remediation,
    });

    // 5. Insert the issue row. `issues.number` is a `serial()` — Postgres
    //    assigns the next number automatically, matching the pattern used
    //    in src/routes/issues.tsx.
    let issueNumber: number | null = null;
    try {
      const [inserted] = await db
        .insert(issues)
        .values({
          repositoryId: repoRow.id,
          authorId: repoRow.ownerId,
          title: analysis.title,
          body,
          state: "open",
        })
        .returning();
      issueNumber = inserted?.number ?? null;

      // Best-effort: attach the "incident" label if one exists for the repo.
      if (inserted?.id) {
        try {
          const [incidentLabel] = await db
            .select()
            .from(labels)
            .where(
              and(
                eq(labels.repositoryId, repoRow.id),
                eq(labels.name, "incident")
              )
            )
            .limit(1);
          if (incidentLabel) {
            await db
              .insert(issueLabels)
              .values({ issueId: inserted.id, labelId: incidentLabel.id })
              .catch(() => {
                /* ignore — the unique constraint may reject duplicates */
              });
          }
        } catch {
          /* best-effort */
        }
      }

      // Bump the repo's issue count so the UI stays in sync.
      try {
        await db
          .update(repositories)
          .set({ issueCount: (repoRow.issueCount || 0) + 1 })
          .where(eq(repositories.id, repoRow.id));
      } catch {
        /* best-effort */
      }
    } catch (err) {
      return {
        issueNumber: null,
        reason: (err as Error).message || "issue insert failed",
      };
    }

    // 6. Update the deployment's blockedReason to link the auto-issue, but
    //    only if the field is currently empty or looks like a raw error
    //    (i.e. NOT an admin-edited note).
    if (issueNumber !== null) {
      try {
        const [depRow] = await db
          .select()
          .from(deployments)
          .where(eq(deployments.id, args.deploymentId))
          .limit(1);
        const current = depRow?.blockedReason || "";
        const looksAutoEditable =
          !current ||
          current === errorMessage ||
          /^HTTP \d+/.test(current) ||
          /^auto-issue #/.test(current);
        if (depRow && looksAutoEditable) {
          await db
            .update(deployments)
            .set({ blockedReason: `auto-issue #${issueNumber}` })
            .where(eq(deployments.id, args.deploymentId));
        }
      } catch {
        /* best-effort */
      }
    }

    return {
      issueNumber,
      reason: issueNumber !== null ? "ok" : "issue number unavailable",
    };
  } catch (err) {
    return {
      issueNumber: null,
      reason: (err as Error).message || "unknown failure",
    };
  }
}

// Re-exported for tests that want to inspect the most recent incident issue
// for a repository without hitting the HTTP layer.
export async function getLatestIncidentIssueForRepo(
  repositoryId: string
): Promise<{ number: number; title: string } | null> {
  try {
    const [row] = await db
      .select({ number: issues.number, title: issues.title })
      .from(issues)
      .where(eq(issues.repositoryId, repositoryId))
      .orderBy(desc(issues.createdAt))
      .limit(1);
    return row || null;
  } catch {
    return null;
  }
}