CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 | /**
* 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
* `triggerVapronDeploy`) whenever the Vapron 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;
}
}
// ---------------------------------------------------------------------------
// PLATFORM deploy-failure analysis (2026-05-16 reliability sweep, Level 3).
//
// `onDeployFailure` above is for DOWNSTREAM-APP deployments (the
// `deployments` table — repos that gluecron is CI'ing). This sibling
// function handles failures of gluecron's OWN deploy pipeline
// (the `platform_deploys` table, populated by hetzner-deploy.yml).
//
// When a deploy event with status="failed" arrives at /deploy/finished,
// this function:
// 1. Loads the last 10 commits to main from the box-side repo.
// 2. Asks Sonnet for a root-cause analysis as structured JSON.
// 3. Returns the analysis as a markdown string ready to embed in the
// platform_deploys.error column or an audit-log entry.
//
// Never throws. Degrades to a deterministic "AI unavailable" body when
// ANTHROPIC_API_KEY is unset or the Sonnet call fails — operators still
// get the recent-commits context, just without the AI summary.
// ---------------------------------------------------------------------------
export interface PlatformDeployFailureInput {
runId: string;
sha: string;
errorMessage: string;
/** owner/repo of the gluecron platform repo (e.g. "ccantynz/Gluecron.com"). */
selfHostRepo?: string;
}
export interface PlatformDeployFailureResult {
/** Markdown-formatted RCA suitable for an issue body or audit log. */
rcaMarkdown: string;
/** Did Claude actually run, or did we fall back? */
aiAvailable: boolean;
/** First 7 chars of the sha or "unknown". */
shortSha: string;
}
export async function analyzePlatformDeployFailure(
input: PlatformDeployFailureInput
): Promise<PlatformDeployFailureResult> {
const shortSha = input.sha ? input.sha.slice(0, 7) : "unknown";
const repoFullName = input.selfHostRepo || process.env.SELF_HOST_REPO || "ccantynz/Gluecron.com";
const [ownerName, repoName] = repoFullName.includes("/")
? repoFullName.split("/")
: [repoFullName, "Gluecron.com"];
let commitSummary = "";
try {
const commits = await listCommits(ownerName, repoName, "main", 10);
commitSummary = commits
.map((c) => `- ${c.sha.slice(0, 7)} ${c.message.split("\n")[0].slice(0, 100)}`)
.join("\n");
} catch (err) {
console.warn(
`[platform-incident] listCommits failed for ${ownerName}/${repoName}:`,
err instanceof Error ? err.message : err
);
}
if (!isAiAvailable()) {
return {
rcaMarkdown: [
`## Platform deploy failure — run ${input.runId} (sha ${shortSha})`,
"",
"**AI analysis unavailable** — `ANTHROPIC_API_KEY` is not configured.",
"",
"### Error",
"```",
truncate(input.errorMessage, 4000),
"```",
"",
"### Recent commits",
commitSummary || "(none available)",
].join("\n"),
aiAvailable: false,
shortSha,
};
}
const analysis = await askClaudeForAnalysis(
repoFullName,
"refs/heads/main",
shortSha,
input.errorMessage,
commitSummary
);
if (!analysis) {
return {
rcaMarkdown: [
`## Platform deploy failure — run ${input.runId} (sha ${shortSha})`,
"",
"**AI returned no parseable analysis.** Raw Sonnet call failed or returned malformed JSON.",
"",
"### Error",
"```",
truncate(input.errorMessage, 4000),
"```",
"",
"### Recent commits",
commitSummary || "(none available)",
].join("\n"),
aiAvailable: true,
shortSha,
};
}
return {
rcaMarkdown: [
`## ${analysis.title}`,
"",
`**Run:** ${input.runId} **SHA:** ${shortSha}`,
"",
"### Likely cause",
analysis.likelyCause,
"",
"### Suspected commit",
analysis.suspectedCommit
? `\`${analysis.suspectedCommit.slice(0, 7)}\``
: "(none identified)",
"",
"### Suggested remediation",
analysis.remediation,
"",
"### Raw error",
"```",
truncate(input.errorMessage, 4000),
"```",
"",
"### Recent commits",
commitSummary || "(none available)",
].join("\n"),
aiAvailable: true,
shortSha,
};
}
|