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-release-notes.test.ts16.5 KB · 519 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
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
/**
 * Tests for src/lib/ai-release-notes.ts.
 *
 * Two layers:
 *
 *   1. Pure helpers — bucketing, prompt assembly, markdown rendering.
 *      No DB / no Claude. Always run.
 *
 *   2. End-to-end through `generateReleaseNotes` with a fake Claude
 *      client + a real bare repo on disk. DB-touching assertions are
 *      gated on DATABASE_URL via the HAS_DB skipIf pattern used across
 *      the rest of the suite.
 */

import { describe, it, expect, beforeAll, afterAll } from "bun:test";
import { join } from "path";
import { rm, mkdir } from "fs/promises";
import {
  bucketPrs,
  buildReleaseNotesPrompt,
  classifyPr,
  generateReleaseNotes,
  isSemverTag,
  mergeClaudeSections,
  prNumberFromCommitMessage,
  renderPrBullet,
  renderSectionsToMarkdown,
  resolvePrsForCommits,
  type ResolvedPullRequest,
  type ReleaseSections,
} from "../lib/ai-release-notes";
import {
  initBareRepo,
  createOrUpdateFileOnBranch,
  createTag,
  resolveRef,
} from "../git/repository";
import { db } from "../db";
import { eq } from "drizzle-orm";
import {
  pullRequests,
  repositories,
  users,
} from "../db/schema";

const HAS_DB = Boolean(process.env.DATABASE_URL);

const TEST_REPOS = join(
  import.meta.dir,
  "../../.test-repos-ai-release-notes-" + Date.now()
);

beforeAll(async () => {
  process.env.GIT_REPOS_PATH = TEST_REPOS;
  await rm(TEST_REPOS, { recursive: true, force: true });
  await mkdir(TEST_REPOS, { recursive: true });
});

afterAll(async () => {
  await rm(TEST_REPOS, { recursive: true, force: true });
});

// ---------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------

function pr(overrides: Partial<ResolvedPullRequest>): ResolvedPullRequest {
  return {
    number: 1,
    title: "feat: thing",
    body: null,
    authorUsername: "alice",
    headBranch: "feature/x",
    mergedAt: new Date("2026-01-01T00:00:00Z"),
    labels: [],
    autoMergedByAi: false,
    ...overrides,
  };
}

describe("classifyPr", () => {
  it("routes auto-merged PRs to ai_changes", () => {
    expect(classifyPr(pr({ autoMergedByAi: true }))).toBe("ai_changes");
  });

  it("routes by label first", () => {
    expect(classifyPr(pr({ title: "anything", labels: ["security"] }))).toBe(
      "security"
    );
    expect(classifyPr(pr({ title: "anything", labels: ["bug"] }))).toBe(
      "fixes"
    );
    expect(classifyPr(pr({ title: "anything", labels: ["ai:feature"] }))).toBe(
      "features"
    );
    expect(classifyPr(pr({ title: "anything", labels: ["ai:auto-merge"] }))).toBe(
      "ai_changes"
    );
  });

  it("falls back to conventional-commit prefix on the title", () => {
    expect(classifyPr(pr({ title: "feat: new x" }))).toBe("features");
    expect(classifyPr(pr({ title: "feat(api): scoped" }))).toBe("features");
    expect(classifyPr(pr({ title: "fix: bug" }))).toBe("fixes");
    expect(classifyPr(pr({ title: "perf: faster" }))).toBe("perf");
    expect(classifyPr(pr({ title: "docs: readme" }))).toBe("docs");
    expect(classifyPr(pr({ title: "security: sanitise" }))).toBe("security");
  });

  it("dumps anything unclassified into 'other'", () => {
    expect(classifyPr(pr({ title: "tidy up" }))).toBe("other");
    expect(classifyPr(pr({ title: "refactor: split file" }))).toBe("other");
  });
});

describe("renderPrBullet", () => {
  it("strips the conventional-commit prefix and adds attribution", () => {
    const out = renderPrBullet(pr({ number: 42, title: "feat(api): scoped thing", authorUsername: "bob" }));
    expect(out).toBe("scoped thing (#42) — @bob");
  });
});

describe("bucketPrs", () => {
  it("groups PRs into the right sections", () => {
    const sections = bucketPrs([
      pr({ number: 1, title: "feat: A" }),
      pr({ number: 2, title: "fix: B" }),
      pr({ number: 3, title: "perf: C" }),
      pr({ number: 4, title: "anything", autoMergedByAi: true }),
      pr({ number: 5, title: "refactor: D" }),
    ]);
    expect(sections.features.bullets.length).toBe(1);
    expect(sections.fixes.bullets.length).toBe(1);
    expect(sections.perf.bullets.length).toBe(1);
    expect(sections.ai_changes.bullets.length).toBe(1);
    expect(sections.other.bullets.length).toBe(1);
    expect(sections.security.bullets.length).toBe(0);
    expect(sections.docs.bullets.length).toBe(0);
  });
});

describe("prNumberFromCommitMessage", () => {
  it("recognises GitHub-style merge commits", () => {
    expect(prNumberFromCommitMessage("Merge pull request #42 from foo/bar")).toBe(42);
  });
  it("recognises squash subjects", () => {
    expect(prNumberFromCommitMessage("feat: stuff (#7)")).toBe(7);
  });
  it("returns null on missing", () => {
    expect(prNumberFromCommitMessage("plain commit")).toBeNull();
  });
});

describe("buildReleaseNotesPrompt", () => {
  it("embeds repo, range, grouped sections, and raw PRs", () => {
    const sections: ReleaseSections = {
      features: { bullets: ["A (#1) — @alice"] },
      fixes: { bullets: [] },
      perf: { bullets: [] },
      docs: { bullets: [] },
      security: { bullets: [] },
      ai_changes: { bullets: [] },
      other: { bullets: [] },
    };
    const prompt = buildReleaseNotesPrompt({
      repoFullName: "alice/demo",
      fromTag: "v1.0.0",
      toTag: "v1.1.0",
      sections,
      prs: [pr({ number: 1, title: "feat: A" })],
    });
    expect(prompt).toContain("alice/demo");
    expect(prompt).toContain("v1.0.0");
    expect(prompt).toContain("v1.1.0");
    expect(prompt).toContain("features:");
    expect(prompt).toContain("A (#1) — @alice");
    expect(prompt).toContain('"sections"');
    expect(prompt).toContain('"headline"');
  });

  it("notes the initial release case when fromTag is null", () => {
    const prompt = buildReleaseNotesPrompt({
      repoFullName: "alice/demo",
      fromTag: null,
      toTag: "v0.1.0",
      sections: {
        features: { bullets: [] },
        fixes: { bullets: [] },
        perf: { bullets: [] },
        docs: { bullets: [] },
        security: { bullets: [] },
        ai_changes: { bullets: [] },
        other: { bullets: [] },
      },
      prs: [],
    });
    expect(prompt).toContain("(initial)");
  });
});

describe("mergeClaudeSections", () => {
  const deterministic: ReleaseSections = {
    features: { bullets: ["thing (#1) — @alice"] },
    fixes: { bullets: ["bug (#2) — @bob"] },
    perf: { bullets: [] },
    docs: { bullets: [] },
    security: { bullets: [] },
    ai_changes: { bullets: [] },
    other: { bullets: [] },
  };

  it("returns deterministic when Claude is null", () => {
    expect(mergeClaudeSections(deterministic, null)).toEqual(deterministic);
  });

  it("prefers Claude wording when it covers all bullets", () => {
    const merged = mergeClaudeSections(deterministic, {
      sections: {
        features: { bullets: ["Add the thing (#1) — @alice"] },
      },
    });
    expect(merged.features.bullets).toEqual(["Add the thing (#1) — @alice"]);
    // Untouched bucket stays deterministic.
    expect(merged.fixes.bullets).toEqual(["bug (#2) — @bob"]);
  });

  it("keeps deterministic when Claude drops bullets", () => {
    const merged = mergeClaudeSections(deterministic, {
      sections: {
        // Claude returned fewer items than we know about — distrust.
        fixes: { bullets: [] },
      },
    });
    expect(merged.fixes.bullets).toEqual(["bug (#2) — @bob"]);
  });
});

describe("renderSectionsToMarkdown", () => {
  it("emits a header, headline, summary, and ordered sections", () => {
    const md = renderSectionsToMarkdown({
      repoFullName: "alice/demo",
      fromTag: "v1.0.0",
      toTag: "v1.1.0",
      headline: "Stability + speed.",
      summary: "This release tightens the merge queue.",
      sections: {
        features: { bullets: ["A (#1) — @alice"] },
        fixes: { bullets: ["B (#2) — @bob"] },
        perf: { bullets: [] },
        docs: { bullets: [] },
        security: { bullets: ["sanitise (#3) — @carol"] },
        ai_changes: { bullets: [] },
        other: { bullets: [] },
      },
    });
    expect(md).toContain("## v1.1.0 (since v1.0.0)");
    expect(md).toContain("**Stability + speed.**");
    expect(md).toContain("This release tightens the merge queue.");
    // Features comes before fixes, which comes before security.
    const feat = md.indexOf("### Features");
    const fixIdx = md.indexOf("### Bug fixes");
    const sec = md.indexOf("### Security");
    expect(feat).toBeGreaterThan(0);
    expect(fixIdx).toBeGreaterThan(feat);
    expect(sec).toBeGreaterThan(fixIdx);
    expect(md).toContain("- A (#1) — @alice");
    expect(md).toContain("- B (#2) — @bob");
    // Empty sections are skipped.
    expect(md).not.toContain("### Performance");
    expect(md).not.toContain("### Documentation");
  });

  it("skips the headline + summary lines when both are empty", () => {
    const md = renderSectionsToMarkdown({
      repoFullName: "alice/demo",
      fromTag: null,
      toTag: "v0.1.0",
      headline: "",
      summary: "",
      sections: {
        features: { bullets: [] },
        fixes: { bullets: [] },
        perf: { bullets: [] },
        docs: { bullets: [] },
        security: { bullets: [] },
        ai_changes: { bullets: [] },
        other: { bullets: [] },
      },
    });
    expect(md).toContain("## v0.1.0");
    expect(md).not.toContain("**");
    expect(md).toContain("(initial)...v0.1.0");
  });
});

describe("isSemverTag", () => {
  it("accepts vX.Y.Z and X.Y.Z", () => {
    expect(isSemverTag("v1.2.3")).toBe(true);
    expect(isSemverTag("1.2.3")).toBe(true);
    expect(isSemverTag("v0.1.0-beta.1")).toBe(true);
  });
  it("rejects garbage", () => {
    expect(isSemverTag("release-2024-01")).toBe(false);
    expect(isSemverTag("v1")).toBe(false);
    expect(isSemverTag("nightly")).toBe(false);
  });
});

// ---------------------------------------------------------------------------
// End-to-end with fake Claude + real bare repo. DB-backed.
// ---------------------------------------------------------------------------

/**
 * Fake Anthropic client returning a canned JSON envelope. Matches the
 * shape ai-release-notes's parser expects.
 */
function fakeClient(responseText: string) {
  return {
    messages: {
      create: async () => ({
        content: [{ type: "text" as const, text: responseText }],
      }),
    },
  } as any;
}

describe.skipIf(!HAS_DB)("generateReleaseNotes — end-to-end with fake Claude", () => {
  const OWNER = `relnotes_${Date.now().toString(36)}`;
  const REPO = "subject";
  let repositoryId = "";
  let userId = "";
  let toSha = "";

  beforeAll(async () => {
    // Seed user + repo + bare git repo on disk with two commits and two tags.
    const [u] = await db
      .insert(users)
      .values({
        username: OWNER,
        email: `${OWNER}@example.com`,
        passwordHash: "x",
      })
      .returning({ id: users.id });
    userId = u.id;

    const [r] = await db
      .insert(repositories)
      .values({
        ownerId: userId,
        name: REPO,
        diskPath: `/tmp/${OWNER}/${REPO}`,
        defaultBranch: "main",
      })
      .returning({ id: repositories.id });
    repositoryId = r.id;

    await initBareRepo(OWNER, REPO);

    const seed = await createOrUpdateFileOnBranch({
      owner: OWNER,
      name: REPO,
      branch: "main",
      filePath: "README.md",
      bytes: new TextEncoder().encode("# v1\n"),
      message: "initial commit",
      authorName: "Seeder",
      authorEmail: "seed@example.com",
    });
    if ("error" in seed) throw new Error(`seed failed: ${seed.error}`);
    await createTag(OWNER, REPO, "v1.0.0", seed.commitSha, "v1.0.0");

    // Commit referencing PR #1 — landed as a squash subject.
    const c1 = await createOrUpdateFileOnBranch({
      owner: OWNER,
      name: REPO,
      branch: "main",
      filePath: "src/feature.ts",
      bytes: new TextEncoder().encode("export const f = 1;\n"),
      message: "feat: add feature (#1)",
      authorName: "Alice",
      authorEmail: "alice@example.com",
    });
    if ("error" in c1) throw new Error(`c1 failed: ${c1.error}`);

    // Commit referencing PR #2 — a fix.
    const c2 = await createOrUpdateFileOnBranch({
      owner: OWNER,
      name: REPO,
      branch: "main",
      filePath: "src/fix.ts",
      bytes: new TextEncoder().encode("export const fixed = true;\n"),
      message: "fix: handle null case (#2)",
      authorName: "Bob",
      authorEmail: "bob@example.com",
    });
    if ("error" in c2) throw new Error(`c2 failed: ${c2.error}`);

    await createTag(OWNER, REPO, "v1.1.0", c2.commitSha, "v1.1.0");
    toSha = c2.commitSha;

    // Insert two merged PR rows so cross-referencing succeeds.
    await db.insert(pullRequests).values({
      repositoryId,
      authorId: userId,
      title: "feat: add feature",
      body: "Adds the feature.",
      state: "merged",
      baseBranch: "main",
      headBranch: "feature/x",
      mergedAt: new Date(),
      number: 1,
    });
    await db.insert(pullRequests).values({
      repositoryId,
      authorId: userId,
      title: "fix: handle null case",
      body: "Crash fix.",
      state: "merged",
      baseBranch: "main",
      headBranch: "fix/y",
      mergedAt: new Date(),
      number: 2,
    });
  });

  afterAll(async () => {
    // Cleanup — cascades handle PRs / releases.
    if (repositoryId) {
      await db.delete(repositories).where(eq(repositories.id, repositoryId));
    }
    if (userId) {
      await db.delete(users).where(eq(users.id, userId));
    }
  });

  it("cross-references PRs from the commit range", async () => {
    const fromSha = await resolveRef(OWNER, REPO, "v1.0.0");
    expect(fromSha).toBeTruthy();
    expect(toSha).toBeTruthy();
    const { commitsBetween } = await import("../git/repository");
    const commits = await commitsBetween(OWNER, REPO, fromSha, toSha);
    expect(commits.length).toBe(2);

    const prs = await resolvePrsForCommits(repositoryId, commits);
    expect(prs.length).toBe(2);
    const nums = prs.map((p) => p.number).sort();
    expect(nums).toEqual([1, 2]);
  });

  it("renders structured output into markdown with section grouping", async () => {
    const claudeOut = JSON.stringify({
      headline: "Feature + fix.",
      summary: "Adds the new feature and patches the null crash.",
      sections: {
        features: { bullets: ["Add feature (#1) — @" + OWNER] },
        fixes: { bullets: ["Handle null (#2) — @" + OWNER] },
      },
    });

    const result = await generateReleaseNotes({
      repositoryId,
      fromTag: "v1.0.0",
      toTag: "v1.1.0",
      client: fakeClient(claudeOut),
    });

    expect(result.aiUsed).toBe(true);
    expect(result.prCount).toBe(2);
    expect(result.headline).toBe("Feature + fix.");
    expect(result.summary).toContain("Adds the new feature");
    expect(result.sections.features.bullets.length).toBe(1);
    expect(result.sections.fixes.bullets.length).toBe(1);
    expect(result.markdown).toContain("## v1.1.0 (since v1.0.0)");
    expect(result.markdown).toContain("**Feature + fix.**");
    expect(result.markdown).toContain("### Features");
    expect(result.markdown).toContain("### Bug fixes");
    expect(result.markdown).toContain("Add feature (#1)");
  });

  it("falls back to deterministic markdown when Claude returns garbage", async () => {
    const result = await generateReleaseNotes({
      repositoryId,
      fromTag: "v1.0.0",
      toTag: "v1.1.0",
      client: fakeClient("not json at all"),
    });
    expect(result.aiUsed).toBe(false);
    // Even without Claude, sections must be populated from the PR cross-ref.
    expect(result.sections.features.bullets.length).toBeGreaterThan(0);
    expect(result.sections.fixes.bullets.length).toBeGreaterThan(0);
    expect(result.markdown).toContain("### Features");
    expect(result.markdown).toContain("### Bug fixes");
  });

  it("returns a non-empty markdown even when no PRs match", async () => {
    // Generate notes for the initial-tag → initial-tag range (no commits).
    const result = await generateReleaseNotes({
      repositoryId,
      fromTag: "v1.0.0",
      toTag: "v1.0.0",
      client: fakeClient("{}"),
    });
    expect(result.markdown).toContain("v1.0.0");
    expect(result.prCount).toBe(0);
  });
});

describe("generateReleaseNotes — repo not found", () => {
  it("returns a graceful fallback for an unknown repository id", async () => {
    const result = await generateReleaseNotes({
      repositoryId: "00000000-0000-0000-0000-000000000000",
      fromTag: null,
      toTag: "v1.0.0",
    });
    expect(result.prCount).toBe(0);
    expect(result.aiUsed).toBe(false);
    expect(result.markdown).toContain("v1.0.0");
  });
});