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
triage-agent.test.ts12.2 KB · 369 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
/**
 * Block K4 — Triage agent tests.
 *
 * Pure-side tests only. We never touch Claude here — the happy path exercises
 * the deterministic "no AI backend" branch by clearing ANTHROPIC_API_KEY in
 * beforeEach, mirroring the style of src/__tests__/prod-signals.test.ts and
 * src/__tests__/copilot.test.ts.
 *
 * The triage agent's DB writes degrade gracefully (it calls `startAgentRun`
 * which catches exceptions and returns null), so running these tests without
 * a live DB still yields a well-shaped result object — just with runId null.
 */

import { describe, it, expect, beforeEach, afterEach } from "bun:test";
import {
  runTriageAgent,
  normaliseTriagePayload,
  validateTriageArgs,
  estimateHaikuCents,
  renderTriageComment,
  buildRunSummary,
  type TriageClassification,
} from "../../lib/agents/triage-agent";

const hadKey = !!process.env.ANTHROPIC_API_KEY;
const originalKey = process.env.ANTHROPIC_API_KEY;

beforeEach(() => {
  // Force the deterministic (no-AI) path. Individual tests that want to
  // simulate a key can set it locally and restore before returning.
  delete process.env.ANTHROPIC_API_KEY;
});

afterEach(() => {
  if (hadKey) {
    process.env.ANTHROPIC_API_KEY = originalKey;
  } else {
    delete process.env.ANTHROPIC_API_KEY;
  }
});

// ---------------------------------------------------------------------------
// validateTriageArgs — pure
// ---------------------------------------------------------------------------

describe("triage-agent — validateTriageArgs", () => {
  const base = {
    kind: "issue" as const,
    repositoryId: "00000000-0000-0000-0000-000000000000",
    itemId: "00000000-0000-0000-0000-000000000001",
    itemNumber: 1,
    title: "Something is broken",
    body: "Details here.",
  };

  it("accepts a well-formed issue", () => {
    expect(validateTriageArgs(base)).toEqual({ ok: true });
  });

  it("accepts a well-formed PR", () => {
    expect(validateTriageArgs({ ...base, kind: "pr" })).toEqual({ ok: true });
  });

  it("rejects an empty title", () => {
    const r = validateTriageArgs({ ...base, title: "   " });
    expect(r.ok).toBe(false);
    if (!r.ok) expect(r.reason).toMatch(/empty title/i);
  });

  it("rejects a missing title", () => {
    const r = validateTriageArgs({ ...base, title: undefined as unknown as string });
    expect(r.ok).toBe(false);
  });

  it("rejects an invalid kind", () => {
    const r = validateTriageArgs({
      ...base,
      kind: "wat" as unknown as "issue",
    });
    expect(r.ok).toBe(false);
    if (!r.ok) expect(r.reason).toMatch(/kind/);
  });

  it("rejects a missing repositoryId", () => {
    const r = validateTriageArgs({ ...base, repositoryId: "" });
    expect(r.ok).toBe(false);
  });

  it("rejects a non-finite itemNumber", () => {
    const r = validateTriageArgs({ ...base, itemNumber: NaN });
    expect(r.ok).toBe(false);
  });

  it("rejects a zero / negative itemNumber", () => {
    expect(validateTriageArgs({ ...base, itemNumber: 0 }).ok).toBe(false);
    expect(validateTriageArgs({ ...base, itemNumber: -7 }).ok).toBe(false);
  });

  it("accepts an empty body (body is not required content-wise)", () => {
    // A bare title with no body should still be triage-able.
    expect(validateTriageArgs({ ...base, body: "" })).toEqual({ ok: true });
  });
});

// ---------------------------------------------------------------------------
// normaliseTriagePayload — pure JSON coercion
// ---------------------------------------------------------------------------

describe("triage-agent — normaliseTriagePayload", () => {
  it("returns default classification for non-object input", () => {
    const out = normaliseTriagePayload(null);
    expect(out.category).toBe("chore");
    expect(out.complexity).toBe("unknown");
    expect(out.priority).toBe("unknown");
    expect(out.labels).toEqual([]);
    expect(out.suggestedReviewers).toEqual([]);
  });

  it("accepts a fully-valid blob untouched (modulo trimming)", () => {
    const out = normaliseTriagePayload({
      category: "bug",
      labels: ["auth", "regression"],
      complexity: "medium",
      priority: "high",
      riskArea: "session handling",
      reasoning: "Race between session revoke and cookie set.",
      suggestedReviewers: ["alice"],
    });
    expect(out.category).toBe("bug");
    expect(out.complexity).toBe("medium");
    expect(out.priority).toBe("high");
    expect(out.labels).toEqual(["auth", "regression"]);
    expect(out.suggestedReviewers).toEqual(["alice"]);
    expect(out.riskArea).toBe("session handling");
  });

  it("coerces out-of-vocab category/complexity/priority to defaults", () => {
    const out = normaliseTriagePayload({
      category: "rocketship",
      complexity: "XXL",
      priority: "blocker",
      reasoning: "nope",
    });
    expect(out.category).toBe("chore");
    expect(out.complexity).toBe("unknown");
    expect(out.priority).toBe("unknown");
  });

  it("drops unknown keys and non-string labels, dedupes + caps labels", () => {
    const many = Array.from({ length: 30 }, (_, i) => `label-${i}`);
    const out = normaliseTriagePayload({
      category: "feature",
      labels: [...many, "label-0", 42, null, "VALID-Label"],
      bogus: "ignored",
      complexity: "small",
      priority: "low",
      reasoning: "ok",
      suggestedReviewers: ["bob", "bob", 9, "carol", "dave", "eve"],
    });
    // Caps at 6, lower-cased, deduped.
    expect(out.labels.length).toBeLessThanOrEqual(6);
    expect(new Set(out.labels).size).toBe(out.labels.length);
    for (const l of out.labels) {
      expect(l).toBe(l.toLowerCase());
    }
    // Reviewers: deduped, cap 3.
    expect(out.suggestedReviewers.length).toBeLessThanOrEqual(3);
    expect(new Set(out.suggestedReviewers).size).toBe(
      out.suggestedReviewers.length
    );
  });

  it("caps reasoning and riskArea length", () => {
    const out = normaliseTriagePayload({
      category: "docs",
      reasoning: "x".repeat(5000),
      riskArea: "y".repeat(500),
    });
    expect(out.reasoning.length).toBeLessThanOrEqual(1200);
    expect(out.riskArea.length).toBeLessThanOrEqual(80);
  });

  it("falls back to a sentinel reasoning when the model omits one", () => {
    const out = normaliseTriagePayload({ category: "bug" });
    expect(out.reasoning).toMatch(/no reasoning/i);
  });
});

// ---------------------------------------------------------------------------
// Pricing
// ---------------------------------------------------------------------------

describe("triage-agent — estimateHaikuCents", () => {
  it("returns 0 for zero tokens", () => {
    expect(estimateHaikuCents(0, 0)).toBe(0);
  });

  it("is monotone in both inputs", () => {
    const a = estimateHaikuCents(1000, 200);
    const b = estimateHaikuCents(2000, 200);
    const c = estimateHaikuCents(1000, 400);
    expect(b).toBeGreaterThanOrEqual(a);
    expect(c).toBeGreaterThanOrEqual(a);
  });

  it("rounds up so any positive usage is at least 1 cent", () => {
    expect(estimateHaikuCents(1, 1)).toBe(1);
  });

  it("computes a reasonable value for a typical triage call (~2k in, ~200 out)", () => {
    // (2000 * 0.25 + 200 * 1.25) / 1e6 * 100 = 0.075 cents → ceil to 1.
    expect(estimateHaikuCents(2000, 200)).toBe(1);
  });

  it("ignores negative / non-finite inputs", () => {
    expect(estimateHaikuCents(-100, -50)).toBe(0);
    expect(estimateHaikuCents(Number.NaN, Number.NaN)).toBe(0);
  });
});

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

describe("triage-agent — renderTriageComment", () => {
  const sample: TriageClassification = {
    category: "bug",
    labels: ["auth", "regression"],
    complexity: "medium",
    priority: "high",
    riskArea: "session handling",
    reasoning: "Race between revoke and set.",
    suggestedReviewers: ["alice", "bob"],
  };

  it("begins with the ## Triage heading (required for the dedupe check)", () => {
    const out = renderTriageComment("issue", sample, true);
    expect(out.startsWith("## Triage")).toBe(true);
  });

  it("mentions that no AI backend is configured when aiAvailable=false", () => {
    const out = renderTriageComment("issue", sample, false);
    expect(out.toLowerCase()).toContain("no ai backend");
    expect(out.toLowerCase()).toContain("manual triage");
  });

  it("omits suggested-reviewers section for issues even if classification has them", () => {
    const out = renderTriageComment("issue", sample, true);
    expect(out).not.toMatch(/Suggested reviewers/i);
  });

  it("includes suggested-reviewers section for PRs", () => {
    const out = renderTriageComment("pr", sample, true);
    expect(out).toMatch(/Suggested reviewers/i);
    expect(out).toContain("@alice");
  });

  it("always includes the non-destructive disclaimer footer", () => {
    const out = renderTriageComment("pr", sample, true);
    expect(out).toMatch(/non-destructive suggestion/i);
  });
});

// ---------------------------------------------------------------------------
// buildRunSummary
// ---------------------------------------------------------------------------

describe("triage-agent — buildRunSummary", () => {
  it("references 'no AI backend' when aiAvailable=false", () => {
    const s = buildRunSummary(
      {
        category: "bug",
        labels: [],
        complexity: "small",
        priority: "low",
        riskArea: "x",
        reasoning: "y",
        suggestedReviewers: [],
      },
      false
    );
    expect(s.toLowerCase()).toContain("no ai backend");
  });

  it("mentions category + complexity when AI ran", () => {
    const s = buildRunSummary(
      {
        category: "feature",
        labels: [],
        complexity: "large",
        priority: "medium",
        riskArea: "x",
        reasoning: "y",
        suggestedReviewers: [],
      },
      true
    );
    expect(s).toContain("feature");
    expect(s).toContain("large");
  });
});

// ---------------------------------------------------------------------------
// runTriageAgent — integration-lite
//
// Without ANTHROPIC_API_KEY (forced by beforeEach) the agent hits the
// deterministic path. We can't verify DB side-effects without a live Postgres,
// but we CAN verify:
//   - it never throws
//   - it returns a well-shaped object
//   - the summary references the no-AI path when the DB is absent (in which
//     case startAgentRun returns null and runTriageAgent gives up cleanly).
// ---------------------------------------------------------------------------

describe("triage-agent — runTriageAgent graceful degradation", () => {
  const base = {
    kind: "issue" as const,
    repositoryId: "00000000-0000-0000-0000-000000000000",
    itemId: "00000000-0000-0000-0000-000000000001",
    itemNumber: 1,
    title: "Sample bug",
    body: "Something went wrong.",
  };

  it("returns { ok: false, runId: null } for invalid args, no throw", async () => {
    const r = await runTriageAgent({ ...base, title: "" });
    expect(r.ok).toBe(false);
    expect(r.runId).toBeNull();
    expect(typeof r.summary).toBe("string");
    expect(r.summary).toMatch(/invalid args/i);
  });

  it("returns a well-shaped result even when the DB is unavailable", async () => {
    // startAgentRun catches DB failures and returns null; runTriageAgent
    // propagates that as {ok:false, summary:'could not open agent_runs row'}.
    // If a live DB IS connected, we instead get ok:true and a non-null runId.
    // Either way the function resolves.
    const r = await runTriageAgent(base);
    expect(r).toBeDefined();
    expect(typeof r.ok).toBe("boolean");
    expect(typeof r.summary).toBe("string");
    expect(r.summary.length).toBeGreaterThan(0);
  });

  it("never throws for a PR with an empty body", async () => {
    await expect(
      runTriageAgent({ ...base, kind: "pr", body: "" })
    ).resolves.toBeDefined();
  });

  it("never throws for a PR whose body is missing entirely", async () => {
    await expect(
      runTriageAgent({
        ...base,
        kind: "pr",
        body: undefined as unknown as string,
      })
    ).resolves.toBeDefined();
  });

  it("rejects kind='neither' without side effects", async () => {
    const r = await runTriageAgent({
      ...base,
      kind: "neither" as unknown as "issue",
    });
    expect(r.ok).toBe(false);
    expect(r.runId).toBeNull();
  });
});