forked from just-every/code
-
Notifications
You must be signed in to change notification settings - Fork 0
629 lines (594 loc) · 32.1 KB
/
issue-comment.yml
File metadata and controls
629 lines (594 loc) · 32.1 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
name: Issue Comment
on:
# Automatic: when Preview Build finishes successfully for a PR
workflow_run:
workflows: ["Preview Build"]
types: [completed]
# From triage (or elsewhere): direct repository dispatch
repository_dispatch:
types: [issue-comment]
# Manual: allow maintainers to trigger for a specific PR
workflow_dispatch:
inputs:
pr_number:
description: "PR number to post preview comment to linked issue"
required: true
type: number
type:
description: "comment type (preview|comment)"
required: false
default: preview
type: choice
options: [preview, comment]
issue_number:
description: "Issue number (for type=comment)"
required: false
type: number
context:
description: "Optional context to include in the comment"
required: false
type: string
concurrency:
group: issue-comment-${{ github.event_name == 'workflow_dispatch' && inputs.pr_number || github.event.workflow_run.id }}
cancel-in-progress: true
permissions:
contents: read
issues: write
pull-requests: read
actions: read
jobs:
comment:
name: Post preview instructions to linked issue
if: >-
(github.event_name == 'workflow_run' &&
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion == 'success')
|| (github.event_name == 'workflow_dispatch' && (inputs.type == 'preview' || !inputs.type))
runs-on: ubuntu-latest
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Resolve PR + Issue
id: meta
uses: actions/github-script@v7
with:
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
// Determine PR number from workflow_run payload or manual input
let prNumber = 0;
if (context.eventName === 'workflow_run') {
const wr = context.payload.workflow_run;
const prs = Array.isArray(wr.pull_requests) ? wr.pull_requests : [];
if (prs.length) prNumber = prs[0].number;
} else {
prNumber = Number((context.payload.inputs && context.payload.inputs.pr_number) || 0);
}
if (!prNumber) {
// No PR associated with this workflow_run (e.g., manual re-run or non-PR trigger).
// Do not fail the job; set empty outputs so downstream steps can skip safely.
core.notice('No PR associated with this run; skipping preview issue comment steps.');
core.setOutput('pr_number', '');
core.setOutput('issue_number', '0');
core.setOutput('title', '');
core.setOutput('body', '');
core.setOutput('head', '');
core.setOutput('base', '');
core.setOutput('changed', '');
core.setOutput('commits', '');
core.setOutput('issue_author', '');
return;
}
// Fetch PR details
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: prNumber });
// Try to derive issue number from head branch (issue-123), PR body/title references, or linked issues
let issueNumber = 0;
const branch = pr.head.ref || '';
const m = branch.match(/^issue-(\d+)$/);
if (m) issueNumber = Number(m[1]);
function findIssueRef(text) {
if (!text) return 0;
// Prefer explicit forms like "Closes #123" or "#123"
const rx = /(close[sd]?|fix(e[sd])?|resolve[sd]?)?\s*#(\d{1,6})/ig;
let best = 0; let mm;
while ((mm = rx.exec(text))) { best = Number(mm[3]); }
return best;
}
if (!issueNumber) issueNumber = findIssueRef(pr.body);
if (!issueNumber) issueNumber = findIssueRef(pr.title);
// Quick fallback: search issues mentioning the PR number (rarely needed)
if (!issueNumber) {
try {
const q = `repo:${owner}/${repo} is:issue ${pr.number}`;
const s = await github.rest.search.issuesAndPullRequests({ q, per_page: 5 });
const hit = s.data.items.find(i => i.pull_request == null);
if (hit) issueNumber = hit.number;
} catch {}
}
// Collect a compact file summary for context
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: prNumber, per_page: 100 });
const changed = files.map(f => `- ${f.status.padEnd(6)} ${f.filename}`).slice(0, 50);
// Issue author
let issueAuthor = '';
if (issueNumber) {
try {
const { data: iss } = await github.rest.issues.get({ owner, repo, issue_number: issueNumber });
issueAuthor = iss.user?.login || '';
} catch {}
}
// Collect latest commit subjects on the PR (brief)
let commits = [];
try {
const all = await github.paginate(github.rest.pulls.listCommits, { owner, repo, pull_number: prNumber, per_page: 100 });
commits = all.slice(-5).map(c => `- ${c.commit.message.split('\n')[0]}`);
} catch {}
core.setOutput('pr_number', String(prNumber));
core.setOutput('issue_number', String(issueNumber || 0));
core.setOutput('title', pr.title || '');
core.setOutput('body', pr.body || '');
core.setOutput('head', pr.head.ref || '');
core.setOutput('base', pr.base.ref || '');
core.setOutput('changed', changed.join('\n'));
core.setOutput('commits', commits.join('\n'));
core.setOutput('issue_author', issueAuthor);
- name: Prepare context file
if: steps.meta.outputs.pr_number
id: ctx
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ steps.meta.outputs.pr_number }}
TITLE: ${{ steps.meta.outputs.title }}
BODY: ${{ steps.meta.outputs.body }}
CHANGED: ${{ steps.meta.outputs.changed }}
COMMITS: ${{ steps.meta.outputs.commits }}
ISSUE_AUTHOR: ${{ steps.meta.outputs.issue_author }}
ISSUE_NUMBER: ${{ steps.meta.outputs.issue_number }}
with:
script: |
const fs = require('fs');
const owner = context.repo.owner; const repo = context.repo.repo;
const pr = Number(process.env.PR_NUMBER);
const issue_number = Number(process.env.ISSUE_NUMBER || 0);
// resolve slug
const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pr });
const marker = /<!--\s*codex-id:\s*([a-z0-9-]{3,})\s*-->/i;
function normalizeSlug(s){ if(!s) return ''; let x=String(s).toLowerCase().trim(); if(x.startsWith('code/')) x=x.slice(5); if(x.startsWith('id/')) x=x.slice(3); x=x.replace(/[^a-z0-9-]+/g,'-').replace(/-+/g,'-').replace(/^-|-$/g,''); return /^[a-z0-9-]{3,}$/.test(x)?x:''; }
let slug = '';
// PR labels first
try { const labs = await github.paginate(github.rest.issues.listLabelsOnIssue, { owner, repo, issue_number: pr, per_page: 100 });
const names = labs.map(l => (typeof l === 'string' ? l : l.name)).filter(Boolean);
const codeLabel = names.find(n => n.startsWith('code/'));
const idLabel = names.find(n => n.startsWith('id/'));
slug = normalizeSlug(codeLabel || idLabel || '');
} catch {}
// PR body
if (!slug) { const m = (pull.body || '').match(marker); if (m) slug = normalizeSlug(m[1]); }
// PR comments
if (!slug) {
try { const prc = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number: pr, per_page: 100 });
for (const c of prc) { const mm = (c.body || '').match(marker); if (mm) { slug = normalizeSlug(mm[1]); if (slug) break; } }
} catch {}
}
// Linked issue via branch
const b = pull.head.ref || '';
const im = b.match(/^issue-(\d+)$/); let issue_number2 = 0; if (im) issue_number2 = Number(im[1]);
if (!slug && issue_number2) {
try {
const { data: iss } = await github.rest.issues.get({ owner, repo, issue_number: issue_number2 });
const labels = (iss.labels || []).map(l => (typeof l === 'string' ? l : l.name)).filter(Boolean);
const codeLabel = labels.find(n => typeof n === 'string' && n.startsWith('code/'));
const idLabel = labels.find(n => typeof n === 'string' && n.startsWith('id/'));
slug = normalizeSlug(codeLabel || idLabel || '');
if (!slug) {
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number: issue_number2, per_page: 100 });
for (const c of comments) { const mm = (c.body || '').match(marker); if (mm) { slug = normalizeSlug(mm[1]); if (slug) break; } }
}
} catch {}
}
if (!slug) throw new Error('Missing ID. Add code/<slug> label or <!-- codex-id: <slug> -->.');
// resolve latest tag for slug
const baseTag = `preview-${slug}`;
const rels = await github.paginate(github.rest.repos.listReleases, { owner, repo, per_page: 100 });
let tag = baseTag; let maxN = 0; let hasBase = false;
for (const r of rels) {
const t = r.tag_name || '';
if (t === baseTag) { hasBase = true; maxN = Math.max(maxN, 1); tag = baseTag; }
const mm = t.match(new RegExp(`^${baseTag}-(\\d+)$`));
if (mm) { const n = parseInt(mm[1], 10); if (n > maxN) { maxN = n; tag = t; } }
}
const releaseBase = `https://github.com/${owner}/${repo}/releases/download/${tag}`;
const lines = [];
lines.push(`# PR #${pr}: ${process.env.TITLE || ''}`);
lines.push('');
lines.push(`PR: https://github.com/${owner}/${repo}/pull/${pr}`);
lines.push('');
if ((process.env.BODY || '').trim()) {
lines.push('## PR body');
lines.push(process.env.BODY.trim());
lines.push('');
}
if ((process.env.CHANGED || '').trim()) {
lines.push('## Changed files (first 50)');
lines.push(process.env.CHANGED.trim());
lines.push('');
}
// Commit subjects and links
try {
const commits = await github.paginate(github.rest.pulls.listCommits, { owner, repo, pull_number: pr, per_page: 100 });
const recent = commits.slice(-5);
if (recent.length) {
lines.push('## What changed in this build (recent commits)');
lines.push(recent.map(c => `- ${c.commit.message.split('\n')[0]}`).join('\n'));
lines.push('');
lines.push('## Commit links');
lines.push(recent.map(c => `- ${c.commit.message.split('\n')[0]} (${c.sha.substring(0,7)}): https://github.com/${owner}/${repo}/commit/${c.sha}`).join('\n'));
lines.push('');
}
} catch {}
// Issue body and recent comments for agent context
if (issue_number) {
try {
const { data: issue } = await github.rest.issues.get({ owner, repo, issue_number });
lines.push('## Issue #'+issue_number+' context');
lines.push('### Issue body');
lines.push((issue.body || '').trim());
lines.push('');
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number, per_page: 100 });
if (comments.length) {
lines.push('### Recent issue comments (oldest first, up to 10)');
// Keep chronological order so the newest appears at the bottom
const last = comments.slice(-10);
for (const c of last) {
const when = (c.created_at || '').replace('T',' ').replace('Z','');
lines.push(`- [@${c.user?.login||'unknown'} at ${when}]`);
const body = (c.body || '').trim();
lines.push(body.length > 1200 ? body.slice(0,1200)+"\n…" : body);
lines.push('');
}
}
} catch {}
}
lines.push('## Preview command');
lines.push('```bash');
lines.push(`code preview ${slug}`);
lines.push('```');
lines.push('');
lines.push(`Issue author: @${process.env.ISSUE_AUTHOR || ''}`);
fs.mkdirSync('.github/auto', { recursive: true });
fs.writeFileSync('.github/auto/ISSUE_PREVIEW_CONTEXT.md', lines.join('\n'));
- name: Start local OpenAI proxy (optional; hardened)
if: steps.meta.outputs.pr_number && env.OPENAI_API_KEY != ''
id: proxy
run: |
set -euo pipefail
mkdir -p .github/auto
PORT=5056 LOG_DEST=stdout EXIT_ON_5XX=1 RESPONSES_BETA="responses=v1" node scripts/openai-proxy.js > .github/auto/openai-proxy.log 2>&1 &
for i in {1..30}; do if nc -z 127.0.0.1 5056; then break; else sleep 0.2; fi; done || true
- name: Print proxy startup log tail
if: steps.meta.outputs.pr_number && env.OPENAI_API_KEY != ''
run: |
echo '### openai-proxy.log (tail)' >> "$GITHUB_STEP_SUMMARY"
{ echo '```'; tail -n 80 .github/auto/openai-proxy.log || true; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
- name: Generate comment with Code (read-only)
id: gen
if: steps.meta.outputs.pr_number && env.OPENAI_API_KEY != ''
continue-on-error: true
env:
ISSUE_AUTHOR: ${{ steps.meta.outputs.issue_author }}
run: |
set -euo pipefail
SAFE_PATH="$PATH"; SAFE_HOME="$HOME";
PROMPT=$(cat <<EOP
<task>
You are writing an enthusiastic, user‑facing issue reply about a successful preview build. Please do not assume the user has deep technical knowledge.
Use the following template, but adapt all language to this specific change. Be friendly and curious where appropriate.
You MAY remove sections that repeat earlier replies.
TEMPLATE (example):
---
@user Thanks for the great feature request! Changing the title is an interesting personalization and ties in really well with our existing theme options. [Replace this sentence with specific feedback to the user and reference their idea. Always start by mentioning them.]
I’ve added the ability to edit the title from the /theme slash command, since that’s where the existing theme functionality lives. [Explain in simple, non‑technical language what changed.]
You can run this right now—can’t wait for you to try it! In your terminal, run: [Be excited but concise.]
```
code preview <slug here>
```
Then run /theme in the terminal to see the new option. [Explain how to try it once launched.]
Can’t wait for you to try changing your title! Please comment here if it’s working well or needs tweaks. Maintainers will review and, if merged into a release, you’ll get an update here. Thanks again! [Positive, personable close.]
---
REQUIREMENTS:
- Replace @user with the actual GitHub handle(s) of the person you are replying to (either the issue author and/or last commenter).
- Replace <slug here> with the exact preview command from the context below.
- Keep it brief, clear, and kind.
</task>
<context>
$(cat .github/auto/ISSUE_PREVIEW_CONTEXT.md)
</context>
Output ONLY:
<comment>
…final Markdown comment…
</comment>
EOP
)
set +e
{ printf '%s' "$PROMPT" | env -i PATH="$SAFE_PATH" HOME="$SAFE_HOME" \
OPENAI_API_KEY="x" OPENAI_BASE_URL="http://127.0.0.1:5056/v1" \
npx -y @just-every/code@latest exec -s read-only --cd "$GITHUB_WORKSPACE" --skip-git-repo-check -; } \
2>&1 | tee .github/auto/AGENT_OUT.txt
true
set -e
- name: Assert agent success (fail on server 5xx only; tolerate local stream errors)
if: steps.meta.outputs.pr_number && env.OPENAI_API_KEY != ''
continue-on-error: true
run: |
set -euo pipefail
if [ -s .github/auto/openai-proxy.log ]; then
if rg -n '"phase":"response_head".*"status":5\\d\\d' .github/auto/openai-proxy.log >/dev/null 2>&1; then
echo "Proxy observed 5xx from upstream during agent run. Failing job." >&2
rg -n '"phase":"response_head".*"status":5\\d\\d' .github/auto/openai-proxy.log | tail -n 10 || true
exit 1
fi
if rg -n '"phase":"upstream_error"' .github/auto/openai-proxy.log >/dev/null 2>&1; then
echo "Proxy upstream_error entries found. Failing job." >&2
rg -n '"phase":"upstream_error"' .github/auto/openai-proxy.log | tail -n 10 || true
exit 1
fi
fi
node - <<'JS'
const fs = require('fs');
const t = fs.readFileSync('.github/auto/AGENT_OUT.txt','utf8');
// Extract comment by: find the LAST opening <comment>, then the FIRST closing </comment> after it.
// This avoids earlier stray tags in reasoning blocks.
const PLACEHOLDER = '…final Markdown comment…';
const lower = t.toLowerCase();
const openTag = '<comment>';
const closeTag = '</comment>';
const openIdx = lower.lastIndexOf(openTag);
let body = '';
if (openIdx !== -1) {
const closeIdx = lower.indexOf(closeTag, openIdx + openTag.length);
if (closeIdx !== -1) {
body = t.slice(openIdx + openTag.length, closeIdx).trim();
}
}
if (body && body !== PLACEHOLDER) {
fs.writeFileSync('.github/auto/ISSUE_COMMENT.md', body + '\n');
}
JS
- name: Post comment to linked issue (upsert by marker; fallback to stock)
if: steps.meta.outputs.pr_number
uses: actions/github-script@v7
env:
ISSUE_NUMBER: ${{ steps.meta.outputs.issue_number }}
PR_NUMBER: ${{ steps.meta.outputs.pr_number }}
with:
github-token: ${{ secrets.CODE_GH_PAT || secrets.GITHUB_TOKEN }}
script: |
const fs = require('fs');
const owner = context.repo.owner; const repo = context.repo.repo;
const issue_number = Number(process.env.ISSUE_NUMBER || 0);
const pr = Number(process.env.PR_NUMBER || 0);
if (!issue_number) { core.notice('No linked issue detected; skipping issue comment.'); return; }
const ISSUE_MARK = '<!-- preview-build:issue -->';
let body = '';
try { body = fs.readFileSync('.github/auto/ISSUE_COMMENT.md','utf8').trim(); } catch {}
const PLACEHOLDER = '…final Markdown comment…';
if (body && body.includes(PLACEHOLDER)) { body = ''; }
if (!body) {
// derive slug + latest tag (PR labels → PR body → PR comments → linked issue)
const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pr });
const slugRe = /<!--\s*codex-id:\s*([a-z0-9-]{3,})\s*-->/i;
const normalize = s => { if(!s) return ''; let x=String(s).toLowerCase().trim(); if(x.startsWith('code/')) x=x.slice(5); if(x.startsWith('id/')) x=x.slice(3); x=x.replace(/[^a-z0-9-]+/g,'-').replace(/-+/g,'-').replace(/^-|-$/g,''); return /^[a-z0-9-]{3,}$/.test(x)?x:''; };
let slug = '';
try { const labs = await github.paginate(github.rest.issues.listLabelsOnIssue, { owner, repo, issue_number: pr, per_page: 100 });
const names = labs.map(l => (typeof l === 'string' ? l : l.name)).filter(Boolean);
const codeLabel = names.find(n => n.startsWith('code/'));
const idLabel = names.find(n => n.startsWith('id/'));
slug = normalize(codeLabel || idLabel || '');
} catch {}
if (!slug) { const m = (pull.body || '').match(slugRe); if (m) slug = normalize(m[1]); }
if (!slug) {
try { const prc = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number: pr, per_page: 100 });
for (const c of prc) { const mm = (c.body || '').match(slugRe); if (mm) { slug = normalize(mm[1]); if (slug) break; } }
} catch {}
}
if (!slug) {
const b = pull.head.ref || '';
const im = b.match(/^issue-(\d+)$/); let issue_number2 = 0; if (im) issue_number2 = Number(im[1]);
if (issue_number2) {
// labels on linked issue
try { const iss = await github.rest.issues.get({ owner, repo, issue_number: issue_number2 });
const labels = (iss.data.labels || []).map(l => (typeof l === 'string' ? l : l.name)).filter(Boolean);
const codeLabel = labels.find(n => typeof n === 'string' && n.startsWith('code/'));
const idLabel = labels.find(n => typeof n === 'string' && n.startsWith('id/'));
slug = normalize(codeLabel || idLabel || '');
} catch {}
if (!slug) {
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number: issue_number2, per_page: 100 });
for (const c of comments) { const mm = (c.body || '').match(slugRe); if (mm) { slug = normalize(mm[1]); if (slug) break; } }
}
}
}
const baseTag = `preview-${slug}`;
const rels = await github.paginate(github.rest.repos.listReleases, { owner, repo, per_page: 100 });
let tag = baseTag; let maxN = 0; let hasBase = false;
for (const r of rels) {
const t = r.tag_name || '';
if (t === baseTag) { hasBase = true; maxN = Math.max(maxN, 1); tag = baseTag; }
const mm = t.match(new RegExp(`^${baseTag}-(\\d+)$`));
if (mm) { const n = parseInt(mm[1], 10); if (n > maxN) { maxN = n; tag = t; } }
}
const base = `https://github.com/${owner}/${repo}/releases/download/${tag}`;
// Pull a short commit summary for this PR
let commits = [];
try {
const all = await github.paginate(github.rest.pulls.listCommits, { owner, repo, pull_number: pr, per_page: 100 });
commits = all.slice(-5).map(c => `- ${c.commit.message.split('\n')[0]}`);
} catch {}
// Synthesized fallback matching the template (no direct downloads)
const issueAuthor = `${{ steps.meta.outputs.issue_author }}` || '';
body = [
ISSUE_MARK,
`@${issueAuthor} Thanks for the great request — a preview is ready!`,
'',
'You can run it right now:',
'```bash',
`code preview ${slug}`,
'```',
'',
'Please let us know here if it works well or needs tweaks. Maintainers will review and, if merged, you’ll get an update here. Thanks again! ',
'',
commits.length ? 'Changes made:' : '',
commits.length ? commits.join('\n') : '',
ISSUE_MARK
].filter(Boolean).join('\n');
}
// Upsert by marker on the issue
const all = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number, per_page: 100 });
const mine = all.find(c => c.user?.type?.toLowerCase().includes('bot') && (c.body || '').includes(ISSUE_MARK));
if (mine) {
await github.rest.issues.updateComment({ owner, repo, comment_id: mine.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number, body });
}
// Ensure the linked issue carries the canonical label code/<slug>
try {
const need = `code/${slug}`;
const labs = await github.paginate(github.rest.issues.listLabelsOnIssue, { owner, repo, issue_number, per_page: 100 });
const names = labs.map(l => (typeof l === 'string' ? l : l.name)).filter(Boolean);
if (!names.includes(need)) { await github.rest.issues.addLabels({ owner, repo, issue_number, labels: [need] }); }
} catch {}
dispatch_comment:
name: Post triage comment to issue (dispatch via Code)
if: github.event_name == 'repository_dispatch' && github.event.action == 'issue-comment'
runs-on: ubuntu-latest
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Prepare triage context
id: ctx
uses: actions/github-script@v7
env:
CONTEXT_TEXT: ${{ github.event.client_payload.context }}
with:
script: |
const fs = require('fs');
const owner = context.repo.owner; const repo = context.repo.repo;
const p = context.payload.client_payload || {};
const issue_number = Number(p.issue_number || 0);
if (!issue_number) { core.setFailed('Missing issue_number'); return; }
let issue = null; let comments = [];
try { const { data } = await github.rest.issues.get({ owner, repo, issue_number }); issue = data; } catch {}
try { comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number, per_page: 100 }); } catch {}
const lines = [];
lines.push(`# Issue #${issue_number}`);
if (issue && issue.title) { lines.push(`Title: ${issue.title}`); lines.push(''); }
if (issue && issue.body) { lines.push('## Issue body'); lines.push(issue.body); lines.push(''); }
if (process.env.CONTEXT_TEXT && process.env.CONTEXT_TEXT.trim()) { lines.push('## Triage context'); lines.push(process.env.CONTEXT_TEXT.trim()); lines.push(''); }
if (comments.length) {
lines.push('## Recent comments (oldest first, up to 10)');
// Chronological order: newest at the bottom
const last = comments.slice(-10);
for (const c of last) {
const when = (c.created_at || '').replace('T',' ').replace('Z','');
lines.push(`- [@${c.user?.login||'unknown'} at ${when}]`);
const body = (c.body || '').trim();
lines.push(body.length > 1200 ? body.slice(0,1200)+"\n…" : body);
lines.push('');
}
}
fs.mkdirSync('.github/auto', { recursive: true });
fs.writeFileSync('.github/auto/ISSUE_TRIAGE_CONTEXT.md', lines.join('\n'));
core.setOutput('issue_number', String(issue_number));
- name: Start local OpenAI proxy (optional; hardened)
if: env.OPENAI_API_KEY != ''
id: proxy
run: |
set -euo pipefail
mkdir -p .github/auto
PORT=5056 LOG_DEST=stdout EXIT_ON_5XX=1 RESPONSES_BETA="responses=v1" node scripts/openai-proxy.js > .github/auto/openai-proxy.log 2>&1 &
for i in {1..30}; do if nc -z 127.0.0.1 5056; then break; else sleep 0.2; fi; done || true
- name: Print proxy startup log tail
if: env.OPENAI_API_KEY != ''
run: |
echo '### openai-proxy.log (tail)' >> "$GITHUB_STEP_SUMMARY"
{ echo '```'; tail -n 80 .github/auto/openai-proxy.log || true; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
- name: Generate triage comment with Code (read-only)
if: env.OPENAI_API_KEY != ''
id: gen
continue-on-error: true
run: |
set -euo pipefail
SAFE_PATH="$PATH"; SAFE_HOME="$HOME";
PROMPT=$(cat <<EOP
<task>
Write a brief, kind GitHub issue reply explaining that the bot did not auto-apply changes yet and needs more details.
- Do not include any internal IDs, request IDs, or API errors.
- Do not suggest preview commands or code blocks.
- Ask for concrete steps to reproduce, expected vs actual behavior, and logs or screenshots.
- Keep it to 3–6 short sentences. Friendly, clear, and helpful.
- Address the issue author if visible in the context.
Respond with exactly one <comment>…</comment> block containing the final Markdown, and nothing else.
</task>
<context>
$(cat .github/auto/ISSUE_TRIAGE_CONTEXT.md)
</context>
EOP
)
set +e
{ printf '%s' "$PROMPT" | env -i PATH="$SAFE_PATH" HOME="$SAFE_HOME" \
OPENAI_API_KEY="x" OPENAI_BASE_URL="http://127.0.0.1:5056/v1" \
CARGO_HOME="$GITHUB_WORKSPACE/.cargo-home" \
RUSTUP_HOME="$GITHUB_WORKSPACE/.cargo-home/rustup" \
CARGO_TARGET_DIR="$GITHUB_WORKSPACE/codex-rs/target" \
STRICT_CARGO_HOME="1" \
npx -y @just-every/code@latest exec -s read-only --cd "$GITHUB_WORKSPACE" --skip-git-repo-check -; } \
2>&1 | tee .github/auto/TRIAGE_AGENT_OUT.txt
true
set -e
- name: Extract generated comment
if: env.OPENAI_API_KEY != ''
run: |
set -euo pipefail
node - <<'JS'
const fs = require('fs');
const t = fs.readFileSync('.github/auto/TRIAGE_AGENT_OUT.txt','utf8');
const lower = t.toLowerCase();
const openTag = '<comment>';
const closeTag = '</comment>';
const openIdx = lower.lastIndexOf(openTag);
let body = '';
if (openIdx !== -1) {
const closeIdx = lower.indexOf(closeTag, openIdx + openTag.length);
if (closeIdx !== -1) body = t.slice(openIdx + openTag.length, closeIdx).trim();
}
const PLACEHOLDER = '…final Markdown comment…';
if (body && body !== PLACEHOLDER) fs.writeFileSync('.github/auto/ISSUE_COMMENT.md', body + '\n');
JS
- name: Post generated comment to issue
if: env.OPENAI_API_KEY != ''
uses: actions/github-script@v7
env:
ISSUE_NUMBER: ${{ steps.ctx.outputs.issue_number }}
with:
github-token: ${{ secrets.CODE_GH_PAT || secrets.GITHUB_TOKEN }}
script: |
const fs = require('fs');
const owner = context.repo.owner; const repo = context.repo.repo;
const issue_number = Number(process.env.ISSUE_NUMBER || 0);
const ISSUE_MARK = '<!-- triage:comment -->';
let body = '';
try { body = fs.readFileSync('.github/auto/ISSUE_COMMENT.md','utf8').trim(); } catch {}
const PLACEHOLDER = '…final Markdown comment…';
if (!body || body.includes(PLACEHOLDER)) { core.notice('No generated comment (placeholder only); skipping'); return; }
body = ISSUE_MARK + '\n' + body + '\n' + ISSUE_MARK;
const all = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number, per_page: 100 });
const mine = all.find(c => c.user?.type?.toLowerCase().includes('bot') && (c.body || '').includes(ISSUE_MARK));
if (mine) await github.rest.issues.updateComment({ owner, repo, comment_id: mine.id, body });
else await github.rest.issues.createComment({ owner, repo, issue_number, body });
- name: Skip when no OPENAI_API_KEY
if: env.OPENAI_API_KEY == ''
run: |
echo "OPENAI_API_KEY not set; skipping Code-generated triage comment." >> "$GITHUB_STEP_SUMMARY"