Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
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
heal-bot.test.ts11.7 KB · 336 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
/**
 * Block K12 — heal-bot tests.
 *
 * The agent runtime writes to Neon on every step, so in the test environment
 * (which has no DATABASE_URL) the DB-touching entry points degrade to the
 * documented "never throws" shapes. The tests below exercise:
 *
 *   1. Pure helpers (`renderHealBotPrBody`, `renderHealBotPrTitle`,
 *      `buildHealBotSummary`) — fully exercised without any I/O.
 *   2. `runHealBot` argument validation.
 *   3. `runHealBot`'s graceful-degradation path when the DB / Gatetest are
 *      unreachable (no throws, well-formed result shape, honours the
 *      "gatetest offline" summary when the Gatetest key isn't set).
 *   4. `runHealBotForAll` — empty / failing repo listing must not throw.
 *
 * For Gatetest we flip `globalThis.fetch` and `GATETEST_API_KEY` to steer the
 * client between its offline short-circuit and its "fetch returned 500"
 * short-circuit, without reaching the network.
 */

import {
  afterEach,
  beforeEach,
  describe,
  expect,
  it,
} from "bun:test";
import {
  buildHealBotSummary,
  HEAL_BOT_BOT_USERNAME,
  HEAL_BOT_SLUG,
  renderHealBotPrBody,
  renderHealBotPrTitle,
  runHealBot,
  runHealBotForAll,
} from "../../lib/agents/heal-bot";
import { healSuite } from "../../lib/gatetest-client";

const ENV_KEYS = ["GATETEST_API_KEY", "GATETEST_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;
});

// ---------------------------------------------------------------------------
// Constants / identity
// ---------------------------------------------------------------------------

describe("heal-bot — identity constants", () => {
  it("uses the agent- prefixed slug", () => {
    expect(HEAL_BOT_SLUG).toBe("agent-heal-bot");
  });

  it("uses the [bot] suffixed username", () => {
    expect(HEAL_BOT_BOT_USERNAME).toBe("agent-heal-bot[bot]");
    expect(HEAL_BOT_BOT_USERNAME.endsWith("[bot]")).toBe(true);
  });
});

// ---------------------------------------------------------------------------
// Pure helpers — renderHealBotPrTitle
// ---------------------------------------------------------------------------

describe("heal-bot — renderHealBotPrTitle", () => {
  it("pluralises for multiple repairs", () => {
    expect(renderHealBotPrTitle(5)).toBe("chore(tests): heal-bot — 5 repairs");
  });

  it("uses the singular form for exactly one repair", () => {
    expect(renderHealBotPrTitle(1)).toBe("chore(tests): heal-bot — 1 repair");
  });

  it("still uses plural for zero (degenerate)", () => {
    expect(renderHealBotPrTitle(0)).toBe("chore(tests): heal-bot — 0 repairs");
  });
});

// ---------------------------------------------------------------------------
// Pure helpers — renderHealBotPrBody
// ---------------------------------------------------------------------------

describe("heal-bot — renderHealBotPrBody", () => {
  it("includes finding counts + branches + generator footer", () => {
    const body = renderHealBotPrBody({
      flakyFound: 3,
      deadFound: 1,
      coverageGapsFound: 2,
      headBranch: "gatetest/heal-2026-04-17",
      baseBranch: "main",
    });
    expect(body).toContain("6 repairs");
    expect(body).toContain("gatetest/heal-2026-04-17");
    expect(body).toContain("main");
    expect(body).toContain("Flaky tests stabilised | 3");
    expect(body).toContain("Dead / obsolete tests pruned | 1");
    expect(body).toContain("Coverage gaps newly covered | 2");
    expect(body).toContain(HEAL_BOT_BOT_USERNAME);
    // Must never suggest auto-merge.
    expect(body.toLowerCase()).toContain("never auto-merges");
  });

  it("uses singular 'repair' for exactly one finding", () => {
    const body = renderHealBotPrBody({
      flakyFound: 1,
      deadFound: 0,
      coverageGapsFound: 0,
      headBranch: "feature/x",
      baseBranch: "main",
    });
    expect(body).toContain("1 repair");
    expect(body).not.toContain("1 repairs");
  });
});

// ---------------------------------------------------------------------------
// Pure helpers — buildHealBotSummary
// ---------------------------------------------------------------------------

describe("heal-bot — buildHealBotSummary", () => {
  it("returns 'suite healthy' when there are no findings", () => {
    expect(
      buildHealBotSummary({
        flakyFound: 0,
        deadFound: 0,
        coverageGapsFound: 0,
        prNumber: null,
        branchProduced: false,
      })
    ).toBe("suite healthy");
  });

  it("reports degraded reconfiguration hint when findings > 0 but no branch", () => {
    const s = buildHealBotSummary({
      flakyFound: 2,
      deadFound: 1,
      coverageGapsFound: 0,
      prNumber: null,
      branchProduced: false,
    });
    expect(s).toContain("3 findings");
    expect(s).toContain("no branch produced");
    expect(s).toContain("Gatetest");
  });

  it("embeds the PR number + counts when a branch was produced", () => {
    const s = buildHealBotSummary({
      flakyFound: 4,
      deadFound: 2,
      coverageGapsFound: 1,
      prNumber: 42,
      branchProduced: true,
    });
    expect(s).toBe("opened #42 (4 flaky, 2 dead, 1 coverage)");
  });

  it("handles a missing prNumber gracefully when branch is produced", () => {
    const s = buildHealBotSummary({
      flakyFound: 1,
      deadFound: 0,
      coverageGapsFound: 0,
      prNumber: null,
      branchProduced: true,
    });
    expect(s).toContain("(unknown PR)");
  });
});

// ---------------------------------------------------------------------------
// runHealBot — arg validation + graceful degradation.
//
// Because the test env has no DATABASE_URL, `startAgentRun` fails and
// `runHealBot` returns its documented "could not open agent_runs row" shape.
// That still proves the never-throws contract and shows that the DB is only
// ever touched via defensive helpers.
// ---------------------------------------------------------------------------

describe("heal-bot — runHealBot", () => {
  it("rejects missing args without throwing", async () => {
    const r = await runHealBot({ repositoryId: "" });
    expect(r.ok).toBe(false);
    expect(r.runId).toBeNull();
    expect(r.summary.toLowerCase()).toContain("invalid args");
  });

  it("rejects non-string repositoryId without throwing", async () => {
    const r = await runHealBot({
      // Intentional cast — simulates a caller passing bad data.
      repositoryId: 123 as unknown as string,
    });
    expect(r.ok).toBe(false);
    expect(r.runId).toBeNull();
  });

  it("returns a well-formed result when the DB is unavailable (scheduled)", async () => {
    // Mock fetch so a network call would fail loudly — proving the path
    // short-circuits before Gatetest is reached (we never even open a run).
    globalThis.fetch = (() => {
      throw new Error("fetch must not be called when run cannot be opened");
    }) as unknown as typeof fetch;
    const r = await runHealBot({
      repositoryId: "00000000-0000-0000-0000-000000000000",
    });
    // With no DATABASE_URL the run-opening step returns null and the agent
    // reports the documented failure without throwing.
    expect(r.ok).toBe(false);
    expect(r.runId).toBeNull();
    expect(r.summary.toLowerCase()).toContain("agent_runs");
  });

  it("treats triggerBy truthiness as the 'manual' switch", async () => {
    // We can't observe the trigger directly without a DB, but we can at least
    // prove the call completes cleanly when triggerBy is provided.
    const r = await runHealBot({
      repositoryId: "00000000-0000-0000-0000-000000000000",
      triggerBy: "11111111-1111-1111-1111-111111111111",
    });
    expect(r.ok).toBe(false); // no DB in test env
    expect(r.runId).toBeNull();
    // Must not have thrown — reaching this line is the assertion.
    expect(typeof r.summary).toBe("string");
  });
});

// ---------------------------------------------------------------------------
// Underlying Gatetest contract — we want the client's `offline` signal to
// propagate correctly, so we assert it here. If this contract breaks the
// heal-bot's "offline" branch never fires.
// ---------------------------------------------------------------------------

describe("heal-bot — gatetest client contract", () => {
  it("propagates offline:true when the API key is missing", async () => {
    // No GATETEST_API_KEY → client returns the offline shape, no fetch call.
    globalThis.fetch = (() => {
      throw new Error("fetch must not be called when offline");
    }) as unknown as typeof fetch;
    const result = await healSuite({ repo: "o/r" });
    expect(result.offline).toBe(true);
    expect(result.flakyFound).toBe(0);
    expect(result.deadFound).toBe(0);
    expect(result.coverageGapsFound).toBe(0);
    expect(result.prDraftBranch).toBeNull();
  });

  it("returns an offline-shaped result when fetch returns a non-200", async () => {
    process.env.GATETEST_API_KEY = "sk-test";
    globalThis.fetch = (async () =>
      new Response("fail", { status: 500 })) as unknown as typeof fetch;
    const result = await healSuite({ repo: "o/r" });
    // The client's contract is: any non-2xx → offline shape.
    expect(result.offline).toBe(true);
    expect(result.prDraftBranch).toBeNull();
  });

  it("surfaces the draft branch when Gatetest returns one", async () => {
    process.env.GATETEST_API_KEY = "sk-test";
    globalThis.fetch = (async () =>
      new Response(
        JSON.stringify({
          flakyFound: 2,
          deadFound: 1,
          coverageGapsFound: 3,
          prDraftBranch: "gatetest/heal-abc",
        }),
        { status: 200 }
      )) as unknown as typeof fetch;
    const result = await healSuite({ repo: "o/r" });
    expect(result.offline).toBe(false);
    expect(result.flakyFound).toBe(2);
    expect(result.deadFound).toBe(1);
    expect(result.coverageGapsFound).toBe(3);
    expect(result.prDraftBranch).toBe("gatetest/heal-abc");
  });

  it("normalises to zero when Gatetest returns zero findings + null branch", async () => {
    process.env.GATETEST_API_KEY = "sk-test";
    globalThis.fetch = (async () =>
      new Response(
        JSON.stringify({
          flakyFound: 0,
          deadFound: 0,
          coverageGapsFound: 0,
          prDraftBranch: null,
        }),
        { status: 200 }
      )) as unknown as typeof fetch;
    const result = await healSuite({ repo: "o/r" });
    expect(result.offline).toBe(false);
    expect(result.flakyFound).toBe(0);
    expect(result.deadFound).toBe(0);
    expect(result.coverageGapsFound).toBe(0);
    expect(result.prDraftBranch).toBeNull();
  });
});

// ---------------------------------------------------------------------------
// runHealBotForAll — empty repo set / DB failure handling
// ---------------------------------------------------------------------------

describe("heal-bot — runHealBotForAll", () => {
  it("returns zeroed aggregates when no repos are listable (no DB)", async () => {
    // No DATABASE_URL → listEligibleRepositoryIds returns []. We assert the
    // function terminates cleanly with a zero result and no throw.
    const agg = await runHealBotForAll();
    expect(agg).toEqual({
      started: 0,
      succeeded: 0,
      failed: 0,
      skipped: 0,
    });
  });

  it("does not invoke fetch when there are no repos to process", async () => {
    let fetchCalls = 0;
    globalThis.fetch = (async (...args: unknown[]) => {
      fetchCalls++;
      return new Response("", { status: 500 });
    }) as unknown as typeof fetch;
    await runHealBotForAll();
    expect(fetchCalls).toBe(0);
  });
});