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.test.ts9.8 KB · 327 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
/**
 * Block K7 — deploy-watcher tests.
 *
 * Same shape as heal-bot.test.ts + fix-agent.test.ts: pure helpers exhaustively,
 * entry-point arg validation, graceful-degradation when DB/Crontech offline.
 */

import {
  afterEach,
  beforeEach,
  describe,
  expect,
  it,
} from "bun:test";
import {
  DEPLOY_WATCHER_BOT_USERNAME,
  DEPLOY_WATCHER_COST_CENTS,
  DEPLOY_WATCHER_ERROR_THRESHOLD,
  DEPLOY_WATCHER_SLUG,
  DEPLOY_WATCHER_WINDOW_MS,
  buildDeployWatcherSummary,
  renderIncidentIssueBody,
  runDeployWatcher,
  shouldRollback,
} from "../../lib/agents/deploy-watcher";
import type { DeployWatchResult } from "../../lib/crontech-client";

const ENV_KEYS = ["CRONTECH_API_KEY", "CRONTECH_BASE_URL"] as const;

let savedEnv: Record<string, string | undefined> = {};
let savedFetch: typeof fetch;

beforeEach(() => {
  savedEnv = {};
  for (const k of ENV_KEYS) savedEnv[k] = process.env[k];
  for (const k of ENV_KEYS) delete process.env[k];
  savedFetch = globalThis.fetch;
});

afterEach(() => {
  for (const k of ENV_KEYS) {
    const v = savedEnv[k];
    if (v === undefined) delete process.env[k];
    else process.env[k] = v;
  }
  globalThis.fetch = savedFetch;
});

// ---------------------------------------------------------------------------
// Identity + constants
// ---------------------------------------------------------------------------

describe("deploy-watcher — identity constants", () => {
  it("uses the agent- prefixed slug", () => {
    expect(DEPLOY_WATCHER_SLUG).toBe("agent-deploy-watcher");
  });
  it("uses the [bot] suffixed username", () => {
    expect(DEPLOY_WATCHER_BOT_USERNAME).toBe("agent-deploy-watcher[bot]");
    expect(DEPLOY_WATCHER_BOT_USERNAME.endsWith("[bot]")).toBe(true);
  });
  it("cost is flat 2¢", () => {
    expect(DEPLOY_WATCHER_COST_CENTS).toBe(2);
  });
  it("error threshold defaults to 5", () => {
    expect(DEPLOY_WATCHER_ERROR_THRESHOLD).toBe(5);
  });
  it("watch window is 15 minutes", () => {
    expect(DEPLOY_WATCHER_WINDOW_MS).toBe(15 * 60 * 1000);
  });
});

// ---------------------------------------------------------------------------
// shouldRollback
// ---------------------------------------------------------------------------

function mkWatch(status: DeployWatchResult["finalStatus"]): DeployWatchResult {
  return {
    deployId: "d1",
    finalStatus: status,
    errors: [],
    watchedForMs: 60_000,
    offline: false,
  };
}

describe("deploy-watcher — shouldRollback", () => {
  it("rolls back when deploy finalStatus=failed", () => {
    const r = shouldRollback({
      watchResult: mkWatch("failed"),
      errorSignalCount: 0,
      threshold: 5,
    });
    expect(r.rollback).toBe(true);
    expect(r.reason).toContain("status=failed");
  });

  it("does NOT roll back when already rolled_back", () => {
    const r = shouldRollback({
      watchResult: mkWatch("rolled_back"),
      errorSignalCount: 99,
      threshold: 5,
    });
    expect(r.rollback).toBe(false);
    expect(r.reason).toContain("already rolled back");
  });

  it("rolls back when error signals ≥ threshold on a live deploy", () => {
    const r = shouldRollback({
      watchResult: mkWatch("live"),
      errorSignalCount: 7,
      threshold: 5,
    });
    expect(r.rollback).toBe(true);
    expect(r.reason).toContain("7 error signals");
    expect(r.reason).toContain("threshold 5");
  });

  it("rolls back when signals exactly equal threshold", () => {
    const r = shouldRollback({
      watchResult: mkWatch("live"),
      errorSignalCount: 5,
      threshold: 5,
    });
    expect(r.rollback).toBe(true);
  });

  it("declares healthy when deploy live + signals below threshold", () => {
    const r = shouldRollback({
      watchResult: mkWatch("live"),
      errorSignalCount: 2,
      threshold: 5,
    });
    expect(r.rollback).toBe(false);
    expect(r.reason).toBe("deploy healthy");
  });

  it("healthy when deploy pending + no signals", () => {
    const r = shouldRollback({
      watchResult: mkWatch("pending"),
      errorSignalCount: 0,
      threshold: 5,
    });
    expect(r.rollback).toBe(false);
  });
});

// ---------------------------------------------------------------------------
// renderIncidentIssueBody
// ---------------------------------------------------------------------------

describe("deploy-watcher — renderIncidentIssueBody", () => {
  it("includes commit link, deploy id, reason, and top errors table", () => {
    const body = renderIncidentIssueBody({
      commitSha: "abcdef1234567890",
      ownerUsername: "alice",
      repoName: "web",
      deployId: "dpl_xyz",
      reason: "7 error signals ≥ threshold 5",
      topErrors: [
        { hash: "aaaaaaaaaaaaaaaa", message: "Cannot read null", count: 12 },
        { hash: "bbbbbbbbbbbbbbbb", message: "Timeout", count: 3 },
      ],
    });
    expect(body).toContain("/alice/web/commit/abcdef1234567890");
    expect(body).toContain("`abcdef1`");
    expect(body).toContain("dpl_xyz");
    expect(body).toContain("7 error signals");
    expect(body).toContain("aaaaaaaaaaaaaaaa");
    expect(body).toContain("| 12 |");
    expect(body).toContain("Cannot read null");
    expect(body).toContain(DEPLOY_WATCHER_BOT_USERNAME);
  });

  it("escapes pipe chars in error messages", () => {
    const body = renderIncidentIssueBody({
      commitSha: "deadbeefcafebabe",
      ownerUsername: "o",
      repoName: "r",
      deployId: "d",
      reason: "x",
      topErrors: [
        { hash: "h", message: "pipe | inside | message", count: 1 },
      ],
    });
    expect(body).toContain("pipe \\| inside \\| message");
  });

  it("truncates long messages to ~120 chars in the table", () => {
    const longMsg = "x".repeat(500);
    const body = renderIncidentIssueBody({
      commitSha: "1234567",
      ownerUsername: "o",
      repoName: "r",
      deployId: "d",
      reason: "x",
      topErrors: [{ hash: "h", message: longMsg, count: 1 }],
    });
    // The row line contains at most 120 x's between the pipes.
    const match = body.match(/\| `h` \| 1 \| (x+) \|/);
    expect(match).not.toBeNull();
    expect(match![1]!.length).toBeLessThanOrEqual(120);
  });

  it("omits the errors table when topErrors is empty", () => {
    const body = renderIncidentIssueBody({
      commitSha: "1234567",
      ownerUsername: "o",
      repoName: "r",
      deployId: "d",
      reason: "deploy status=failed",
      topErrors: [],
    });
    expect(body).not.toContain("Top errors");
  });
});

// ---------------------------------------------------------------------------
// buildDeployWatcherSummary
// ---------------------------------------------------------------------------

describe("deploy-watcher — buildDeployWatcherSummary", () => {
  it("offline message when crontech offline", () => {
    expect(
      buildDeployWatcherSummary({
        offline: true,
        rolledBack: false,
        reason: "",
        incidentIssueNumber: null,
        watchedForMs: 0,
        errorSignalCount: 0,
      })
    ).toBe("crontech offline; watch skipped");
  });

  it("healthy deploy summary with seconds watched + signal count", () => {
    const s = buildDeployWatcherSummary({
      offline: false,
      rolledBack: false,
      reason: "deploy healthy",
      incidentIssueNumber: null,
      watchedForMs: 125_000,
      errorSignalCount: 3,
    });
    expect(s).toContain("healthy");
    expect(s).toContain("125s");
    expect(s).toContain("3 signal");
  });

  it("rolled-back summary embeds reason + incident issue number", () => {
    const s = buildDeployWatcherSummary({
      offline: false,
      rolledBack: true,
      reason: "7 error signals ≥ threshold 5",
      incidentIssueNumber: 42,
      watchedForMs: 300_000,
      errorSignalCount: 7,
    });
    expect(s).toContain("ROLLED BACK");
    expect(s).toContain("threshold");
    expect(s).toContain("#42");
  });

  it("handles missing incident issue number on rollback", () => {
    const s = buildDeployWatcherSummary({
      offline: false,
      rolledBack: true,
      reason: "deploy reported status=failed",
      incidentIssueNumber: null,
      watchedForMs: 10_000,
      errorSignalCount: 0,
    });
    expect(s).toContain("ROLLED BACK");
    expect(s).toContain("(unknown issue)");
  });
});

// ---------------------------------------------------------------------------
// runDeployWatcher — arg validation + graceful degradation
// ---------------------------------------------------------------------------

describe("deploy-watcher — runDeployWatcher", () => {
  it("rejects empty repositoryId", async () => {
    const r = await runDeployWatcher({
      repositoryId: "",
      deployId: "d1",
      commitSha: "abcdef1234567",
    });
    expect(r.ok).toBe(false);
    expect(r.runId).toBeNull();
    expect(r.summary.toLowerCase()).toContain("invalid args");
  });

  it("rejects empty deployId", async () => {
    const r = await runDeployWatcher({
      repositoryId: "00000000-0000-0000-0000-000000000000",
      deployId: "",
      commitSha: "abcdef1234567",
    });
    expect(r.ok).toBe(false);
    expect(r.summary.toLowerCase()).toContain("invalid args");
  });

  it("rejects empty commitSha", async () => {
    const r = await runDeployWatcher({
      repositoryId: "00000000-0000-0000-0000-000000000000",
      deployId: "d1",
      commitSha: "",
    });
    expect(r.ok).toBe(false);
    expect(r.summary.toLowerCase()).toContain("invalid args");
  });

  it("returns documented failure when DB cannot open a run", async () => {
    globalThis.fetch = (() => {
      throw new Error("fetch must not be called when run cannot be opened");
    }) as unknown as typeof fetch;
    const r = await runDeployWatcher({
      repositoryId: "00000000-0000-0000-0000-000000000000",
      deployId: "d1",
      commitSha: "abcdef1234567",
    });
    expect(r.ok).toBe(false);
    expect(r.runId).toBeNull();
    expect(r.rolledBack).toBe(false);
    expect(r.incidentIssueNumber).toBeNull();
  });
});