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.ts17.4 KB · 566 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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/**
 * Block K4 — Autonomous triage agent.
 *
 * Runs on top of the Wave 1 agent-runtime substrate. On issue / PR open we:
 *
 *   1. Open an `agent_runs` row (kind = "triage").
 *   2. Ask Claude Haiku for a structured classification.
 *   3. Post a **single** comment on the issue or PR summarising the triage.
 *
 * Non-destructive: we never apply labels, close, or assign. We only comment.
 * When the caller's repo hasn't wired up an ANTHROPIC_API_KEY we still record
 * the run and post a minimal deterministic "manual triage required" comment —
 * so the audit trail is complete either way.
 *
 * Style mirrors src/lib/ai-incident.ts (the D4 cleanest-example) and the pre-
 * existing `triagePullRequest` in src/lib/ai-generators.ts which this upgrades.
 * Never throws; all DB / Anthropic errors are caught and become a "failed" run.
 */

import { and, eq } from "drizzle-orm";
import { db } from "../../db";
import {
  issueComments,
  issues,
  prComments,
  pullRequests,
  repositories,
} from "../../db/schema";
import {
  MODEL_HAIKU,
  extractText,
  getAnthropic,
  isAiAvailable,
  parseJsonResponse,
} from "../ai-client";
import {
  executeAgentRun,
  startAgentRun,
  type AgentExecutorContext,
} from "../agent-runtime";

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

export type TriageItemKind = "issue" | "pr";

export type TriageCategory =
  | "bug"
  | "feature"
  | "question"
  | "docs"
  | "chore"
  | "security";

export type TriageComplexity = "small" | "medium" | "large" | "unknown";

export type TriagePriority =
  | "low"
  | "medium"
  | "high"
  | "critical"
  | "unknown";

export interface TriageClassification {
  category: TriageCategory;
  labels: string[];
  complexity: TriageComplexity;
  priority: TriagePriority;
  riskArea: string;
  reasoning: string;
  suggestedReviewers: string[];
}

export interface RunTriageAgentArgs {
  kind: TriageItemKind;
  repositoryId: string;
  itemId: string;
  itemNumber: number;
  title: string;
  body: string;
  authorId?: string;
}

export interface RunTriageAgentResult {
  ok: boolean;
  summary: string;
  runId: string | null;
}

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

const ALLOWED_CATEGORIES: ReadonlySet<TriageCategory> = new Set([
  "bug",
  "feature",
  "question",
  "docs",
  "chore",
  "security",
]);

const ALLOWED_COMPLEXITY: ReadonlySet<TriageComplexity> = new Set([
  "small",
  "medium",
  "large",
  "unknown",
]);

const ALLOWED_PRIORITY: ReadonlySet<TriagePriority> = new Set([
  "low",
  "medium",
  "high",
  "critical",
  "unknown",
]);

const DEFAULT_CLASSIFICATION: TriageClassification = {
  category: "chore",
  labels: [],
  complexity: "unknown",
  priority: "unknown",
  riskArea: "unknown",
  reasoning: "No AI backend configured; manual triage required.",
  suggestedReviewers: [],
};

const LABEL_MAX_LEN = 32;
const LABELS_MAX = 6;
const REVIEWERS_MAX = 3;
const REASONING_MAX = 1200;
const RISK_AREA_MAX = 80;

/** Trim + cap a free-form string to `max` chars. */
function capString(v: unknown, max: number): string {
  if (typeof v !== "string") return "";
  const t = v.trim();
  return t.length <= max ? t : t.slice(0, max);
}

/**
 * Coerce an arbitrary JSON blob from Claude into the strict
 * TriageClassification shape. Any unknown keys are dropped; out-of-vocab
 * values are replaced with defaults. Pure — no I/O.
 */
export function normaliseTriagePayload(
  raw: unknown
): TriageClassification {
  if (!raw || typeof raw !== "object") {
    return { ...DEFAULT_CLASSIFICATION };
  }
  const r = raw as Record<string, unknown>;

  const category = ALLOWED_CATEGORIES.has(r.category as TriageCategory)
    ? (r.category as TriageCategory)
    : DEFAULT_CLASSIFICATION.category;

  const complexity = ALLOWED_COMPLEXITY.has(r.complexity as TriageComplexity)
    ? (r.complexity as TriageComplexity)
    : "unknown";

  const priority = ALLOWED_PRIORITY.has(r.priority as TriagePriority)
    ? (r.priority as TriagePriority)
    : "unknown";

  const labels = Array.isArray(r.labels)
    ? r.labels
        .filter((l): l is string => typeof l === "string" && l.trim().length > 0)
        .map((l) => l.trim().toLowerCase().slice(0, LABEL_MAX_LEN))
        .filter((l, i, arr) => arr.indexOf(l) === i)
        .slice(0, LABELS_MAX)
    : [];

  const suggestedReviewers = Array.isArray(r.suggestedReviewers)
    ? r.suggestedReviewers
        .filter((u): u is string => typeof u === "string" && u.trim().length > 0)
        .map((u) => u.trim().slice(0, 64))
        .filter((u, i, arr) => arr.indexOf(u) === i)
        .slice(0, REVIEWERS_MAX)
    : [];

  return {
    category,
    labels,
    complexity,
    priority,
    riskArea: capString(r.riskArea, RISK_AREA_MAX) || "unknown",
    reasoning:
      capString(r.reasoning, REASONING_MAX) ||
      "(no reasoning supplied by model)",
    suggestedReviewers,
  };
}

/** Validate caller args before we touch the DB. */
export function validateTriageArgs(
  args: RunTriageAgentArgs
): { ok: true } | { ok: false; reason: string } {
  if (!args) return { ok: false, reason: "missing args" };
  if (args.kind !== "issue" && args.kind !== "pr") {
    return { ok: false, reason: "invalid kind" };
  }
  if (!args.repositoryId || typeof args.repositoryId !== "string") {
    return { ok: false, reason: "missing repositoryId" };
  }
  if (!args.itemId || typeof args.itemId !== "string") {
    return { ok: false, reason: "missing itemId" };
  }
  if (!Number.isFinite(args.itemNumber) || args.itemNumber <= 0) {
    return { ok: false, reason: "invalid itemNumber" };
  }
  if (typeof args.title !== "string" || args.title.trim().length === 0) {
    return { ok: false, reason: "empty title" };
  }
  return { ok: true };
}

/**
 * Haiku pricing (per BUILD_BIBLE §5.3):
 *   input  ≈ $0.25 / 1M tokens
 *   output ≈ $1.25 / 1M tokens
 * We round UP to whole cents so a zero-cost run at least records the attempt.
 */
export function estimateHaikuCents(
  inputTokens: number,
  outputTokens: number
): number {
  const dIn = Math.max(0, inputTokens | 0);
  const dOut = Math.max(0, outputTokens | 0);
  const dollars = (dIn * 0.25 + dOut * 1.25) / 1_000_000;
  return Math.ceil(dollars * 100);
}

/** Render the comment body. Exported so tests can assert on its shape. */
export function renderTriageComment(
  kind: TriageItemKind,
  classification: TriageClassification,
  aiAvailable: boolean
): string {
  const heading = "## Triage";
  const botLine = aiAvailable
    ? "_Posted by GlueCron triage agent (suggestion only — no labels applied)._"
    : "_Posted by GlueCron triage agent — no AI backend configured; manual triage required._";

  const lines: string[] = [
    heading,
    "",
    botLine,
    "",
    `- **Category:** \`${classification.category}\``,
    `- **Complexity:** \`${classification.complexity}\``,
    `- **Priority:** \`${classification.priority}\``,
    `- **Risk area:** ${classification.riskArea || "unknown"}`,
  ];
  if (classification.labels.length) {
    lines.push(
      `- **Suggested labels:** ${classification.labels
        .map((l) => `\`${l}\``)
        .join(", ")}`
    );
  }
  if (
    kind === "pr" &&
    classification.suggestedReviewers.length > 0
  ) {
    lines.push(
      `- **Suggested reviewers:** ${classification.suggestedReviewers
        .map((u) => `@${u.replace(/^@/, "")}`)
        .join(", ")}`
    );
  }
  lines.push("", "### Reasoning", classification.reasoning);
  lines.push(
    "",
    "---",
    "_This is a non-destructive suggestion. A maintainer must apply any labels, assignments, or state changes._"
  );
  return lines.join("\n");
}

/** Short human sentence for the `agent_runs.summary` column. */
export function buildRunSummary(
  classification: TriageClassification,
  aiAvailable: boolean
): string {
  if (!aiAvailable) {
    return "no AI backend configured; manual triage required";
  }
  return `classified as ${classification.category}, complexity ${classification.complexity}`;
}

// ---------------------------------------------------------------------------
// Internal: Claude call
// ---------------------------------------------------------------------------

function buildPrompt(args: RunTriageAgentArgs): string {
  const kindLabel = args.kind === "pr" ? "pull request" : "issue";
  const body = (args.body || "(no body)").slice(0, 4000);
  return `You are GlueCron's triage agent. Classify this newly opened ${kindLabel}.

Respond ONLY with JSON of this exact shape (no prose, no code fences):
{
  "category": "bug" | "feature" | "question" | "docs" | "chore" | "security",
  "labels": ["short-label", ...],
  "complexity": "small" | "medium" | "large" | "unknown",
  "priority": "low" | "medium" | "high" | "critical" | "unknown",
  "riskArea": "short phrase, e.g. 'auth/session handling'",
  "reasoning": "2-4 sentences explaining your classification.",
  "suggestedReviewers": ["username", ...]
}

Rules:
- "labels" must be 0-6 short kebab-case strings (<= 32 chars each).
- "suggestedReviewers" is optional; at most 3 usernames. Omit the field if you have no suggestions.
- Use "unknown" for complexity/priority when the text is too thin to judge.
- Use category "security" for anything involving auth, credentials, or vulnerability reports.

Title: ${args.title}
Body:
${body}
`;
}

async function askClaudeForTriage(
  args: RunTriageAgentArgs,
  ctx: AgentExecutorContext
): Promise<{
  classification: TriageClassification;
  inputTokens: number;
  outputTokens: number;
} | null> {
  try {
    const client = getAnthropic();
    const prompt = buildPrompt(args);
    const message = await client.messages.create({
      model: MODEL_HAIKU,
      max_tokens: 512,
      messages: [{ role: "user", content: prompt }],
    });
    const text = extractText(message);
    const parsed = parseJsonResponse<unknown>(text);
    const classification = normaliseTriagePayload(parsed);

    // Anthropic SDK surfaces token usage on `usage`. Fall back to rough
    // heuristic if the field isn't present so we always record *something*.
    const usage = (message as { usage?: { input_tokens?: number; output_tokens?: number } }).usage;
    const inputTokens =
      typeof usage?.input_tokens === "number"
        ? usage.input_tokens
        : Math.ceil(prompt.length / 4);
    const outputTokens =
      typeof usage?.output_tokens === "number"
        ? usage.output_tokens
        : Math.ceil(text.length / 4);

    await ctx.appendLog(
      `[triage] haiku returned ${text.length} chars; tokens in=${inputTokens} out=${outputTokens}`
    );
    return { classification, inputTokens, outputTokens };
  } catch (err) {
    await ctx.appendLog(
      `[triage] anthropic call failed: ${(err as Error).message}`
    );
    console.error("[triage-agent] askClaudeForTriage:", err);
    return null;
  }
}

// ---------------------------------------------------------------------------
// Comment author resolution
//
// issueComments.authorId and prComments.authorId are NOT NULL — we need a real
// user row. Preference order:
//   1. the caller-supplied authorId (typically the item's creator),
//   2. the item's own author (looked up from the DB),
//   3. the repository owner (last resort).
// This mirrors ai-incident.ts and the existing ai-review path in pulls.tsx.
// ---------------------------------------------------------------------------

async function resolveCommentAuthorId(
  args: RunTriageAgentArgs
): Promise<string | null> {
  if (args.authorId) return args.authorId;
  try {
    if (args.kind === "issue") {
      const [row] = await db
        .select({ authorId: issues.authorId })
        .from(issues)
        .where(eq(issues.id, args.itemId))
        .limit(1);
      if (row?.authorId) return row.authorId;
    } else {
      const [row] = await db
        .select({ authorId: pullRequests.authorId })
        .from(pullRequests)
        .where(eq(pullRequests.id, args.itemId))
        .limit(1);
      if (row?.authorId) return row.authorId;
    }
  } catch (err) {
    console.error("[triage-agent] resolveCommentAuthorId item lookup:", err);
  }
  try {
    const [row] = await db
      .select({ ownerId: repositories.ownerId })
      .from(repositories)
      .where(eq(repositories.id, args.repositoryId))
      .limit(1);
    if (row?.ownerId) return row.ownerId;
  } catch (err) {
    console.error("[triage-agent] resolveCommentAuthorId owner lookup:", err);
  }
  return null;
}

/**
 * Have we already triaged this item? We rely on the marker line from the
 * heading — "## Triage" is unique enough. This avoids stacking duplicate
 * comments if a caller fires the trigger twice (e.g. retry after 500).
 */
async function alreadyTriaged(
  kind: TriageItemKind,
  itemId: string
): Promise<boolean> {
  try {
    if (kind === "issue") {
      const rows = await db
        .select({ body: issueComments.body })
        .from(issueComments)
        .where(eq(issueComments.issueId, itemId));
      return rows.some((r) => (r.body || "").startsWith("## Triage"));
    }
    const rows = await db
      .select({ body: prComments.body })
      .from(prComments)
      .where(
        and(
          eq(prComments.pullRequestId, itemId),
          eq(prComments.isAiReview, true)
        )
      );
    return rows.some((r) => (r.body || "").startsWith("## Triage"));
  } catch (err) {
    console.error("[triage-agent] alreadyTriaged:", err);
    return false; // on failure, prefer to post rather than silently skip
  }
}

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

/**
 * Kick off a triage run for a newly-opened issue or PR. Non-destructive.
 * Never throws. Always returns `{ ok, summary, runId }` — even when input
 * validation fails or the DB is unavailable, in which case `runId` is null.
 */
export async function runTriageAgent(
  args: RunTriageAgentArgs
): Promise<RunTriageAgentResult> {
  // 1. Validate eagerly — we don't want to open an agent_runs row for a
  //    clearly-malformed caller (which is almost certainly a dev bug).
  const check = validateTriageArgs(args);
  if (!check.ok) {
    return { ok: false, summary: `invalid args: ${check.reason}`, runId: null };
  }

  // 2. Open the run. If the DB is down this returns null and we give up —
  //    there's nowhere to record logs without the row.
  const run = await startAgentRun({
    repositoryId: args.repositoryId,
    kind: "triage",
    trigger: args.kind === "issue" ? "issue.opened" : "pr.opened",
    triggerRef: String(args.itemNumber),
  });
  if (!run) {
    return {
      ok: false,
      summary: "could not open agent_runs row",
      runId: null,
    };
  }

  let finalSummary = "no AI backend configured; manual triage required";

  await executeAgentRun(run.id, async (ctx) => {
    await ctx.appendLog(
      `[triage] classifying ${args.kind} #${args.itemNumber} "${args.title.slice(0, 120)}"`
    );

    // Skip if we've already commented on this item. The run still succeeds —
    // double-firing is not an error from the caller's perspective.
    if (await alreadyTriaged(args.kind, args.itemId)) {
      await ctx.appendLog("[triage] already triaged; skipping comment");
      finalSummary = "already triaged; skipped";
      return { ok: true, summary: finalSummary };
    }

    const aiAvailable = isAiAvailable();
    let classification: TriageClassification = { ...DEFAULT_CLASSIFICATION };

    if (aiAvailable) {
      const ai = await askClaudeForTriage(args, ctx);
      if (ai) {
        classification = ai.classification;
        const cents = estimateHaikuCents(ai.inputTokens, ai.outputTokens);
        await ctx.recordCost(ai.inputTokens, ai.outputTokens, cents);
      } else {
        await ctx.appendLog(
          "[triage] AI call failed — falling back to deterministic comment"
        );
        classification = {
          ...DEFAULT_CLASSIFICATION,
          reasoning:
            "AI classifier was unreachable. A maintainer should triage this manually.",
        };
      }
    } else {
      await ctx.appendLog("[triage] no ANTHROPIC_API_KEY; deterministic path");
    }

    const commentBody = renderTriageComment(
      args.kind,
      classification,
      aiAvailable
    );
    const authorId = await resolveCommentAuthorId(args);
    if (!authorId) {
      await ctx.appendLog(
        "[triage] no viable author_id for comment; aborting insert"
      );
      finalSummary = "no author_id available; comment not posted";
      return { ok: false, summary: finalSummary };
    }

    try {
      if (args.kind === "issue") {
        await db.insert(issueComments).values({
          issueId: args.itemId,
          authorId,
          body: commentBody,
        });
      } else {
        await db.insert(prComments).values({
          pullRequestId: args.itemId,
          authorId,
          body: commentBody,
          isAiReview: true,
        });
      }
    } catch (err) {
      await ctx.appendLog(
        `[triage] comment insert failed: ${(err as Error).message}`
      );
      finalSummary = `comment insert failed: ${(err as Error).message}`;
      return { ok: false, summary: finalSummary };
    }

    finalSummary = buildRunSummary(classification, aiAvailable);
    await ctx.appendLog(`[triage] posted comment; ${finalSummary}`);
    return { ok: true, summary: finalSummary };
  });

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