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
fix-agent.ts11.4 KB · 387 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
/**
 * Block K5 — Fix Agent.
 *
 * Pairs with Gatetest. When a PR has failing checks (or a human pokes the
 * "try fix" button), the fix agent calls `runAndRepair` on Gatetest, which
 * returns file-level before/after patches. For v1 we DO NOT auto-push the
 * patches — instead we post a structured PR comment listing each repair with
 * its reason. A human (or a follow-up agent) applies. This keeps the blast
 * radius bounded while the platform gets its sea legs.
 *
 * Design rules (mirrors heal-bot.ts):
 *   - Never throws. Every DB / network error returns `{ ok: false, summary }`.
 *   - Runs inside the K1 `executeAgentRun` wrapper so the run row carries
 *     status + log + cost.
 *   - Cost: 3¢ flat (Gatetest compute proxy). No Anthropic round-trip.
 *   - No new tables.
 */

import { eq } from "drizzle-orm";
import { db } from "../../db";
import {
  prComments,
  pullRequests,
  repositories,
  users,
} from "../../db/schema";
import { runAndRepair, type GatetestRepair } from "../gatetest-client";
import {
  executeAgentRun,
  startAgentRun,
  type AgentExecutorContext,
} from "../agent-runtime";

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

export interface RunFixAgentArgs {
  repositoryId: string;
  pullRequestId: string;
  triggerBy?: string | null;
  targetGlob?: string | null;
}

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

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/** Per-run Gatetest compute cost proxy, in cents. */
export const FIX_AGENT_COST_CENTS = 3;

/** Max individual repairs to enumerate in the PR comment body. */
export const FIX_AGENT_MAX_REPAIRS_IN_COMMENT = 20;

/** Bot slug — matches the identity K2 will ensureAgentApp for. */
export const FIX_AGENT_SLUG = "agent-fix";

/** Bot username used in comment bodies so humans know who commented. */
export const FIX_AGENT_BOT_USERNAME = "agent-fix[bot]";

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

/**
 * Render the PR comment body for a successful Gatetest run. Deterministic +
 * no I/O so we can exercise it in isolation.
 */
export function renderFixAgentComment(params: {
  passed: boolean;
  totalTests: number;
  failedBefore: number;
  failedAfter: number;
  repairs: GatetestRepair[];
  unfixable: { file: string; reason: string }[];
}): string {
  const { passed, totalTests, failedBefore, failedAfter, repairs, unfixable } =
    params;
  const lines: string[] = [];
  lines.push(`## Fix Agent`);
  lines.push("");
  if (passed) {
    lines.push(
      `Gatetest ran **${totalTests}** test${totalTests === 1 ? "" : "s"} — all passing after ${repairs.length} repair${repairs.length === 1 ? "" : "s"}.`
    );
  } else {
    lines.push(
      `Gatetest proposed **${repairs.length}** repair${repairs.length === 1 ? "" : "s"} (${failedBefore}${failedAfter} failing).`
    );
  }
  lines.push("");

  if (repairs.length > 0) {
    lines.push(`### Repairs`);
    const cap = Math.min(repairs.length, FIX_AGENT_MAX_REPAIRS_IN_COMMENT);
    for (let i = 0; i < cap; i++) {
      const r = repairs[i]!;
      lines.push(`- \`${r.file}\` — ${r.reason}`);
    }
    if (repairs.length > cap) {
      lines.push(`- _…and ${repairs.length - cap} more._`);
    }
    lines.push("");
  }

  if (unfixable.length > 0) {
    lines.push(`### Unfixable`);
    for (const u of unfixable.slice(0, FIX_AGENT_MAX_REPAIRS_IN_COMMENT)) {
      lines.push(`- \`${u.file}\` — ${u.reason}`);
    }
    lines.push("");
  }

  lines.push(`_Generated by ${FIX_AGENT_BOT_USERNAME}._`);
  return lines.join("\n");
}

/** Short summary stored in agent_runs.summary. */
export function buildFixAgentSummary(params: {
  offline: boolean;
  passed: boolean;
  failedBefore: number;
  failedAfter: number;
  repairs: number;
}): string {
  if (params.offline) return "gatetest offline; skipped";
  if (params.repairs === 0 && params.failedBefore === 0) {
    return "suite healthy; nothing to fix";
  }
  if (params.repairs === 0) {
    return `${params.failedBefore} failing, 0 repairs proposed`;
  }
  if (params.passed) {
    return `repaired ${params.repairs} (${params.failedBefore} → 0)`;
  }
  return `proposed ${params.repairs} repair${params.repairs === 1 ? "" : "s"} (${params.failedBefore}${params.failedAfter})`;
}

// ---------------------------------------------------------------------------
// Internal DB helpers — defensive, never throw.
// ---------------------------------------------------------------------------

interface PrContext {
  prId: string;
  prNumber: number;
  headBranch: string;
  isClosed: boolean;
  isMerged: boolean;
  repoId: string;
  repoName: string;
  ownerUsername: string;
  ownerId: string;
}

async function resolvePrContext(
  pullRequestId: string
): Promise<PrContext | null> {
  try {
    const rows = await db
      .select({
        prId: pullRequests.id,
        prNumber: pullRequests.number,
        headBranch: pullRequests.headBranch,
        state: pullRequests.state,
        mergedAt: pullRequests.mergedAt,
        repoId: repositories.id,
        repoName: repositories.name,
        ownerUsername: users.username,
        ownerId: repositories.ownerId,
      })
      .from(pullRequests)
      .innerJoin(repositories, eq(repositories.id, pullRequests.repositoryId))
      .innerJoin(users, eq(users.id, repositories.ownerId))
      .where(eq(pullRequests.id, pullRequestId))
      .limit(1);
    const row = rows[0];
    if (!row) return null;
    return {
      prId: row.prId,
      prNumber: row.prNumber,
      headBranch: row.headBranch,
      isClosed: row.state !== "open",
      isMerged: row.mergedAt !== null,
      repoId: row.repoId,
      repoName: row.repoName,
      ownerUsername: row.ownerUsername,
      ownerId: row.ownerId,
    };
  } catch (err) {
    console.error("[fix-agent] resolvePrContext:", err);
    return null;
  }
}

/**
 * Pick the author_id for the PR comment. Preference:
 *   1. a "bot" user named FIX_AGENT_BOT_USERNAME,
 *   2. the repo owner.
 */
async function resolveFixAgentAuthorId(
  ownerId: string
): Promise<string | null> {
  try {
    const [bot] = await db
      .select({ id: users.id })
      .from(users)
      .where(eq(users.username, FIX_AGENT_BOT_USERNAME))
      .limit(1);
    if (bot?.id) return bot.id;
  } catch (err) {
    console.error("[fix-agent] bot author lookup:", err);
  }
  return ownerId;
}

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

/**
 * Run the fix agent for a single PR. Never throws.
 *
 * Lifecycle:
 *   1. Open an `agent_runs` row (kind = "fix").
 *   2. Resolve the PR; short-circuit if closed/merged.
 *   3. Call Gatetest `runAndRepair` against the PR head branch.
 *   4. On any result post a PR comment summarising the repairs.
 *   5. Cost: 3¢ flat.
 */
export async function runFixAgent(
  args: RunFixAgentArgs
): Promise<RunFixAgentResult> {
  if (
    !args ||
    typeof args.repositoryId !== "string" ||
    !args.repositoryId ||
    typeof args.pullRequestId !== "string" ||
    !args.pullRequestId
  ) {
    return {
      ok: false,
      summary: "invalid args: missing repositoryId or pullRequestId",
      runId: null,
    };
  }

  const trigger = args.triggerBy ? "manual" : "pr.review_comment";

  const run = await startAgentRun({
    repositoryId: args.repositoryId,
    kind: "fix",
    trigger,
    triggerRef: args.pullRequestId,
  });
  if (!run) {
    return {
      ok: false,
      summary: "could not open agent_runs row",
      runId: null,
    };
  }

  let finalSummary = "not started";

  await executeAgentRun(run.id, async (ctx: AgentExecutorContext) => {
    await ctx.appendLog(
      `[fix-agent] starting run for PR ${args.pullRequestId} (trigger=${trigger})`
    );

    const pr = await resolvePrContext(args.pullRequestId);
    if (!pr) {
      finalSummary = "PR lookup failed";
      await ctx.appendLog("[fix-agent] PR lookup failed; aborting");
      return { ok: false, summary: finalSummary };
    }
    if (pr.repoId !== args.repositoryId) {
      finalSummary = "PR does not belong to repository";
      await ctx.appendLog(
        `[fix-agent] PR ${pr.prId} is in repo ${pr.repoId}, expected ${args.repositoryId}`
      );
      return { ok: false, summary: finalSummary };
    }
    if (pr.isClosed || pr.isMerged) {
      finalSummary = "PR is closed/merged; skipped";
      await ctx.appendLog(`[fix-agent] ${finalSummary}`);
      return { ok: true, summary: finalSummary };
    }

    const repoSlug = `${pr.ownerUsername}/${pr.repoName}`;
    await ctx.appendLog(
      `[fix-agent] calling gatetest.runAndRepair for ${repoSlug}@${pr.headBranch}`
    );

    const result = await runAndRepair({
      repo: repoSlug,
      ref: pr.headBranch,
      targetGlob: args.targetGlob || undefined,
    });
    await ctx.recordCost(0, 0, FIX_AGENT_COST_CENTS);

    if (result.offline) {
      finalSummary = buildFixAgentSummary({
        offline: true,
        passed: false,
        failedBefore: 0,
        failedAfter: 0,
        repairs: 0,
      });
      await ctx.appendLog(`[fix-agent] ${finalSummary}`);
      return { ok: true, summary: finalSummary };
    }

    await ctx.appendLog(
      `[fix-agent] gatetest returned: passed=${result.passed}, failedBefore=${result.failedBefore}, failedAfter=${result.failedAfter}, repairs=${result.repairs.length}`
    );

    // If nothing to say, short-circuit before spamming the PR.
    if (
      result.repairs.length === 0 &&
      result.unfixable.length === 0 &&
      result.failedBefore === 0
    ) {
      finalSummary = buildFixAgentSummary({
        offline: false,
        passed: true,
        failedBefore: 0,
        failedAfter: 0,
        repairs: 0,
      });
      return { ok: true, summary: finalSummary };
    }

    const authorId = await resolveFixAgentAuthorId(pr.ownerId);
    if (!authorId) {
      finalSummary = "no viable author_id for comment";
      await ctx.appendLog(`[fix-agent] ${finalSummary}`);
      return { ok: false, summary: finalSummary };
    }

    const body = renderFixAgentComment({
      passed: result.passed,
      totalTests: result.totalTests,
      failedBefore: result.failedBefore,
      failedAfter: result.failedAfter,
      repairs: result.repairs,
      unfixable: result.unfixable,
    });

    try {
      await db.insert(prComments).values({
        pullRequestId: pr.prId,
        authorId,
        body,
        isAiReview: true,
      });
    } catch (err) {
      finalSummary = `comment insert failed: ${(err as Error).message}`;
      await ctx.appendLog(`[fix-agent] ${finalSummary}`);
      return { ok: false, summary: finalSummary };
    }

    finalSummary = buildFixAgentSummary({
      offline: false,
      passed: result.passed,
      failedBefore: result.failedBefore,
      failedAfter: result.failedAfter,
      repairs: result.repairs.length,
    });
    await ctx.appendLog(`[fix-agent] ${finalSummary}`);
    return { ok: true, summary: finalSummary };
  });

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

export const __internal = {
  FIX_AGENT_COST_CENTS,
  FIX_AGENT_MAX_REPAIRS_IN_COMMENT,
  resolvePrContext,
  resolveFixAgentAuthorId,
};