-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmention.ts
More file actions
1150 lines (1054 loc) · 43.2 KB
/
mention.ts
File metadata and controls
1150 lines (1054 loc) · 43.2 KB
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
IssueCommentCreatedEvent,
PullRequestReviewCommentCreatedEvent,
PullRequestReviewSubmittedEvent,
} from "@octokit/webhooks-types";
import type { Logger } from "pino";
import { $ } from "bun";
import { createHash } from "node:crypto";
import type { EventRouter, WebhookEvent } from "../webhook/types.ts";
import type { JobQueue, WorkspaceManager, Workspace } from "../jobs/types.ts";
import type { GitHubApp } from "../auth/github-app.ts";
import type { createExecutor } from "../execution/executor.ts";
import { loadRepoConfig } from "../execution/config.ts";
import {
fetchAndCheckoutPullRequestHeadRef,
getGitStatusPorcelain,
createBranchCommitAndPush,
commitAndPushToRemoteRef,
pushHeadToRemoteRef,
WritePolicyError,
} from "../jobs/workspace.ts";
import {
type MentionEvent,
normalizeIssueComment,
normalizeReviewComment,
normalizeReviewBody,
containsMention,
stripMention,
} from "./mention-types.ts";
import { buildMentionContext } from "../execution/mention-context.ts";
import { buildMentionPrompt } from "../execution/mention-prompt.ts";
import { classifyError, formatErrorComment, postOrUpdateErrorComment } from "../lib/errors.ts";
import { wrapInDetails } from "../lib/formatting.ts";
import { requestRereviewTeamBestEffort } from "./rereview-team.ts";
/**
* Create the mention handler and register it with the event router.
*
* Handles @kodiai mentions across all four comment surfaces:
* - issue_comment.created (issues and PR general comments)
* - pull_request_review_comment.created (inline diff comments)
* - pull_request_review.submitted (review body)
*/
export function createMentionHandler(deps: {
eventRouter: EventRouter;
jobQueue: JobQueue;
workspaceManager: WorkspaceManager;
githubApp: GitHubApp;
executor: ReturnType<typeof createExecutor>;
logger: Logger;
}): void {
const { eventRouter, jobQueue, workspaceManager, githubApp, executor, logger } = deps;
// Basic in-memory rate limiter for write-mode requests.
// Keyed by installation+repo; resets on process restart.
const lastWriteAt = new Map<string, number>();
const inFlightWriteKeys = new Set<string>();
function buildWriteOutputKey(input: {
installationId: number;
owner: string;
repo: string;
prNumber: number;
commentId: number;
keyword: string;
}): string {
const normalizedOwner = input.owner.trim().toLowerCase();
const normalizedRepo = input.repo.trim().toLowerCase();
const normalizedKeyword = input.keyword.trim().toLowerCase();
return [
"kodiai-write-output",
"v1",
`inst-${input.installationId}`,
`${normalizedOwner}/${normalizedRepo}`,
`pr-${input.prNumber}`,
`comment-${input.commentId}`,
`keyword-${normalizedKeyword}`,
].join(":");
}
function buildWriteBranchName(params: {
prNumber: number;
commentId: number;
writeOutputKey: string;
}): string {
const hash = createHash("sha256").update(params.writeOutputKey).digest("hex").slice(0, 12);
return `kodiai/apply/pr-${params.prNumber}-comment-${params.commentId}-${hash}`;
}
function pruneRateLimiter(now: number): void {
// Defense-in-depth: prevent unbounded growth in long-lived processes.
// Keep recent entries only; this limiter is best-effort and not durable.
const ttlMs = 24 * 60 * 60 * 1000; // 24h
for (const [key, ts] of lastWriteAt.entries()) {
if (now - ts > ttlMs) {
lastWriteAt.delete(key);
}
}
// Hard cap: if still large, drop oldest entries.
const maxEntries = 10_000;
if (lastWriteAt.size <= maxEntries) return;
const entries = [...lastWriteAt.entries()].sort((a, b) => a[1] - b[1]);
const toDelete = entries.length - maxEntries;
for (let i = 0; i < toDelete; i++) {
const k = entries[i]?.[0];
if (k) lastWriteAt.delete(k);
}
}
function parseWriteIntent(userQuestion: string): {
writeIntent: boolean;
keyword: "apply" | "change" | "plan" | undefined;
request: string;
} {
const trimmed = userQuestion.trimStart();
const lower = trimmed.toLowerCase();
for (const keyword of ["apply", "change", "plan"] as const) {
const prefix = `${keyword}:`;
if (lower.startsWith(prefix)) {
return {
writeIntent: true,
keyword,
request: trimmed.slice(prefix.length).trim(),
};
}
}
return { writeIntent: false, keyword: undefined, request: userQuestion.trim() };
}
async function handleMention(event: WebhookEvent): Promise<void> {
const appSlug = githubApp.getAppSlug();
const possibleHandles = [appSlug, "claude"];
const action = (event.payload as Record<string, unknown>).action as string | undefined;
// Normalize payload based on event type
let mention: MentionEvent;
if (event.name === "issue_comment") {
if ((event.payload as Record<string, unknown>).action !== "created") return;
mention = normalizeIssueComment(event.payload as unknown as IssueCommentCreatedEvent);
} else if (event.name === "pull_request_review_comment") {
if ((event.payload as Record<string, unknown>).action !== "created") return;
mention = normalizeReviewComment(
event.payload as unknown as PullRequestReviewCommentCreatedEvent,
);
} else if (event.name === "pull_request_review") {
if ((event.payload as Record<string, unknown>).action !== "submitted") return;
const payload = event.payload as unknown as PullRequestReviewSubmittedEvent;
// Review body can be null (e.g. approval with no comment)
if (!payload.review.body) return;
mention = normalizeReviewBody(payload);
} else {
return;
}
// Fast filter: ignore if neither @appSlug nor @claude appear.
// NOTE: Use a simple substring check here to avoid regex edge cases.
// We still do the authoritative accepted-handles check inside the job after loading config.
const bodyLower = mention.commentBody.toLowerCase();
const appHandle = `@${appSlug.toLowerCase()}`;
if (!bodyLower.includes(appHandle) && !bodyLower.includes("@claude")) return;
// No tracking comment. Tracking is via eyes reaction only.
// The response will be posted as a new comment.
await jobQueue.enqueue(event.installationId, async () => {
let workspace: Workspace | undefined;
let acquiredWriteKey: string | undefined;
try {
const octokit = await githubApp.getInstallationOctokit(event.installationId);
async function postMentionReply(replyBody: string): Promise<void> {
// Prefer replying in-thread for inline review comment mentions.
if (mention.surface === "pr_review_comment" && mention.prNumber !== undefined) {
try {
await octokit.rest.pulls.createReplyForReviewComment({
owner: mention.owner,
repo: mention.repo,
pull_number: mention.prNumber,
comment_id: mention.commentId,
body: replyBody,
});
return;
} catch (err) {
logger.warn(
{ err, prNumber: mention.prNumber, commentId: mention.commentId },
"Failed to post in-thread reply; falling back to top-level comment",
);
}
}
await octokit.rest.issues.createComment({
owner: mention.owner,
repo: mention.repo,
issue_number: mention.issueNumber,
body: replyBody,
});
}
async function postMentionError(errorBody: string): Promise<void> {
// Prefer replying in-thread for inline review comment mentions.
if (mention.surface === "pr_review_comment" && mention.prNumber !== undefined) {
try {
await octokit.rest.pulls.createReplyForReviewComment({
owner: mention.owner,
repo: mention.repo,
pull_number: mention.prNumber,
comment_id: mention.commentId,
body: errorBody,
});
return;
} catch (err) {
logger.warn(
{ err, prNumber: mention.prNumber, commentId: mention.commentId },
"Failed to post in-thread error reply; falling back to top-level error comment",
);
}
}
await postOrUpdateErrorComment(
octokit,
{
owner: mention.owner,
repo: mention.repo,
issueNumber: mention.issueNumber,
},
errorBody,
logger,
);
}
// Determine clone parameters
let cloneOwner = mention.owner;
let cloneRepo = mention.repo;
let cloneRef: string | undefined;
let cloneDepth = 1;
let usesPrRef = false;
if (mention.prNumber !== undefined) {
cloneDepth = 50; // PR mentions need diff context
// Ensure PR details are available (issue_comment on PR requires a pulls.get fetch).
if (!mention.baseRef || !mention.headRef) {
const { data: pr } = await octokit.rest.pulls.get({
owner: mention.owner,
repo: mention.repo,
pull_number: mention.prNumber,
});
mention.headRef = pr.head.ref;
mention.baseRef = pr.base.ref;
mention.headRepoOwner = pr.head.repo?.owner.login;
mention.headRepoName = pr.head.repo?.name;
}
// Fork-safe workspace strategy: clone base repo at base ref, then fetch+checkout
// refs/pull/<n>/head from the base repo.
// This avoids relying on access to contributor forks and mirrors the review handler.
cloneOwner = mention.owner;
cloneRepo = mention.repo;
cloneRef = mention.baseRef;
usesPrRef = true;
} else {
// Pure issue mention -- clone default branch
const repoPayload = event.payload as Record<string, unknown>;
const repository = repoPayload.repository as Record<string, unknown> | undefined;
cloneRef = (repository?.default_branch as string) ?? "main";
}
logger.info(
{
surface: mention.surface,
owner: mention.owner,
repo: mention.repo,
issueNumber: mention.issueNumber,
prNumber: mention.prNumber,
cloneOwner,
cloneRepo,
cloneRef,
cloneDepth,
usesPrRef,
workspaceStrategy: usesPrRef
? "base-clone+pull-ref-fetch"
: "direct-branch-clone",
},
"Creating workspace for mention execution",
);
// Clone workspace
workspace = await workspaceManager.create(event.installationId, {
owner: cloneOwner,
repo: cloneRepo,
ref: cloneRef!,
depth: cloneDepth,
});
// PR mentions: fetch and checkout PR head ref from base repo.
if (usesPrRef && mention.prNumber !== undefined) {
await fetchAndCheckoutPullRequestHeadRef({
dir: workspace.dir,
prNumber: mention.prNumber,
localBranch: "pr-mention",
});
// Ensure base branch exists as a remote-tracking ref so git diff tools can compare
// origin/BASE...HEAD even in --single-branch workspaces.
if (mention.baseRef) {
await $`git -C ${workspace.dir} fetch origin ${mention.baseRef}:refs/remotes/origin/${mention.baseRef} --depth=1`.quiet();
}
}
// Load repo config
const config = await loadRepoConfig(workspace.dir);
// Check mention.enabled
if (!config.mention.enabled) {
logger.info(
{ owner: mention.owner, repo: mention.repo },
"Mentions disabled in config, skipping",
);
return;
}
// Global alias: treat @claude as an always-on alias for mentions.
// (Repo-level opt-out remains possible via mention.acceptClaudeAlias=false,
// but the alias is enabled by default to support immediate cutover.)
const acceptClaudeAlias = config.mention.acceptClaudeAlias !== false;
const acceptedHandles = acceptClaudeAlias ? [appSlug, "claude"] : [appSlug];
// Ensure the mention is actually allowed for this repo (e.g. @claude opt-out).
// Use substring match to align with the fast filter.
const acceptedBodyLower = mention.commentBody.toLowerCase();
const accepted = acceptedHandles
.map((h) => (h.startsWith("@") ? h : `@${h}`))
.map((h) => h.toLowerCase());
if (!accepted.some((h) => acceptedBodyLower.includes(h))) {
logger.info(
{
surface: mention.surface,
owner: mention.owner,
repo: mention.repo,
issueNumber: mention.issueNumber,
prNumber: mention.prNumber,
acceptClaudeAlias,
},
"Mention does not match accepted handles for repo; skipping",
);
return;
}
const userQuestion = stripMention(mention.commentBody, acceptedHandles);
const normalizedQuestion = userQuestion.trim().toLowerCase();
if (userQuestion.trim().length === 0) {
logger.info(
{
surface: mention.surface,
owner: mention.owner,
repo: mention.repo,
issueNumber: mention.issueNumber,
prNumber: mention.prNumber,
acceptClaudeAlias,
},
"Mention contained no question after stripping mention; skipping",
);
return;
}
const writeIntent = parseWriteIntent(userQuestion);
const isWriteRequest = writeIntent.writeIntent;
const isPlanOnly = writeIntent.keyword === "plan";
const writeEnabled = isWriteRequest && !isPlanOnly && config.write.enabled;
const writeKeyword = writeIntent.keyword ?? "apply";
const writeOutputKey =
writeEnabled && mention.prNumber !== undefined
? buildWriteOutputKey({
installationId: event.installationId,
owner: mention.owner,
repo: mention.repo,
prNumber: mention.prNumber,
commentId: mention.commentId,
keyword: writeKeyword,
})
: undefined;
const writeBranchName =
writeOutputKey && mention.prNumber !== undefined
? buildWriteBranchName({
prNumber: mention.prNumber,
commentId: mention.commentId,
writeOutputKey,
})
: undefined;
const triggerCommentUrl =
mention.prNumber !== undefined
? `https://github.com/${mention.owner}/${mention.repo}/pull/${mention.prNumber}#issuecomment-${mention.commentId}`
: `https://github.com/${mention.owner}/${mention.repo}/issues/${mention.issueNumber}#issuecomment-${mention.commentId}`;
if (writeEnabled && writeOutputKey && writeBranchName && mention.prNumber !== undefined) {
// Idempotency: if a PR already exists for this deterministic head branch, reuse it.
try {
const { data: prs } = await octokit.rest.pulls.list({
owner: mention.owner,
repo: mention.repo,
state: "all",
head: `${mention.owner}:${writeBranchName}`,
per_page: 5,
});
const existing = prs[0];
if (existing?.html_url) {
logger.info(
{
evidenceType: "write-mode",
outcome: "reused-pr",
deliveryId: event.id,
installationId: event.installationId,
repo: `${mention.owner}/${mention.repo}`,
sourcePrNumber: mention.prNumber,
triggerCommentId: mention.commentId,
triggerCommentUrl,
writeOutputKey,
branchName: writeBranchName,
prUrl: existing.html_url,
},
"Evidence bundle",
);
const replyBody = wrapInDetails(
[`Existing PR: ${existing.html_url}`].join("\n"),
"kodiai response",
);
await postMentionReply(replyBody);
return;
}
} catch (err) {
logger.warn(
{ err, writeBranchName, writeOutputKey, prNumber: mention.prNumber },
"Failed to look up existing PR for write idempotency; continuing",
);
}
// Best-effort lock: prevent duplicate work for the same trigger.
if (inFlightWriteKeys.has(writeOutputKey)) {
const replyBody = wrapInDetails(
[
"Write request already in progress.",
"",
"If no PR appears shortly, retry the same comment.",
].join("\n"),
"kodiai response",
);
await postMentionReply(replyBody);
return;
}
inFlightWriteKeys.add(writeOutputKey);
acquiredWriteKey = writeOutputKey;
}
if (writeEnabled && config.write.minIntervalSeconds > 0) {
const key = `${event.installationId}:${mention.owner}/${mention.repo}`;
const now = Date.now();
pruneRateLimiter(now);
const last = lastWriteAt.get(key);
const minMs = config.write.minIntervalSeconds * 1000;
if (last !== undefined && now - last < minMs) {
const replyBody = wrapInDetails(
[
"Write request rate-limited.",
"",
`Try again in ${Math.ceil((minMs - (now - last)) / 1000)}s.`,
].join("\n"),
"kodiai response",
);
await postMentionReply(replyBody);
return;
}
}
if (isWriteRequest && mention.prNumber === undefined) {
const replyBody = wrapInDetails(
[
"I can only apply changes in a PR context.",
"",
"Try mentioning me on a pull request (top-level comment or inline diff thread).",
].join("\n"),
"kodiai response",
);
await postMentionReply(replyBody);
return;
}
if (isWriteRequest && !isPlanOnly && !config.write.enabled) {
logger.info(
{
surface: mention.surface,
owner: mention.owner,
repo: mention.repo,
issueNumber: mention.issueNumber,
prNumber: mention.prNumber,
commentAuthor: mention.commentAuthor,
keyword: writeIntent.keyword,
gate: "write-mode",
gateResult: "skipped",
skipReason: "write-disabled",
},
"Write intent detected but write-mode disabled; refusing to apply changes",
);
const replyBody = wrapInDetails(
[
"Write mode is disabled for this repo.",
"",
"To enable:",
"```yml",
"write:",
" enabled: true",
"```",
"",
"Then re-run your request starting with `apply:` or `change:`.",
].join("\n"),
"kodiai response",
);
await postMentionReply(replyBody);
return;
}
logger.info(
{
surface: mention.surface,
owner: mention.owner,
repo: mention.repo,
issueNumber: mention.issueNumber,
prNumber: mention.prNumber,
commentAuthor: mention.commentAuthor,
acceptClaudeAlias,
},
"Processing mention",
);
// Add eyes reaction to trigger comment for immediate visual acknowledgment
try {
if (mention.surface === "pr_review_comment") {
await octokit.rest.reactions.createForPullRequestReviewComment({
owner: mention.owner,
repo: mention.repo,
comment_id: mention.commentId,
content: "eyes",
});
} else if (mention.surface === "pr_review_body") {
// PR review bodies don't support reactions -- skip silently
// (the review ID is not a comment ID, so the reaction endpoints would 404)
} else {
// issue_comment and pr_comment both use the issue comment reaction endpoint
await octokit.rest.reactions.createForIssueComment({
owner: mention.owner,
repo: mention.repo,
comment_id: mention.commentId,
content: "eyes",
});
}
} catch (err) {
// Non-fatal: don't block processing if reaction fails
logger.warn({ err, surface: mention.surface }, "Failed to add eyes reaction");
}
// Minimal rereview trigger: allow @kodiai review / @kodiai recheck.
// Goal: retrigger review without adding any new PR thread comments.
// Signal is via best-effort reviewer request + eyes reaction (above).
if (
mention.prNumber !== undefined &&
(normalizedQuestion === "review" || normalizedQuestion === "recheck")
) {
const configuredTeam = (config.review.uiRereviewTeam ?? "").trim() || "aireview";
await requestRereviewTeamBestEffort({
octokit,
owner: mention.owner,
repo: mention.repo,
prNumber: mention.prNumber,
configuredTeam,
logger,
});
return;
}
// Build mention context (conversation + PR metadata + inline diff context)
// Non-fatal: if context fails to load, still attempt an answer with minimal prompt.
let mentionContext = "";
try {
mentionContext = await buildMentionContext(octokit, mention);
} catch (err) {
logger.warn(
{ err, surface: mention.surface, issueNumber: mention.issueNumber },
"Failed to build mention context; proceeding with empty context",
);
}
const planOnlyInstructions = isPlanOnly
? [
"Plan-only request detected (plan:).",
"In this run:",
"- Do NOT edit files.",
"- Do NOT run git commands.",
"- Do NOT propose opening a PR.",
"Return a concise plan with 3-7 steps and a list of files you would touch.",
"End by asking the user to proceed with `apply:` if they want you to implement it.",
].join("\n")
: undefined;
const writeInstructions = writeEnabled
? [
"Write-intent request detected (apply/change).",
"Write-mode is enabled.",
"",
"In this run:",
"- Make the requested changes by editing files in the workspace.",
"- Do NOT run git commands (no branch/commit/push).",
"- Do NOT publish any GitHub comments/reviews; publish tools are disabled.",
"- Keep changes minimal and focused on the request.",
].join("\n")
: isWriteRequest
? [
"Write-intent request detected (apply/change).",
"In this run: do NOT create branches/commits/PRs and do NOT push changes.",
"Instead, propose a concrete, minimal plan (files + steps) and ask for confirmation.",
"Keep it concise.",
].join("\n")
: undefined;
// Build mention prompt
const mentionPrompt = buildMentionPrompt({
mention,
mentionContext,
userQuestion: writeIntent.request,
customInstructions: [config.mention.prompt, planOnlyInstructions, writeInstructions]
.filter((s) => (s ?? "").trim().length > 0)
.join("\n\n"),
});
// Execute via Claude
const result = await executor.execute({
workspace,
installationId: event.installationId,
owner: mention.owner,
repo: mention.repo,
prNumber: mention.prNumber,
// For inline review comment mentions, provide the triggering review comment id
// so the executor can enable the in-thread reply MCP tool.
commentId: mention.surface === "pr_review_comment" ? mention.commentId : undefined,
deliveryId: event.id,
writeMode: writeEnabled,
eventType: `${event.name}.${action ?? ""}`.replace(/\.$/, ""),
triggerBody: mention.commentBody,
prompt: mentionPrompt,
});
logger.info(
{
surface: mention.surface,
issueNumber: mention.issueNumber,
conclusion: result.conclusion,
published: result.published,
writeEnabled,
costUsd: result.costUsd,
numTurns: result.numTurns,
durationMs: result.durationMs,
sessionId: result.sessionId,
},
"Mention execution completed",
);
// Write-mode: trusted code publishes the branch + PR and replies with a link.
if (writeEnabled && mention.prNumber !== undefined && writeOutputKey && writeBranchName) {
const status = await getGitStatusPorcelain(workspace.dir);
if (status.trim().length === 0) {
const replyBody = wrapInDetails(
[
"I didn't end up making any file changes.",
"",
"If you still want a change, re-run with a more specific request.",
].join("\n"),
"kodiai response",
);
await postMentionReply(replyBody);
return;
}
const sourcePrUrl = `https://github.com/${mention.owner}/${mention.repo}/pull/${mention.prNumber}`;
const normalizeName = (s: string | undefined): string => (s ?? "").trim().toLowerCase();
const sameRepoHead =
normalizeName(mention.headRepoOwner) === normalizeName(mention.owner) &&
normalizeName(mention.headRepoName) === normalizeName(mention.repo) &&
typeof mention.headRef === "string" &&
mention.headRef.length > 0;
// Preferred path: update existing PR branch when possible.
if (sameRepoHead && mention.headRef) {
const headRef = mention.headRef;
const idempotencyMarker = `kodiai-write-output-key: ${writeOutputKey}`;
// NOTE: The in-flight lock is acquired earlier for all write-mode requests.
// It is in-process only; in multi-replica deployments, two replicas can still
// do duplicate work concurrently. This project currently deploys with max-replicas=1.
try {
await $`git -C ${workspace.dir} fetch origin ${headRef}:refs/remotes/origin/${headRef} --depth=50`.quiet();
const recentMessages = (
await $`git -C ${workspace.dir} log -n 50 --pretty=%B refs/remotes/origin/${headRef}`.quiet()
)
.text();
if (recentMessages.includes(idempotencyMarker)) {
logger.info(
{
evidenceType: "write-mode",
outcome: "skipped-idempotent",
deliveryId: event.id,
installationId: event.installationId,
repo: `${mention.owner}/${mention.repo}`,
sourcePrNumber: mention.prNumber,
triggerCommentId: mention.commentId,
triggerCommentUrl,
writeOutputKey,
prUrl: sourcePrUrl,
},
"Evidence bundle",
);
const replyBody = wrapInDetails(
[`Already applied (idempotent): ${sourcePrUrl}`].join("\n"),
"kodiai response",
);
await postMentionReply(replyBody);
return;
}
} catch (err) {
logger.warn(
{ err, prNumber: mention.prNumber, headRef },
"Failed to check idempotency marker on head ref; continuing",
);
}
try {
await $`git -C ${workspace.dir} checkout -B pr-head refs/remotes/origin/${headRef}`.quiet();
const commitMessage = [
`kodiai: apply requested changes (pr #${mention.prNumber})`,
"",
idempotencyMarker,
`deliveryId: ${event.id}`,
].join("\n");
const pushed = await commitAndPushToRemoteRef({
dir: workspace.dir,
remoteRef: headRef,
commitMessage,
policy: {
allowPaths: config.write.allowPaths,
denyPaths: config.write.denyPaths,
secretScanEnabled: config.write.secretScan.enabled,
},
});
logger.info(
{
evidenceType: "write-mode",
outcome: "updated-pr-branch",
deliveryId: event.id,
installationId: event.installationId,
repo: `${mention.owner}/${mention.repo}`,
sourcePrNumber: mention.prNumber,
triggerCommentId: mention.commentId,
triggerCommentUrl,
writeOutputKey,
headRef,
commitSha: pushed.headSha,
prUrl: sourcePrUrl,
},
"Evidence bundle",
);
const replyBody = wrapInDetails(
[`Updated PR: ${sourcePrUrl}`].join("\n"),
"kodiai response",
);
try {
await postMentionReply(replyBody);
} catch (replyErr) {
logger.warn(
{ err: replyErr, prNumber: mention.prNumber, headRef },
"Applied changes but failed to post confirmation reply",
);
}
return;
} catch (err) {
if (err instanceof WritePolicyError) {
const refusal = buildWritePolicyRefusalMessage(err, config.write.allowPaths);
const replyBody = wrapInDetails(refusal, "kodiai response");
await postMentionReply(replyBody);
return;
}
// If another concurrent run already pushed an idempotent commit, treat this as a no-op.
try {
await $`git -C ${workspace.dir} fetch origin ${headRef}:refs/remotes/origin/${headRef} --depth=50`.quiet();
const recentMessages = (
await $`git -C ${workspace.dir} log -n 50 --pretty=%B refs/remotes/origin/${headRef}`.quiet()
)
.text();
if (recentMessages.includes(idempotencyMarker)) {
logger.info(
{
evidenceType: "write-mode",
outcome: "skipped-idempotent",
deliveryId: event.id,
installationId: event.installationId,
repo: `${mention.owner}/${mention.repo}`,
sourcePrNumber: mention.prNumber,
triggerCommentId: mention.commentId,
triggerCommentUrl,
writeOutputKey,
prUrl: sourcePrUrl,
},
"Evidence bundle",
);
const replyBody = wrapInDetails(
[`Already applied (idempotent): ${sourcePrUrl}`].join("\n"),
"kodiai response",
);
await postMentionReply(replyBody);
return;
}
} catch (lookupErr) {
logger.warn(
{ err: lookupErr, prNumber: mention.prNumber, headRef },
"Failed to re-check idempotency marker after push failure",
);
}
logger.warn(
{ err, prNumber: mention.prNumber, headRef },
"Failed to push to PR head branch; falling back to bot PR",
);
// Fallback: push current HEAD to deterministic bot branch and open bot PR.
try {
await pushHeadToRemoteRef({
dir: workspace.dir,
remoteRef: writeBranchName,
});
} catch (pushErr) {
logger.error(
{ err: pushErr, prNumber: mention.prNumber, branchName: writeBranchName },
"Fallback push to bot branch failed",
);
throw err;
}
// Continue into bot PR creation below.
}
}
const branchName = writeBranchName;
const commitMessage = [
`kodiai: apply requested changes (pr #${mention.prNumber})`,
"",
`kodiai-write-output-key: ${writeOutputKey}`,
`deliveryId: ${event.id}`,
].join("\n");
let pushed: { branchName: string; headSha: string };
try {
pushed = await createBranchCommitAndPush({
dir: workspace.dir,
branchName,
commitMessage,
policy: {
allowPaths: config.write.allowPaths,
denyPaths: config.write.denyPaths,
secretScanEnabled: config.write.secretScan.enabled,
},
});
} catch (err) {
if (err instanceof WritePolicyError) {
const refusal = buildWritePolicyRefusalMessage(err, config.write.allowPaths);
const replyBody = wrapInDetails(refusal, "kodiai response");
await postMentionReply(replyBody);
return;
}
// If the branch already exists (e.g. replay), try to find the existing PR.
if (err instanceof Error) {
const msg = err.message.toLowerCase();
const looksLikeBranchExists =
msg.includes("non-fast-forward") ||
msg.includes("fetch first") ||
msg.includes("rejected") ||
msg.includes("already exists");
if (looksLikeBranchExists) {
try {
const { data: prs } = await octokit.rest.pulls.list({
owner: mention.owner,
repo: mention.repo,
state: "all",
head: `${mention.owner}:${branchName}`,
per_page: 5,
});
const existing = prs[0];
if (existing?.html_url) {
const replyBody = wrapInDetails(
[`Existing PR: ${existing.html_url}`].join("\n"),
"kodiai response",
);
await postMentionReply(replyBody);
return;
}
} catch (lookupErr) {
logger.warn(
{ err: lookupErr, prNumber: mention.prNumber, branchName },
"Failed to look up existing PR after push failure",
);
}
}
}
throw err;
}
const prTitle = `kodiai: apply changes for PR #${mention.prNumber}`;
const prBody = [
"Requested via mention write intent.",
"",
`Keyword: ${writeIntent.keyword ?? "apply/change"}`,
"",
`Request: ${writeIntent.request}`,
"",
`Source PR: #${mention.prNumber}`,
`Delivery: ${event.id}`,
`Commit: ${pushed.headSha}`,
].join("\n");
const { data: createdPr } = await octokit.rest.pulls.create({
owner: mention.owner,
repo: mention.repo,
title: prTitle,
head: pushed.branchName,
base: mention.baseRef ?? "main",
body: prBody,
});
const replyBody = wrapInDetails(
[`Opened PR: ${createdPr.html_url}`].join("\n"),
"kodiai response",
);
await postMentionReply(replyBody);
logger.info(
{
evidenceType: "write-mode",
outcome: "created-pr",
deliveryId: event.id,
installationId: event.installationId,
repo: `${mention.owner}/${mention.repo}`,
sourcePrNumber: mention.prNumber,
triggerCommentId: mention.commentId,
triggerCommentUrl,
writeOutputKey,
branchName,
prUrl: createdPr.html_url,
commitSha: pushed.headSha,
},
"Evidence bundle",
);
// Record successful publish time for rate limiting.
if (config.write.minIntervalSeconds > 0) {
const key = `${event.installationId}:${mention.owner}/${mention.repo}`;
lastWriteAt.set(key, Date.now());
}
return;
}
// If Claude finished successfully but did not publish any output, post a fallback reply.
// This prevents "silent success" where the model chose not to call any comment tools.
if (!writeEnabled && result.conclusion === "success" && !result.published) {
const fallbackBody = wrapInDetails(
[
"I saw your mention, but I didn't publish a reply automatically.",
"",