opencode-magi 0.0.0-dev-20260520045400 → 0.0.0-dev-20260520064744

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,9 +2,9 @@ import { mkdir, writeFile } from "node:fs/promises";
2
2
  import { dirname, join } from "node:path";
3
3
  import { issueRunOutputDir } from "../config/output";
4
4
  import { worktreeBaseDir } from "../config/worktree";
5
- import { closeIssue, closePullRequest, configureGitIdentity, createPullRequest, fetchIssue, fetchIssueComments, fetchRelatedPullRequests, postIssueComment, pushHead, removeIssueLabels, removeWorktree, searchDuplicateIssues, shellQuote, } from "../github/commands";
6
- import { composeTriageBugPrompt, composeTriageCommentPrompt, composeTriageDuplicatePrompt, composeTriageExistingPrPrompt, composeTriageFeaturePrompt, composeTriageKindPrompt, } from "../prompts/compose";
7
- import { parseEditOutput, parseTriageBinaryOutput, parseTriageDuplicateOutput, parseTriageExistingPrOutput, parseTriageKindOutput, } from "../prompts/output";
5
+ import { closeIssue, closePullRequest, configureGitIdentity, createPullRequest, fetchIssue, fetchIssueComments, fetchRelatedPullRequests, postIssueComment, pushHead, removeIssueLabels, removeWorktree, searchDuplicateIssues, shellQuote, updateIssueComment, } from "../github/commands";
6
+ import { composeTriageBugPrompt, composeTriageActionPrompt, composeTriageCommentClassificationPrompt, composeTriageCommentPrompt, composeTriageCreatePrPrompt, composeTriageDuplicatePrompt, composeTriageExistingPrPrompt, composeTriageFeaturePrompt, composeTriageKindPrompt, composeTriageQuestionPrompt, composeTriageReconsiderPrompt, } from "../prompts/compose";
7
+ import { parseEditOutput, parseTriageActionOutput, parseTriageBinaryOutput, parseTriageCommentClassificationOutput, parseTriageDuplicateOutput, parseTriageExistingPrOutput, parseTriageFinalOutput, parseTriageKindOutput, } from "../prompts/output";
8
8
  import { aggregateStringMajority, majorityThreshold } from "./majority";
9
9
  import { runModelText, runModelWithRepair } from "./model";
10
10
  const MARKER_PREFIX = "opencode-magi:triage";
@@ -15,8 +15,21 @@ const EXISTING_PR_VOTES = [
15
15
  "RELATED_PR_DOES_NOT_HANDLE_ISSUE",
16
16
  "RELATED_PR_HANDLES_ISSUE",
17
17
  ];
18
+ const FINAL_VOTES = [
19
+ "ASK",
20
+ "BUG_ACCEPTED",
21
+ "BUG_REJECTED",
22
+ "DUPLICATE",
23
+ "FEATURE_ACCEPTED",
24
+ "FEATURE_REJECTED",
25
+ ];
26
+ const RECONSIDERATION_CLASSES = new Set([
27
+ "CLARIFICATION",
28
+ "NEW_EVIDENCE",
29
+ "OBJECTION",
30
+ ]);
18
31
  function marker(input) {
19
- return `<!-- ${MARKER_PREFIX} v=1 issue=${input.issue} result=${input.result} action=${input.action} checkpoint=pending pr=${input.pr ?? "none"} processed=${(input.processed ?? []).join(",")} -->`;
32
+ return `<!-- ${MARKER_PREFIX} v=1 issue=${input.issue} result=${input.result} action=${input.action} checkpoint=${input.checkpoint ?? "pending"} pr=${input.pr ?? "none"} processed=${(input.processed ?? []).join(",")} -->`;
20
33
  }
21
34
  export function parseTriageMarker(body) {
22
35
  const match = body.match(/<!--\s*opencode-magi:triage\s+([^>]+?)\s*-->/);
@@ -36,7 +49,9 @@ export function parseTriageMarker(body) {
36
49
  return undefined;
37
50
  return {
38
51
  action: entries.action,
39
- checkpoint: entries.checkpoint ? Number(entries.checkpoint) : undefined,
52
+ checkpoint: entries.checkpoint && Number.isFinite(Number(entries.checkpoint))
53
+ ? Number(entries.checkpoint)
54
+ : undefined,
40
55
  issue: entries.issue ? Number(entries.issue) : undefined,
41
56
  pr: entries.pr,
42
57
  processed: entries.processed
@@ -67,6 +82,7 @@ function issueContext(input) {
67
82
  duplicateCandidates: input.relationship.duplicateCandidates,
68
83
  issue: input.issue,
69
84
  recentComments: input.relationship.comments.slice(-20),
85
+ reconsideration: input.reconsideration,
70
86
  relatedPullRequests: input.relationship.relatedPullRequests,
71
87
  }, null, 2);
72
88
  }
@@ -93,7 +109,21 @@ async function runVote(input) {
93
109
  signal: input.signal,
94
110
  title: `Magi triage ${input.schemaName} #${input.issue} (${input.agent.key})`,
95
111
  });
96
- return { ...result.value, raw: result.raw, sessionId: result.sessionId };
112
+ return {
113
+ ...result.value,
114
+ promptText: prompt,
115
+ raw: result.raw,
116
+ sessionId: result.sessionId,
117
+ };
118
+ }
119
+ async function writeVoteArtifacts(input) {
120
+ const base = join(input.outputDir, `${input.reviewer}.${input.phase}`);
121
+ await writeFile(`${base}.prompt.txt`, `${input.output.promptText}\n`);
122
+ await writeFile(`${base}.raw.txt`, `${input.output.raw}\n`);
123
+ await writeJson(`${base}.json`, {
124
+ reason: input.output.reason,
125
+ vote: input.output.vote,
126
+ });
97
127
  }
98
128
  export function chooseDuplicateOutput(input) {
99
129
  const candidates = new Set(input.candidateNumbers);
@@ -132,6 +162,17 @@ async function runDuplicateVote(input) {
132
162
  reviewer: agents[index].key,
133
163
  vote: output.vote,
134
164
  })), DUPLICATE_VOTES);
165
+ await Promise.all(outputs.map((output, index) => writeVoteArtifacts({
166
+ output,
167
+ outputDir: input.outputDir,
168
+ phase: "duplicate",
169
+ reviewer: agents[index].key,
170
+ })));
171
+ await Promise.all(outputs.map((output, index) => writeJson(join(input.outputDir, `${agents[index].key}.duplicate.json`), {
172
+ duplicateOf: output.duplicateOf,
173
+ reason: output.reason,
174
+ vote: output.vote,
175
+ })));
135
176
  await writeJson(join(input.outputDir, "duplicate-majority.json"), majority);
136
177
  if (majority.vote !== "DUPLICATE")
137
178
  return undefined;
@@ -160,6 +201,12 @@ async function runPhaseVote(input) {
160
201
  reviewer: agents[index].key,
161
202
  vote: output.vote,
162
203
  })), input.votes);
204
+ await Promise.all(outputs.map((output, index) => writeVoteArtifacts({
205
+ output,
206
+ outputDir: input.outputDir,
207
+ phase: input.phase,
208
+ reviewer: agents[index].key,
209
+ })));
163
210
  await writeJson(join(input.outputDir, `${input.phase}-majority.json`), majority);
164
211
  return majority.vote;
165
212
  }
@@ -169,11 +216,332 @@ async function relationshipScan(input, issue) {
169
216
  fetchRelatedPullRequests(input.exec, input.repository, input.issue),
170
217
  searchDuplicateIssues(input.exec, input.repository, issue),
171
218
  ]);
172
- const previousMarker = comments
173
- .map((comment) => parseTriageMarker(comment.body))
174
- .filter((item) => Boolean(item))
175
- .at(-1);
176
- return { comments, duplicateCandidates, previousMarker, relatedPullRequests };
219
+ const markers = comments
220
+ .filter((comment) => comment.author === input.repository.triage?.account)
221
+ .map((comment) => {
222
+ const parsed = parseTriageMarker(comment.body);
223
+ return parsed ? { ...parsed, commentId: comment.id } : undefined;
224
+ })
225
+ .filter(Boolean);
226
+ const previousMarker = markers.at(-1);
227
+ const mentionReplies = previousMarker
228
+ ? eligibleMentionReplies({
229
+ account: input.repository.triage?.account ?? "",
230
+ comments,
231
+ marker: previousMarker,
232
+ processed: previousMarker.processed,
233
+ repository: input.repository,
234
+ })
235
+ : [];
236
+ return {
237
+ comments,
238
+ duplicateCandidates,
239
+ mentionReplies,
240
+ previousMarker,
241
+ relatedPullRequests,
242
+ };
243
+ }
244
+ function mentionsAccount(body, account) {
245
+ return new RegExp(`@${account.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "i").test(body);
246
+ }
247
+ function markerCheckpoint(marker) {
248
+ return marker.checkpoint ?? marker.commentId;
249
+ }
250
+ function markerPr(marker) {
251
+ const pr = Number(marker.pr);
252
+ return Number.isInteger(pr) && pr > 0 ? pr : undefined;
253
+ }
254
+ export function mentionAllowed(comment, repository) {
255
+ const safety = repository.triage?.safety;
256
+ if (!safety)
257
+ return false;
258
+ const actorAllowed = safety.allowMentionActors.length
259
+ ? safety.allowMentionActors.includes(comment.author)
260
+ : false;
261
+ const roleAllowed = safety.allowMentionRoles.length
262
+ ? safety.allowMentionRoles.includes(comment.authorAssociation ?? "")
263
+ : false;
264
+ return safety.allowMentionActors.length || safety.allowMentionRoles.length
265
+ ? actorAllowed || roleAllowed
266
+ : true;
267
+ }
268
+ export function eligibleMentionReplies(input) {
269
+ const checkpoint = markerCheckpoint(input.marker);
270
+ const processed = new Set(input.processed);
271
+ return input.comments.filter((comment) => {
272
+ if (checkpoint != null && comment.id <= checkpoint)
273
+ return false;
274
+ if (processed.has(comment.id))
275
+ return false;
276
+ if (!mentionsAccount(comment.body, input.account))
277
+ return false;
278
+ return mentionAllowed(comment, input.repository);
279
+ });
280
+ }
281
+ function finalResultFromMarker(marker) {
282
+ if (marker.result === "RESOLVED_BY_MERGED_PR")
283
+ return "BUG_ACCEPTED";
284
+ return isFinalResult(marker.result) ? marker.result : "FAILED";
285
+ }
286
+ function isFinalResult(value) {
287
+ return (value === "ASK" ||
288
+ value === "BUG_ACCEPTED" ||
289
+ value === "BUG_REJECTED" ||
290
+ value === "CLEAR_ONLY" ||
291
+ value === "DUPLICATE" ||
292
+ value === "FEATURE_ACCEPTED" ||
293
+ value === "FEATURE_REJECTED" ||
294
+ value === "FAILED");
295
+ }
296
+ function actionPlan(input) {
297
+ if (input.result === "CLEAR_ONLY") {
298
+ return {
299
+ action: "CLEAR_ONLY",
300
+ allowedActions: ["CLEAR_ONLY"],
301
+ clearLabels: true,
302
+ closeIssue: false,
303
+ createPr: false,
304
+ postComment: false,
305
+ };
306
+ }
307
+ if (input.result === "ASK") {
308
+ return {
309
+ action: "ASK",
310
+ allowedActions: ["ASK"],
311
+ clearLabels: false,
312
+ closeIssue: false,
313
+ createPr: false,
314
+ postComment: true,
315
+ };
316
+ }
317
+ const closeIssue = input.triage.automation.close &&
318
+ (input.result === "BUG_REJECTED" ||
319
+ input.result === "DUPLICATE" ||
320
+ input.result === "FEATURE_REJECTED");
321
+ const createPr = input.triage.automation.pr &&
322
+ (input.result === "BUG_ACCEPTED" || input.result === "FEATURE_ACCEPTED");
323
+ return {
324
+ action: closeIssue ? "CLOSE" : createPr ? "PR" : "COMMENT",
325
+ allowedActions: [closeIssue ? "CLOSE" : createPr ? "PR" : "COMMENT"],
326
+ clearLabels: true,
327
+ closeIssue,
328
+ createPr,
329
+ postComment: true,
330
+ };
331
+ }
332
+ async function runActionPrompt(input) {
333
+ const agent = input.input.repository.agents.triage?.[0];
334
+ if (!agent)
335
+ throw new Error("triage.agents is required");
336
+ const context = JSON.stringify({
337
+ allowedActions: input.plan.allowedActions,
338
+ deterministicPlan: input.plan,
339
+ result: input.result,
340
+ triageContext: input.context,
341
+ }, null, 2);
342
+ const prompt = await composeTriageActionPrompt({
343
+ context,
344
+ directory: input.input.directory,
345
+ issue: input.input.issue,
346
+ repository: input.input.repository,
347
+ reviewer: agent,
348
+ });
349
+ const result = await runModelWithRepair({
350
+ client: input.input.client,
351
+ model: agent.model,
352
+ options: agent.options,
353
+ parse: parseTriageActionOutput,
354
+ permission: agent.permission,
355
+ prompt,
356
+ repairAttempts: 3,
357
+ schemaName: "triage action",
358
+ signal: input.input.signal,
359
+ title: `Magi triage action #${input.input.issue}`,
360
+ });
361
+ await writeJson(join(input.outputDir, "action.json"), {
362
+ model: result.value,
363
+ plan: input.plan,
364
+ });
365
+ return result.value;
366
+ }
367
+ async function classifyMentionReplies(input) {
368
+ const agent = input.input.repository.agents.triage?.[0];
369
+ if (!agent)
370
+ throw new Error("triage.agents is required");
371
+ const prompt = await composeTriageCommentClassificationPrompt({
372
+ context: JSON.stringify({ context: input.context, mentionReplies: input.replies }, null, 2),
373
+ directory: input.input.directory,
374
+ issue: input.input.issue,
375
+ repository: input.input.repository,
376
+ reviewer: agent,
377
+ });
378
+ const result = await runModelWithRepair({
379
+ client: input.input.client,
380
+ model: agent.model,
381
+ options: agent.options,
382
+ parse: parseTriageCommentClassificationOutput,
383
+ permission: agent.permission,
384
+ prompt,
385
+ repairAttempts: 3,
386
+ schemaName: "triage comment classification",
387
+ signal: input.input.signal,
388
+ title: `Magi triage comment classification #${input.input.issue}`,
389
+ });
390
+ await writeJson(join(input.outputDir, "comment-classification.json"), result.value);
391
+ return result.value;
392
+ }
393
+ async function runReconsiderationVote(input) {
394
+ return runPhaseVote({
395
+ context: input.context,
396
+ input: input.input,
397
+ outputDir: input.outputDir,
398
+ parse: parseTriageFinalOutput,
399
+ phase: "reconsider",
400
+ prompt: composeTriageReconsiderPrompt,
401
+ schemaName: "triage reconsider",
402
+ votes: FINAL_VOTES,
403
+ });
404
+ }
405
+ async function composeResultComment(input) {
406
+ const agents = input.input.repository.agents.triage;
407
+ if (!agents?.length)
408
+ throw new Error("triage.agents is required");
409
+ const prompt = await (input.result === "ASK"
410
+ ? composeTriageQuestionPrompt
411
+ : composeTriageCommentPrompt)({
412
+ author: input.issue.author,
413
+ context: input.context,
414
+ directory: input.input.directory,
415
+ issue: input.issue.number,
416
+ repository: input.input.repository,
417
+ });
418
+ const comment = (await runModelText({
419
+ allowEmpty: false,
420
+ client: input.input.client,
421
+ model: agents[0].model,
422
+ options: agents[0].options,
423
+ permission: agents[0].permission,
424
+ prompt,
425
+ signal: input.input.signal,
426
+ title: `Magi triage comment #${input.issue.number}`,
427
+ })).raw +
428
+ `\n\n${marker({
429
+ action: input.action,
430
+ checkpoint: "pending",
431
+ issue: input.issue.number,
432
+ processed: input.processed,
433
+ result: input.result,
434
+ })}`;
435
+ await writeFile(join(input.outputDir, "comment.md"), `${comment}\n`);
436
+ return comment;
437
+ }
438
+ async function postMarkedIssueComment(input) {
439
+ const posted = await postIssueComment(input.exec, input.repository, input.issue, input.account, input.body);
440
+ const body = input.body.replace("checkpoint=pending", `checkpoint=${posted.id}`);
441
+ const updated = body === input.body
442
+ ? posted
443
+ : await updateIssueComment(input.exec, input.repository, posted.id, input.account, body);
444
+ await writeJson(join(input.outputDir, "posted.json"), updated);
445
+ return updated;
446
+ }
447
+ async function persistProcessedMarker(input) {
448
+ if (!input.marker.commentId)
449
+ return;
450
+ const previousComment = input.comments.find((comment) => comment.id === input.marker.commentId);
451
+ if (!previousComment)
452
+ return;
453
+ const updatedMarker = marker({
454
+ action: input.marker.action ?? input.marker.result ?? "ASK",
455
+ checkpoint: markerCheckpoint(input.marker),
456
+ issue: input.issue.number,
457
+ pr: markerPr(input.marker),
458
+ processed: input.processed,
459
+ result: input.marker.result ?? "ASK",
460
+ });
461
+ const body = previousComment.body.replace(/<!--\s*opencode-magi:triage\s+[^>]+?\s*-->/, updatedMarker);
462
+ if (body === previousComment.body)
463
+ return;
464
+ const updated = await updateIssueComment(input.exec, input.repository, input.marker.commentId, input.account, body);
465
+ await writeJson(join(input.outputDir, "processed.json"), {
466
+ processed: input.processed,
467
+ updated,
468
+ });
469
+ }
470
+ async function finishWithResult(input) {
471
+ const triage = input.input.repository.triage;
472
+ if (!triage)
473
+ throw new Error("triage configuration is required");
474
+ const plan = actionPlan({ result: input.result, triage });
475
+ await runActionPrompt({
476
+ context: input.context,
477
+ input: input.input,
478
+ outputDir: input.outputDir,
479
+ plan,
480
+ result: input.result,
481
+ });
482
+ let prUrl;
483
+ const comment = plan.postComment
484
+ ? await composeResultComment({
485
+ action: plan.action,
486
+ context: `Result: ${input.result}\nAction: ${plan.action}\n\n${input.context}`,
487
+ input: input.input,
488
+ issue: input.issue,
489
+ outputDir: input.outputDir,
490
+ processed: input.processed,
491
+ result: input.result,
492
+ })
493
+ : undefined;
494
+ if (!input.input.dryRun) {
495
+ if (comment) {
496
+ await postMarkedIssueComment({
497
+ account: triage.account ?? "",
498
+ body: comment,
499
+ exec: input.input.exec,
500
+ issue: input.issue.number,
501
+ outputDir: input.outputDir,
502
+ repository: input.input.repository,
503
+ });
504
+ }
505
+ if (plan.closeIssue) {
506
+ const closedPrs = [];
507
+ for (const pr of input.relationship.relatedPullRequests.filter((pr) => pr.state === "OPEN")) {
508
+ await closePullRequest(input.input.exec, input.input.repository, pr.number, triage.account ?? "");
509
+ closedPrs.push(pr.number);
510
+ }
511
+ if (closedPrs.length)
512
+ await writeJson(join(input.outputDir, "closed-prs.json"), closedPrs);
513
+ await closeIssue(input.input.exec, input.input.repository, input.issue.number, triage.account ?? "");
514
+ }
515
+ if (plan.createPr) {
516
+ prUrl = await createImplementationPr({
517
+ context: input.context,
518
+ input: input.input,
519
+ issue: input.issue,
520
+ outputDir: input.outputDir,
521
+ });
522
+ if (prUrl)
523
+ await writeJson(join(input.outputDir, "pr.json"), { url: prUrl });
524
+ }
525
+ if (plan.clearLabels) {
526
+ await removeIssueLabels(input.input.exec, input.input.repository, input.issue.number, triage.automation.clear, triage.account ?? "");
527
+ }
528
+ }
529
+ const report = [
530
+ `Magi triage result for #${input.issue.number}: ${input.result}`,
531
+ prUrl ? `Created PR: ${prUrl}` : undefined,
532
+ input.input.dryRun
533
+ ? "Dry run: no GitHub mutations were performed."
534
+ : undefined,
535
+ ]
536
+ .filter(Boolean)
537
+ .join("\n");
538
+ await writeFile(join(input.outputDir, "report.md"), `${report}\n`);
539
+ return {
540
+ issue: input.issue.number,
541
+ outputDir: input.outputDir,
542
+ report,
543
+ result: input.result,
544
+ };
177
545
  }
178
546
  function safetyBlocked(input, issue, hasMarker) {
179
547
  const triage = input.repository.triage;
@@ -206,7 +574,13 @@ async function createImplementationPr(input) {
206
574
  await input.input.exec(`git worktree add -b ${shellQuote(branch)} ${shellQuote(worktreePath)}`);
207
575
  try {
208
576
  await configureGitIdentity(input.input.exec, worktreePath, creator.author);
209
- const prompt = `Implement issue #${input.issue.number}.\n\n${input.context}\n\nReturn the edit output contract.`;
577
+ const prompt = await composeTriageCreatePrPrompt({
578
+ context: input.context,
579
+ directory: input.input.directory,
580
+ issue: input.issue.number,
581
+ repository: input.input.repository,
582
+ worktreePath,
583
+ });
210
584
  const result = await runModelWithRepair({
211
585
  client: input.input.client,
212
586
  model: creator.model,
@@ -256,14 +630,72 @@ export async function runTriage(input) {
256
630
  const relationship = await relationshipScan(input, issue);
257
631
  const block = safetyBlocked(input, issue, Boolean(relationship.previousMarker));
258
632
  await writeJson(join(outputDir, "issue.json"), issue);
633
+ await writeJson(join(outputDir, "comments.json"), relationship.comments);
259
634
  await writeJson(join(outputDir, "relationship-summary.json"), relationship);
635
+ if (relationship.previousMarker)
636
+ await writeJson(join(outputDir, "previous-triage.json"), relationship.previousMarker);
260
637
  if (block) {
261
638
  const report = `Magi triage blocked for #${input.issue}: ${block}`;
262
639
  await writeFile(join(outputDir, "report.md"), `${report}\n`);
263
640
  return { issue: input.issue, outputDir, report, result: "FAILED" };
264
641
  }
265
- const context = issueContext({ issue, relationship });
266
- if (relationship.relatedPullRequests.length) {
642
+ let context = issueContext({ issue, relationship });
643
+ await writeFile(join(outputDir, "context.md"), `${context}\n`);
644
+ let processed = relationship.previousMarker?.processed ?? [];
645
+ let result;
646
+ if (relationship.previousMarker) {
647
+ if (!relationship.mentionReplies.length) {
648
+ const result = finalResultFromMarker(relationship.previousMarker);
649
+ const report = `Magi triage skipped #${issue.number} because no eligible mention replies were found for reconsideration.`;
650
+ await writeFile(join(outputDir, "report.md"), `${report}\n`);
651
+ return { issue: issue.number, outputDir, report, result };
652
+ }
653
+ const classifications = await classifyMentionReplies({
654
+ context,
655
+ input,
656
+ outputDir,
657
+ replies: relationship.mentionReplies,
658
+ });
659
+ const triggeringComments = relationship.mentionReplies.filter((comment) => classifications.comments.some((item) => item.commentId === comment.id &&
660
+ RECONSIDERATION_CLASSES.has(item.classification)));
661
+ processed = [
662
+ ...new Set([
663
+ ...processed,
664
+ ...classifications.comments.map((comment) => comment.commentId),
665
+ ]),
666
+ ];
667
+ if (!triggeringComments.length) {
668
+ if (!input.dryRun) {
669
+ await persistProcessedMarker({
670
+ account: triage.account,
671
+ comments: relationship.comments,
672
+ exec: input.exec,
673
+ issue,
674
+ marker: relationship.previousMarker,
675
+ outputDir,
676
+ processed,
677
+ repository: input.repository,
678
+ });
679
+ }
680
+ const result = finalResultFromMarker(relationship.previousMarker);
681
+ const report = `Magi triage skipped #${issue.number} because allowed mention replies did not request reconsideration.`;
682
+ await writeFile(join(outputDir, "report.md"), `${report}\n`);
683
+ return { issue: issue.number, outputDir, report, result };
684
+ }
685
+ context = issueContext({
686
+ issue,
687
+ relationship,
688
+ reconsideration: {
689
+ classifications,
690
+ previousMarker: relationship.previousMarker,
691
+ triggeringComments,
692
+ },
693
+ });
694
+ await writeFile(join(outputDir, "context.md"), `${context}\n`);
695
+ result =
696
+ (await runReconsiderationVote({ context, input, outputDir })) ?? "ASK";
697
+ }
698
+ if (!result && relationship.relatedPullRequests.length) {
267
699
  const vote = await runPhaseVote({
268
700
  context,
269
701
  input,
@@ -277,9 +709,46 @@ export async function runTriage(input) {
277
709
  if (vote === "RELATED_PR_HANDLES_ISSUE") {
278
710
  const merged = relationship.relatedPullRequests.some((pr) => pr.state === "MERGED");
279
711
  if (merged && triage.automation.close) {
280
- const body = `@${issue.author} Magi found a related merged pull request that appears to resolve this issue.\n\n${marker({ action: "CLOSE", issue: issue.number, result: "RESOLVED_BY_MERGED_PR" })}`;
712
+ const plan = {
713
+ action: "CLOSE",
714
+ allowedActions: ["CLOSE"],
715
+ clearLabels: true,
716
+ closeIssue: true,
717
+ createPr: false,
718
+ postComment: true,
719
+ };
720
+ await runActionPrompt({
721
+ context,
722
+ input,
723
+ outputDir,
724
+ plan,
725
+ result: "BUG_ACCEPTED",
726
+ });
727
+ const body = await composeResultComment({
728
+ action: "CLOSE",
729
+ context: `Result: BUG_ACCEPTED\nAction: CLOSE\n\n${context}`,
730
+ input,
731
+ issue,
732
+ outputDir,
733
+ processed,
734
+ result: "BUG_ACCEPTED",
735
+ });
281
736
  if (!input.dryRun) {
282
- await postIssueComment(input.exec, input.repository, issue.number, triage.account, body);
737
+ await postMarkedIssueComment({
738
+ account: triage.account,
739
+ body,
740
+ exec: input.exec,
741
+ issue: issue.number,
742
+ outputDir,
743
+ repository: input.repository,
744
+ });
745
+ const closedPrs = [];
746
+ for (const pr of relationship.relatedPullRequests.filter((pr) => pr.state === "OPEN")) {
747
+ await closePullRequest(input.exec, input.repository, pr.number, triage.account);
748
+ closedPrs.push(pr.number);
749
+ }
750
+ if (closedPrs.length)
751
+ await writeJson(join(outputDir, "closed-prs.json"), closedPrs);
283
752
  await closeIssue(input.exec, input.repository, issue.number, triage.account);
284
753
  await removeIssueLabels(input.exec, input.repository, issue.number, triage.automation.clear, triage.account);
285
754
  }
@@ -292,15 +761,18 @@ export async function runTriage(input) {
292
761
  result: "BUG_ACCEPTED",
293
762
  };
294
763
  }
295
- if (!input.dryRun) {
296
- await removeIssueLabels(input.exec, input.repository, issue.number, triage.automation.clear, triage.account);
297
- }
298
- const report = `Magi triage cleared #${issue.number} because a related PR handles it.`;
299
- await writeFile(join(outputDir, "report.md"), `${report}\n`);
300
- return { issue: issue.number, outputDir, report, result: "CLEAR_ONLY" };
764
+ return finishWithResult({
765
+ context,
766
+ input,
767
+ issue,
768
+ outputDir,
769
+ processed,
770
+ relationship,
771
+ result: "CLEAR_ONLY",
772
+ });
301
773
  }
302
774
  }
303
- if (relationship.duplicateCandidates.length) {
775
+ if (!result && relationship.duplicateCandidates.length) {
304
776
  const duplicate = await runDuplicateVote({
305
777
  candidateNumbers: relationship.duplicateCandidates.map((candidate) => candidate.number),
306
778
  context,
@@ -308,113 +780,69 @@ export async function runTriage(input) {
308
780
  outputDir,
309
781
  });
310
782
  if (duplicate) {
311
- const body = `@${issue.author} Magi triage found this issue duplicates #${duplicate.duplicateOf}.\n\nReason: ${duplicate.reason}\n\n${marker({ action: "CLOSE", issue: issue.number, result: "DUPLICATE" })}`;
312
- if (!input.dryRun) {
313
- await postIssueComment(input.exec, input.repository, issue.number, triage.account, body);
314
- }
315
- if (!input.dryRun && triage.automation.close) {
316
- for (const pr of relationship.relatedPullRequests.filter((pr) => pr.state === "OPEN")) {
317
- await closePullRequest(input.exec, input.repository, pr.number, triage.account);
318
- }
319
- await closeIssue(input.exec, input.repository, issue.number, triage.account);
320
- }
321
- if (!input.dryRun) {
322
- await removeIssueLabels(input.exec, input.repository, issue.number, triage.automation.clear, triage.account);
323
- }
324
- const report = `Magi triage marked #${issue.number} duplicate of #${duplicate.duplicateOf}.`;
325
- await writeFile(join(outputDir, "report.md"), `${report}\n`);
326
- return { issue: issue.number, outputDir, report, result: "DUPLICATE" };
783
+ context = `${context}\n\nDuplicate decision: ${JSON.stringify(duplicate)}`;
784
+ result = "DUPLICATE";
327
785
  }
328
786
  }
329
- const kind = resolveIssueKind(issue, input.repository) ??
330
- (await runPhaseVote({
331
- context,
332
- input,
333
- outputDir,
334
- parse: parseTriageKindOutput,
335
- phase: "kind",
336
- prompt: composeTriageKindPrompt,
337
- schemaName: "triage kind",
338
- votes: KIND_VOTES,
339
- })) ??
340
- "ASK";
341
- let result = "ASK";
342
- if (kind === "BUG") {
343
- const vote = await runPhaseVote({
344
- context,
345
- input,
346
- outputDir,
347
- parse: parseTriageBinaryOutput,
348
- phase: "bug",
349
- prompt: composeTriageBugPrompt,
350
- schemaName: "triage bug",
351
- votes: BINARY_VOTES,
352
- });
353
- result =
354
- vote === "YES" ? "BUG_ACCEPTED" : vote === "NO" ? "BUG_REJECTED" : "ASK";
355
- }
356
- if (kind === "FEATURE") {
357
- const vote = await runPhaseVote({
358
- context,
359
- input,
360
- outputDir,
361
- parse: parseTriageBinaryOutput,
362
- phase: "feature",
363
- prompt: composeTriageFeaturePrompt,
364
- schemaName: "triage feature",
365
- votes: BINARY_VOTES,
787
+ if (!result) {
788
+ const resolvedKind = resolveIssueKind(issue, input.repository);
789
+ await writeJson(join(outputDir, "kind-resolution.json"), {
790
+ kind: resolvedKind,
791
+ source: resolvedKind ? "config" : "vote",
366
792
  });
367
- result =
368
- vote === "YES"
369
- ? "FEATURE_ACCEPTED"
370
- : vote === "NO"
371
- ? "FEATURE_REJECTED"
372
- : "ASK";
373
- }
374
- const needsClose = triage.automation.close &&
375
- (result === "BUG_REJECTED" || result === "FEATURE_REJECTED");
376
- const needsPr = triage.automation.pr &&
377
- (result === "BUG_ACCEPTED" || result === "FEATURE_ACCEPTED");
378
- const commentContext = `Result: ${result}\n\n${context}`;
379
- const commentPrompt = composeTriageCommentPrompt({
380
- author: issue.author,
381
- context: commentContext,
382
- directory: input.directory,
383
- issue: issue.number,
384
- repository: input.repository,
385
- });
386
- const comment = (await runModelText({
387
- allowEmpty: false,
388
- client: input.client,
389
- model: agents[0].model,
390
- options: agents[0].options,
391
- permission: agents[0].permission,
392
- prompt: commentPrompt,
393
- signal: input.signal,
394
- title: `Magi triage comment #${issue.number}`,
395
- })).raw + `\n\n${marker({ action: result, issue: issue.number, result })}`;
396
- let prUrl;
397
- if (!input.dryRun) {
398
- await postIssueComment(input.exec, input.repository, issue.number, triage.account, comment);
399
- if (needsClose) {
400
- for (const pr of relationship.relatedPullRequests.filter((pr) => pr.state === "OPEN")) {
401
- await closePullRequest(input.exec, input.repository, pr.number, triage.account);
402
- }
403
- await closeIssue(input.exec, input.repository, issue.number, triage.account);
793
+ const kind = resolvedKind ??
794
+ (await runPhaseVote({
795
+ context,
796
+ input,
797
+ outputDir,
798
+ parse: parseTriageKindOutput,
799
+ phase: "kind",
800
+ prompt: composeTriageKindPrompt,
801
+ schemaName: "triage kind",
802
+ votes: KIND_VOTES,
803
+ })) ??
804
+ "ASK";
805
+ result = "ASK";
806
+ if (kind === "BUG") {
807
+ const vote = await runPhaseVote({
808
+ context,
809
+ input,
810
+ outputDir,
811
+ parse: parseTriageBinaryOutput,
812
+ phase: "bug",
813
+ prompt: composeTriageBugPrompt,
814
+ schemaName: "triage bug",
815
+ votes: BINARY_VOTES,
816
+ });
817
+ result =
818
+ vote === "YES" ? "BUG_ACCEPTED" : vote === "NO" ? "BUG_REJECTED" : "ASK";
404
819
  }
405
- if (needsPr)
406
- prUrl = await createImplementationPr({ context, input, issue, outputDir });
407
- if (result !== "ASK") {
408
- await removeIssueLabels(input.exec, input.repository, issue.number, triage.automation.clear, triage.account);
820
+ if (kind === "FEATURE") {
821
+ const vote = await runPhaseVote({
822
+ context,
823
+ input,
824
+ outputDir,
825
+ parse: parseTriageBinaryOutput,
826
+ phase: "feature",
827
+ prompt: composeTriageFeaturePrompt,
828
+ schemaName: "triage feature",
829
+ votes: BINARY_VOTES,
830
+ });
831
+ result =
832
+ vote === "YES"
833
+ ? "FEATURE_ACCEPTED"
834
+ : vote === "NO"
835
+ ? "FEATURE_REJECTED"
836
+ : "ASK";
409
837
  }
410
838
  }
411
- const report = [
412
- `Magi triage result for #${issue.number}: ${result}`,
413
- prUrl ? `Created PR: ${prUrl}` : undefined,
414
- input.dryRun ? "Dry run: no GitHub mutations were performed." : undefined,
415
- ]
416
- .filter(Boolean)
417
- .join("\n");
418
- await writeFile(join(outputDir, "report.md"), `${report}\n`);
419
- return { issue: issue.number, outputDir, report, result };
839
+ return finishWithResult({
840
+ context,
841
+ input,
842
+ issue,
843
+ outputDir,
844
+ processed,
845
+ relationship,
846
+ result: result ?? "ASK",
847
+ });
420
848
  }