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
deploy-watcher.ts13.4 KB · 455 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
/**
 * Block K7 — Deploy Watcher Agent.
 *
 * Fires after Crontech reports a deployment for a commit. Watches the
 * deployment and consumes prod error signals (ingested via K9) for the same
 * commit. If the deploy fails outright, OR if the error-signal count exceeds
 * ERROR_THRESHOLD within the watch window, the watcher calls Crontech's
 * `rollbackDeployment` and opens a P0 incident issue on the repo.
 *
 * Design rules (mirrors heal-bot.ts + fix-agent.ts):
 *   - Never throws. Every DB / network error returns `{ ok, summary }`.
 *   - Runs inside K1's `executeAgentRun` wrapper.
 *   - Cost: 2¢ flat per watch (Crontech compute proxy).
 *   - No new tables — consumes `deployments`, `prod_signals`, `issues`.
 */

import { and, eq, gte, sql } from "drizzle-orm";
import { db } from "../../db";
import {
  issues,
  repositories,
  users,
} from "../../db/schema";
import {
  rollbackDeployment,
  watchDeployment,
  type DeployWatchResult,
} from "../crontech-client";
import {
  executeAgentRun,
  startAgentRun,
  type AgentExecutorContext,
} from "../agent-runtime";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface RunDeployWatcherArgs {
  repositoryId: string;
  deployId: string;
  commitSha: string;
  triggerBy?: string | null;
}

export interface RunDeployWatcherResult {
  ok: boolean;
  summary: string;
  runId: string | null;
  rolledBack: boolean;
  incidentIssueNumber: number | null;
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

export const DEPLOY_WATCHER_COST_CENTS = 2;

/** Error signals of (error|critical) severity needed to auto-rollback. */
export const DEPLOY_WATCHER_ERROR_THRESHOLD = 5;

/** How long to watch before declaring the deploy healthy. */
export const DEPLOY_WATCHER_WINDOW_MS = 15 * 60 * 1000;

/** Poll interval inside the window. */
export const DEPLOY_WATCHER_POLL_MS = 30 * 1000;

export const DEPLOY_WATCHER_SLUG = "agent-deploy-watcher";
export const DEPLOY_WATCHER_BOT_USERNAME = "agent-deploy-watcher[bot]";

// ---------------------------------------------------------------------------
// Pure helpers (unit-testable)
// ---------------------------------------------------------------------------

/**
 * Is the given deploy-watch result a rollback trigger? Either the deploy
 * itself failed, or the error-signal threshold was breached.
 */
export function shouldRollback(params: {
  watchResult: DeployWatchResult;
  errorSignalCount: number;
  threshold: number;
}): { rollback: boolean; reason: string } {
  if (params.watchResult.finalStatus === "failed") {
    return { rollback: true, reason: "deploy reported status=failed" };
  }
  if (params.watchResult.finalStatus === "rolled_back") {
    return { rollback: false, reason: "deploy already rolled back" };
  }
  if (params.errorSignalCount >= params.threshold) {
    return {
      rollback: true,
      reason: `${params.errorSignalCount} error signals ≥ threshold ${params.threshold}`,
    };
  }
  return { rollback: false, reason: "deploy healthy" };
}

/**
 * Deterministic P0 incident issue body. Lists the top error hashes + a link
 * back to the commit.
 */
export function renderIncidentIssueBody(params: {
  commitSha: string;
  ownerUsername: string;
  repoName: string;
  deployId: string;
  reason: string;
  topErrors: Array<{ hash: string; message: string; count: number }>;
}): string {
  const {
    commitSha,
    ownerUsername,
    repoName,
    deployId,
    reason,
    topErrors,
  } = params;
  const shortSha = commitSha.slice(0, 7);
  const lines: string[] = [];
  lines.push(`**Automatic regression rollback triggered by the deploy-watcher agent.**`);
  lines.push("");
  lines.push(`- **Commit:** [\`${shortSha}\`](/${ownerUsername}/${repoName}/commit/${commitSha})`);
  lines.push(`- **Deployment:** \`${deployId}\``);
  lines.push(`- **Reason:** ${reason}`);
  lines.push("");
  if (topErrors.length > 0) {
    lines.push(`### Top errors`);
    lines.push("");
    lines.push("| Hash | Count | Message |");
    lines.push("| --- | ---: | --- |");
    for (const e of topErrors.slice(0, 10)) {
      const safeMsg = e.message.replace(/\|/g, "\\|").slice(0, 120);
      lines.push(`| \`${e.hash}\` | ${e.count} | ${safeMsg} |`);
    }
    lines.push("");
  }
  lines.push(`_Generated by ${DEPLOY_WATCHER_BOT_USERNAME}._`);
  return lines.join("\n");
}

export function buildDeployWatcherSummary(params: {
  offline: boolean;
  rolledBack: boolean;
  reason: string;
  incidentIssueNumber: number | null;
  watchedForMs: number;
  errorSignalCount: number;
}): string {
  if (params.offline) return "crontech offline; watch skipped";
  if (params.rolledBack) {
    const issueLabel =
      params.incidentIssueNumber !== null
        ? `#${params.incidentIssueNumber}`
        : "(unknown issue)";
    return `ROLLED BACK — ${params.reason}; opened ${issueLabel}`;
  }
  const secs = Math.round(params.watchedForMs / 1000);
  return `deploy healthy — watched ${secs}s, ${params.errorSignalCount} signal(s)`;
}

// ---------------------------------------------------------------------------
// Internal DB helpers — defensive, never throw.
// ---------------------------------------------------------------------------

interface RepoContext {
  repoId: string;
  repoName: string;
  ownerUsername: string;
  ownerId: string;
}

async function resolveRepoContext(
  repositoryId: string
): Promise<RepoContext | null> {
  try {
    const rows = await db
      .select({
        repoId: repositories.id,
        repoName: repositories.name,
        ownerUsername: users.username,
        ownerId: repositories.ownerId,
      })
      .from(repositories)
      .innerJoin(users, eq(users.id, repositories.ownerId))
      .where(eq(repositories.id, repositoryId))
      .limit(1);
    const row = rows[0];
    if (!row) return null;
    return row;
  } catch (err) {
    console.error("[deploy-watcher] resolveRepoContext:", err);
    return null;
  }
}

/**
 * Pick the author_id for the incident issue. Preference:
 *   1. a "bot" user named DEPLOY_WATCHER_BOT_USERNAME,
 *   2. the repo owner.
 */
async function resolveWatcherAuthorId(ownerId: string): Promise<string | null> {
  try {
    const [bot] = await db
      .select({ id: users.id })
      .from(users)
      .where(eq(users.username, DEPLOY_WATCHER_BOT_USERNAME))
      .limit(1);
    if (bot?.id) return bot.id;
  } catch (err) {
    console.error("[deploy-watcher] bot author lookup:", err);
  }
  return ownerId;
}

interface SignalAggregate {
  hash: string;
  message: string;
  count: number;
  severity: string;
}

/**
 * Count error/critical signals for the given commit that have been recorded
 * since `since`, and return the top-N aggregated signals for the incident
 * body.
 *
 * Uses raw sql because we filter on severity in SQL for efficiency.
 */
async function countAndTopErrors(
  repositoryId: string,
  commitSha: string,
  since: Date
): Promise<{ count: number; top: SignalAggregate[] }> {
  try {
    const rows = (await db.execute(sql`
      SELECT error_hash, message, count, severity
      FROM prod_signals
      WHERE repository_id = ${repositoryId}
        AND commit_sha = ${commitSha.toLowerCase()}
        AND severity IN ('error', 'critical')
        AND last_seen >= ${since.toISOString()}
      ORDER BY count DESC
      LIMIT 25
    `)) as unknown as Array<Record<string, unknown>>;
    if (!Array.isArray(rows)) return { count: 0, top: [] };
    const list = rows.map((r) => ({
      hash: String(r.error_hash ?? ""),
      message: String(r.message ?? ""),
      count: Number(r.count ?? 1),
      severity: String(r.severity ?? "error"),
    }));
    // Total count = sum of counts (each signal row is one distinct error,
    // bumped per occurrence).
    const total = list.reduce((acc, r) => acc + r.count, 0);
    return { count: total, top: list };
  } catch (err) {
    console.error("[deploy-watcher] countAndTopErrors:", err);
    return { count: 0, top: [] };
  }
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

/**
 * Run the deploy watcher for a single deployment. Never throws.
 */
export async function runDeployWatcher(
  args: RunDeployWatcherArgs
): Promise<RunDeployWatcherResult> {
  const emptyResult = (summary: string): RunDeployWatcherResult => ({
    ok: false,
    summary,
    runId: null,
    rolledBack: false,
    incidentIssueNumber: null,
  });

  if (
    !args ||
    typeof args.repositoryId !== "string" ||
    !args.repositoryId ||
    typeof args.deployId !== "string" ||
    !args.deployId ||
    typeof args.commitSha !== "string" ||
    !args.commitSha
  ) {
    return emptyResult("invalid args: missing repositoryId/deployId/commitSha");
  }

  const trigger = args.triggerBy ? "manual" : "scheduled";

  const run = await startAgentRun({
    repositoryId: args.repositoryId,
    kind: "deploy_watcher",
    trigger,
    triggerRef: args.deployId,
  });
  if (!run) {
    return emptyResult("could not open agent_runs row");
  }

  let finalSummary = "not started";
  let rolledBack = false;
  let incidentIssueNumber: number | null = null;

  await executeAgentRun(run.id, async (ctx: AgentExecutorContext) => {
    await ctx.appendLog(
      `[deploy-watcher] starting watch for deploy ${args.deployId} @ ${args.commitSha.slice(0, 7)} (trigger=${trigger})`
    );

    const repo = await resolveRepoContext(args.repositoryId);
    if (!repo) {
      finalSummary = "repo lookup failed";
      await ctx.appendLog("[deploy-watcher] repo lookup failed; aborting");
      return { ok: false, summary: finalSummary };
    }

    const repoSlug = `${repo.ownerUsername}/${repo.repoName}`;
    const watchStart = new Date();

    await ctx.appendLog(
      `[deploy-watcher] calling crontech.watchDeployment for ${repoSlug}`
    );
    const watchResult = await watchDeployment({
      repo: repoSlug,
      deployId: args.deployId,
      maxWaitMs: DEPLOY_WATCHER_WINDOW_MS,
      pollIntervalMs: DEPLOY_WATCHER_POLL_MS,
    });
    await ctx.recordCost(0, 0, DEPLOY_WATCHER_COST_CENTS);

    if (watchResult.offline) {
      finalSummary = buildDeployWatcherSummary({
        offline: true,
        rolledBack: false,
        reason: "",
        incidentIssueNumber: null,
        watchedForMs: 0,
        errorSignalCount: 0,
      });
      await ctx.appendLog(`[deploy-watcher] ${finalSummary}`);
      return { ok: true, summary: finalSummary };
    }

    const { count: errorSignalCount, top: topErrors } = await countAndTopErrors(
      args.repositoryId,
      args.commitSha,
      watchStart
    );
    await ctx.appendLog(
      `[deploy-watcher] watch complete: finalStatus=${watchResult.finalStatus}, errorSignals=${errorSignalCount}, watchedForMs=${watchResult.watchedForMs}`
    );

    const decision = shouldRollback({
      watchResult,
      errorSignalCount,
      threshold: DEPLOY_WATCHER_ERROR_THRESHOLD,
    });

    if (!decision.rollback) {
      finalSummary = buildDeployWatcherSummary({
        offline: false,
        rolledBack: false,
        reason: decision.reason,
        incidentIssueNumber: null,
        watchedForMs: watchResult.watchedForMs,
        errorSignalCount,
      });
      await ctx.appendLog(`[deploy-watcher] ${decision.reason}`);
      return { ok: true, summary: finalSummary };
    }

    await ctx.appendLog(
      `[deploy-watcher] ROLLBACK TRIGGERED: ${decision.reason}`
    );

    const rollbackOk = await rollbackDeployment({
      repo: repoSlug,
      deployId: args.deployId,
    });
    rolledBack = rollbackOk;
    if (!rollbackOk) {
      await ctx.appendLog(
        `[deploy-watcher] crontech rollback failed; opening incident anyway`
      );
    }

    // Open a P0 incident issue.
    const authorId = await resolveWatcherAuthorId(repo.ownerId);
    if (!authorId) {
      finalSummary = `rollback ${rollbackOk ? "ok" : "failed"}; no author for incident`;
      await ctx.appendLog(`[deploy-watcher] ${finalSummary}`);
      return { ok: false, summary: finalSummary };
    }

    const body = renderIncidentIssueBody({
      commitSha: args.commitSha,
      ownerUsername: repo.ownerUsername,
      repoName: repo.repoName,
      deployId: args.deployId,
      reason: decision.reason,
      topErrors,
    });

    try {
      const [inserted] = await db
        .insert(issues)
        .values({
          repositoryId: repo.repoId,
          authorId,
          title: `P0: Regression in ${args.commitSha.slice(0, 7)}`,
          body,
        })
        .returning();
      incidentIssueNumber = inserted?.number ?? null;
    } catch (err) {
      await ctx.appendLog(
        `[deploy-watcher] incident issue insert failed: ${(err as Error).message}`
      );
    }

    finalSummary = buildDeployWatcherSummary({
      offline: false,
      rolledBack,
      reason: decision.reason,
      incidentIssueNumber,
      watchedForMs: watchResult.watchedForMs,
      errorSignalCount,
    });
    await ctx.appendLog(`[deploy-watcher] ${finalSummary}`);
    return { ok: rolledBack, summary: finalSummary };
  });

  return {
    ok: true,
    summary: finalSummary,
    runId: run.id,
    rolledBack,
    incidentIssueNumber,
  };
}

export const __internal = {
  DEPLOY_WATCHER_COST_CENTS,
  DEPLOY_WATCHER_ERROR_THRESHOLD,
  DEPLOY_WATCHER_WINDOW_MS,
  DEPLOY_WATCHER_POLL_MS,
  resolveRepoContext,
  resolveWatcherAuthorId,
  countAndTopErrors,
};