-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.js
More file actions
1119 lines (1039 loc) · 50.4 KB
/
Copy pathgithub.js
File metadata and controls
1119 lines (1039 loc) · 50.4 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
// GitHub integration — Code Flow + Dev card parity with azdo.js.
//
// Auth: secretless first — mirrors the `az` pattern using the GitHub CLI
// (`gh auth token`). Fallbacks: GH_TOKEN / GITHUB_TOKEN env, then an optional
// PAT from settings. No token written to disk in the primary path.
//
// Signatures deliberately mirror azdo.js so forge.js can dispatch by descriptor
// with almost no call-site churn: the Code Flow read path uses the AzDo-style
// positional shape (owner, _project, repo, ...) and simply ignores the middle
// "project" slot (GitHub has no project). Work-item (issue) helpers are
// repo-scoped and take (owner, repo, number) because GitHub issues live in a
// repo, not a project — Dev-card callers branch on provider for those.
//
// REST only (no GraphQL): SAML-SSO orgs answer GraphQL with an SSO trap, and
// REST is sufficient for everything Code Flow needs. Thread "resolution" is
// therefore reported as unknown rather than faked.
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { execSync } = require('child_process');
const API_ROOT = 'https://api.github.com';
const API_VERSION_HEADER = '2022-11-28';
const HOST = 'github.com';
let SUPERVISOR_DATA_DIR;
try {
SUPERVISOR_DATA_DIR = require('./config-sync').SUPERVISOR_DATA_DIR;
} catch {
SUPERVISOR_DATA_DIR = path.join(process.env.USERPROFILE || process.env.HOME, '.copilot', 'agent-supervisor');
}
const GITHUB_STORE = path.join(SUPERVISOR_DATA_DIR, 'github-sources');
// Optional PAT fallback, read lazily from settings.js so a missing module or
// empty setting never breaks the primary `gh` path.
function _settingsPat() {
try {
const settings = require('./settings');
const s = (settings.getSettings && settings.getSettings()) || {};
const mode = s.githubAuthMode || 'cli';
if (mode === 'pat' && s.githubPat) return String(s.githubPat).trim();
// Even in cli/env mode, allow a stored PAT as a last resort.
if (s.githubPat) return String(s.githubPat).trim();
} catch {}
return '';
}
let _tokenCache = { token: null, expiresAt: 0 };
// Get a GitHub token. Primary: `gh auth token`. Fallbacks: env, settings PAT.
// gh tokens don't expose an expiry, so we cache for a conservative window and
// refresh on demand. forceRefresh bypasses the cache after a 401.
function getToken(forceRefresh = false) {
const now = Date.now();
if (!forceRefresh && _tokenCache.token && now < _tokenCache.expiresAt - 60_000) {
return _tokenCache.token;
}
let token = '';
// 1) GitHub CLI (secretless, primary).
try {
const raw = execSync(`gh auth token --hostname ${HOST}`, {
encoding: 'utf-8', timeout: 15_000, shell: true
}).trim();
if (/^gh[opsu]_|^github_pat_/.test(raw)) token = raw;
else if (raw && !/not logged|no oauth|error/i.test(raw)) token = raw;
} catch {}
// 2) Environment (CI / shells that exported a token).
if (!token) token = (process.env.GH_TOKEN || process.env.GITHUB_TOKEN || '').trim();
// 3) Optional stored PAT.
if (!token) token = _settingsPat();
if (!token) {
throw new Error(
'GitHub auth required. Run "gh auth login" on the server machine (or set GH_TOKEN, ' +
'or add a PAT under Settings → GitHub).'
);
}
_tokenCache = { token, expiresAt: now + 25 * 60_000 };
return token;
}
// ---- Core request --------------------------------------------------------
function _headers(token, accept) {
return {
Authorization: `Bearer ${token}`,
Accept: accept || 'application/vnd.github+json',
'X-GitHub-Api-Version': API_VERSION_HEADER,
'User-Agent': 'TheOffice.AI'
};
}
// Surface GitHub's SAML-SSO 403 clearly (the token is valid but not authorized
// for the org until the user approves it in the browser).
function _ssoMessage(res) {
const sso = res.headers.get('x-github-sso') || '';
if (sso) {
const m = sso.match(/url=([^;,\s]+)/i);
return 'GitHub blocked this token for a SAML-SSO org. Authorize it here: ' + (m ? m[1] : sso);
}
return '';
}
// Single request. Returns parsed JSON (or raw text when accept is a raw type).
// On 401 refreshes the token once. Follows no pagination itself — see apiAll.
async function api(rest, { method = 'GET', body, accept, raw = false } = {}) {
const url = rest.startsWith('http') ? rest : API_ROOT + rest;
const doFetch = (token) => fetch(url, {
method,
headers: {
..._headers(token, accept || (raw ? 'application/vnd.github.raw' : undefined)),
...(body ? { 'Content-Type': 'application/json' } : {})
},
body: body ? JSON.stringify(body) : undefined
});
let res = await doFetch(getToken());
if (res.status === 401) res = await doFetch(getToken(true));
const text = await res.text();
if (!res.ok) {
const sso = _ssoMessage(res);
let detail = '';
try { detail = (JSON.parse(text).message || '').slice(0, 300); } catch { detail = (text || '').slice(0, 300); }
if (res.status === 401) throw new Error('GitHub denied access (401). Token invalid or expired — run "gh auth login". ' + detail);
if (res.status === 403) throw new Error((sso || `GitHub denied access (403). ${detail}`));
if (res.status === 404) throw new Error(`GitHub resource not found (404). Check owner/repo/number. ${detail}`);
throw new Error(`GitHub request failed (${res.status}). ${detail}`);
}
if (raw || (accept && /raw|html|diff/.test(accept))) return text;
if (!text) return {};
try { return JSON.parse(text); }
catch { throw new Error('GitHub returned a non-JSON response.'); }
}
// Follow RFC5988 Link-header pagination and concatenate array results.
async function apiAll(rest, { cap = 500 } = {}) {
let url = rest.startsWith('http') ? rest : API_ROOT + rest;
const sep = url.includes('?') ? '&' : '?';
if (!/[?&]per_page=/.test(url)) url += sep + 'per_page=100';
const out = [];
for (let guard = 0; guard < 20 && url && out.length < cap; guard++) {
const res = await fetch(url, { headers: _headers(getToken()) });
if (res.status === 401) { getToken(true); continue; }
const text = await res.text();
if (!res.ok) {
const sso = _ssoMessage(res);
let detail = ''; try { detail = (JSON.parse(text).message || ''); } catch { detail = text.slice(0, 200); }
throw new Error(sso || `GitHub request failed (${res.status}). ${detail}`);
}
let arr = []; try { arr = JSON.parse(text); } catch {}
if (Array.isArray(arr)) out.push(...arr);
else if (arr && Array.isArray(arr.items)) out.push(...arr.items);
const link = res.headers.get('link') || '';
const next = link.match(/<([^>]+)>;\s*rel="next"/);
url = next ? next[1] : '';
}
return out.slice(0, cap);
}
// ---- Identity ------------------------------------------------------------
async function getCurrentUser(_owner) {
const u = await api('/user');
return {
id: u.login || '', // login IS the identity key for GitHub filters
login: u.login || '',
name: u.name || u.login || '',
email: u.email || '',
descriptor: u.login || ''
};
}
// ---- Listing -------------------------------------------------------------
// List repos for an owner. Tries org first, then the authed user's affiliations
// (owner + private) filtered to the owner, then the public user endpoint.
async function listRepos(owner, _project) {
const map = r => ({ id: r.id, name: r.name, defaultBranch: r.default_branch || 'main', private: !!r.private, fullName: r.full_name });
const login = (owner || '').trim();
// 1) Org repos.
try {
const orgRepos = await apiAll(`/orgs/${encodeURIComponent(login)}/repos?type=all&sort=full_name`);
if (orgRepos.length) return orgRepos.map(map).sort((a, b) => a.name.localeCompare(b.name));
} catch {}
// 2) The authed user's repos (covers personal + collaborator + private).
try {
const mine = await apiAll('/user/repos?affiliation=owner,collaborator,organization_member&sort=full_name');
const filtered = mine.filter(r => (r.owner && r.owner.login || '').toLowerCase() === login.toLowerCase());
if (filtered.length) return filtered.map(map).sort((a, b) => a.name.localeCompare(b.name));
} catch {}
// 3) Public user repos.
const pub = await apiAll(`/users/${encodeURIComponent(login)}/repos?type=owner&sort=full_name`);
return pub.map(map).sort((a, b) => a.name.localeCompare(b.name));
}
async function listBranches(owner, _project, repo) {
const data = await apiAll(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/branches`);
return data.map(b => b.name).filter(Boolean).sort((a, b) => a.localeCompare(b));
}
async function getRepo(owner, _project, repo) {
const r = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`);
return { id: r.id, name: r.name, defaultBranch: r.default_branch || 'main', fullName: r.full_name };
}
async function getRefObjectId(owner, _project, repo, branch) {
try {
const r = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/git/ref/heads/${encodeURIComponent(branch)}`);
return (r.object && r.object.sha) || null;
} catch { return null; }
}
// ---- Pull requests -------------------------------------------------------
// Map a GitHub review state to the AzDo vote scale so the shared UI works.
function _voteFor(state) {
switch (String(state || '').toUpperCase()) {
case 'APPROVED': return 10;
case 'CHANGES_REQUESTED': return -10;
case 'DISMISSED': return 0;
case 'PENDING': return -5;
case 'COMMENTED': return 0;
default: return 0;
}
}
function voteLabel(vote) {
switch (Number(vote)) {
case 10: return 'approved';
case 5: return 'approved-with-suggestions';
case -5: return 'waiting-for-author';
case -10: return 'rejected';
default: return 'no-vote';
}
}
function pullRequestUrl(owner, _project, repo, prId) {
return `https://github.com/${owner}/${repo}/pull/${prId}`;
}
function workItemUrl(owner, repo, id) {
return `https://github.com/${owner}/${repo}/issues/${id}`;
}
function cloneUrl(owner, _project, repo) {
return `https://github.com/${owner}/${encodeURIComponent(repo)}.git`;
}
// Normalize a GitHub PR (from /pulls or /pulls/{n}) into the neutral shape,
// with fork-aware head/base fields (R1). `reviews` (optional) enriches reviewer
// votes; without it, requested reviewers show as pending no-vote.
function _compactPr(d, owner, repo, reviews) {
const head = d.head || {}, base = d.base || {};
const headRepoFull = (head.repo && head.repo.full_name) || '';
const baseRepoFull = (base.repo && base.repo.full_name) || `${owner}/${repo}`;
const status = d.state === 'open' ? 'active' : (d.merged_at ? 'completed' : 'abandoned');
// Reviewers: collapse latest non-pending review per user, plus still-requested.
// The PR author is excluded — their own review comments (COMMENTED) are not a
// reviewer relationship and GitHub never lists them in the Reviewers sidebar.
const authorLogin = ((d.user && d.user.login) || '').toLowerCase();
const reviewerMap = new Map();
if (Array.isArray(reviews)) {
for (const rv of reviews) {
const login = (rv.user && rv.user.login) || '';
if (!login || login.toLowerCase() === authorLogin) continue;
if (String(rv.state).toUpperCase() === 'PENDING') continue;
// reviews are chronological; keep the last meaningful one per user
reviewerMap.set(login, { login, state: rv.state });
}
}
const reviewers = [];
for (const [login, r] of reviewerMap) {
reviewers.push({ id: login, name: login, login, vote: _voteFor(r.state), voteLabel: voteLabel(_voteFor(r.state)), isRequired: false });
}
for (const rr of (d.requested_reviewers || [])) {
const login = rr.login || '';
if (login && !reviewerMap.has(login)) {
reviewers.push({ id: login, name: login, login, vote: 0, voteLabel: 'no-vote', isRequired: true });
}
}
return {
provider: 'github',
id: d.number,
title: d.title || '',
description: (d.body || '').slice(0, 1200),
status,
isDraft: !!d.draft,
mergeStatus: d.mergeable_state || (d.merged ? 'merged' : ''),
sourceBranch: head.ref || '',
targetBranch: base.ref || '',
creationDate: d.created_at || '',
closedDate: d.closed_at || '',
createdBy: {
id: (d.user && d.user.login) || '',
name: (d.user && d.user.login) || '',
login: (d.user && d.user.login) || ''
},
reviewers,
// Fork-aware fields (R1) — worktree/sync/push must respect cross-repo heads.
headRepoFullName: headRepoFull,
headOwner: headRepoFull.split('/')[0] || owner,
headRepo: headRepoFull.split('/')[1] || repo,
headRef: head.ref || '',
headSha: head.sha || '',
baseRepoFullName: baseRepoFull,
baseRef: base.ref || '',
isCrossRepo: !!(headRepoFull && headRepoFull !== baseRepoFull),
org: owner, project: '', repo,
url: pullRequestUrl(owner, '', repo, d.number),
webUrl: d.html_url || pullRequestUrl(owner, '', repo, d.number)
};
}
// GitHub's /pulls has no server-side author/reviewer filter, so we list by state
// and client-filter by login. status: active(open) | completed/abandoned(closed)
// | all. creatorId / reviewerId are logins (from getCurrentUser().id).
async function listPullRequests(owner, _project, repo, { creatorId, reviewerId, status = 'active', top = 50 } = {}) {
const ghState = status === 'active' ? 'open' : (status === 'all' ? 'all' : 'closed');
const all = await apiAll(
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls?state=${ghState}&sort=updated&direction=desc`,
{ cap: Math.max(50, Number(top) || 50) }
);
let list = all;
const wantCreator = (creatorId || '').toLowerCase();
const wantReviewer = (reviewerId || '').toLowerCase();
if (wantCreator) list = list.filter(p => ((p.user && p.user.login) || '').toLowerCase() === wantCreator);
if (wantReviewer) list = list.filter(p => (p.requested_reviewers || []).some(r => (r.login || '').toLowerCase() === wantReviewer));
return list.slice(0, Number(top) || 50).map(p => _compactPr(p, owner, repo));
}
// Project-wide (all repos for an owner) — mirrors azdo.listProjectPullRequests.
// GitHub has no project scope, so this uses the Search API across the owner.
async function listProjectPullRequests(owner, _project, { creatorId, reviewerId, status = 'completed', top = 100 } = {}) {
const parts = [`org:${owner}`, 'is:pr'];
if (status === 'completed') parts.push('is:merged');
else if (status === 'abandoned') parts.push('is:closed', 'is:unmerged');
else if (status === 'active') parts.push('is:open');
if (creatorId) parts.push(`author:${creatorId}`);
if (reviewerId) parts.push(`review-requested:${reviewerId}`);
const q = encodeURIComponent(parts.join(' '));
const items = await apiAll(`/search/issues?q=${q}&sort=updated&order=desc`, { cap: Number(top) || 100 });
// Search returns issue-shaped PRs; fetch full PR for repo/branch context lazily
// would be N calls, so map what search gives and derive repo from repository_url.
return items.map(it => {
const m = (it.repository_url || '').match(/repos\/([^/]+)\/([^/]+)$/);
const o = m ? m[1] : owner, r = m ? m[2] : '';
return _compactPr({
number: it.number, title: it.title, body: it.body, state: it.state,
merged_at: it.pull_request && it.pull_request.merged_at,
draft: it.draft, created_at: it.created_at, closed_at: it.closed_at,
user: it.user, requested_reviewers: [], head: {}, base: { repo: { full_name: `${o}/${r}` } },
html_url: it.html_url
}, o, r);
});
}
async function getPullRequest(owner, _project, repo, prId) {
const d = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}`);
let reviews = [];
try { reviews = await apiAll(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}/reviews`, { cap: 200 }); } catch {}
return _compactPr(d, owner, repo, reviews);
}
// Full reviewer set for a single PR: everyone who submitted a review (with their
// vote) PLUS still-requested (pending) reviewers. The /pulls LIST endpoint only
// carries `requested_reviewers`, so anyone who has already reviewed drops off the
// board card — this merges in /reviews to restore them. Used by the codeflow
// enrichment step. Returns the neutral reviewer array (never throws).
async function getReviewers(owner, _project, repo, prId) {
const [d, reviews] = await Promise.all([
api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}`).catch(() => ({})),
apiAll(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}/reviews`, { cap: 200 }).catch(() => [])
]);
return _compactPr(d || {}, owner, repo, reviews).reviewers;
}
// Thread counts. GitHub REST can't tell resolved vs unresolved reliably, so we
// report open review comments and mark resolution unknown (R3).
async function getPrThreads(owner, _project, repo, prId) {
let review = [], issue = [];
try { review = await apiAll(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}/comments`, { cap: 300 }); } catch {}
const open = review.filter(c => c.in_reply_to_id == null); // top-level threads
return { activeComments: open.length, resolvedComments: 0, totalThreads: open.length, resolutionUnknown: true };
}
// Detailed open review-comment threads (file/line + comments), for an agent that
// must respond to feedback. Prefers non-outdated comments (position != null).
async function getPrActiveThreads(owner, _project, repo, prId, { max = 50 } = {}) {
let comments = [];
try { comments = await apiAll(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}/comments`, { cap: 300 }); } catch {}
// Group by thread root (in_reply_to_id chain collapses to the first comment).
const roots = new Map();
for (const c of comments) {
const rootId = c.in_reply_to_id || c.id;
if (!roots.has(rootId)) roots.set(rootId, []);
roots.get(rootId).push(c);
}
const out = [];
for (const [id, thread] of roots) {
const first = thread[0];
const outdated = first.position == null; // GitHub nulls position when outdated
const msgs = thread
.map(c => ({ author: (c.user && c.user.login) || 'unknown', text: String(c.body || '').trim() }))
.filter(c => c.text);
if (!msgs.length) continue;
out.push({
id,
status: outdated ? 'outdated' : 'active',
file: first.path || null,
line: first.line || first.original_line || null,
comments: msgs
});
if (out.length >= max) break;
}
// Prefer active over outdated when trimming.
out.sort((a, b) => (a.status === 'active' ? 0 : 1) - (b.status === 'active' ? 0 : 1));
return out.slice(0, max);
}
// Post ONE comment to a PR. Anchored (filePath + rightLine) → single inline
// review comment on head.sha, RIGHT side. Unanchored → issue comment. Mirrors
// azdo.createPrThread's per-thread contract; the validated all-or-nothing batch
// review is a separate Phase-4 path.
async function createPrThread(owner, _project, repo, prId, { content, filePath, rightLine } = {}) {
if (filePath) {
const pr = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}`);
const sha = (pr.head && pr.head.sha) || '';
const line = parseInt(rightLine, 10);
const body = { body: String(content || ''), commit_id: sha, path: String(filePath).replace(/^\/+/, ''), side: 'RIGHT' };
if (line > 0) body.line = line;
return api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}/comments`, { method: 'POST', body });
}
return api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues/${encodeURIComponent(prId)}/comments`, { method: 'POST', body: { body: String(content || '') } });
}
// Post a batch review with N validated inline comments in one call (R2). Caller
// pre-validates lines against the diff; unanchored findings fold into `bodyText`.
async function createReview(owner, _project, repo, prId, { comments = [], bodyText = '', commitId } = {}) {
let sha = commitId;
if (!sha) {
const pr = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}`);
sha = (pr.head && pr.head.sha) || '';
}
const body = {
event: 'COMMENT',
commit_id: sha,
body: bodyText || undefined,
comments: comments.map(c => ({ path: String(c.filePath || c.path).replace(/^\/+/, ''), line: parseInt(c.rightLine || c.line, 10), side: 'RIGHT', body: String(c.content || c.body || '') }))
};
return api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}/reviews`, { method: 'POST', body });
}
// Map a check-run/status to the shared validation enum.
function _checkState(run) {
if (run.status && run.status !== 'completed') return 'pending';
switch (String(run.conclusion || '').toLowerCase()) {
case 'success': return 'succeeded';
case 'failure': return 'failed';
case 'timed_out': case 'cancelled': case 'stale': case 'startup_failure': return 'error';
case 'action_required': return 'pending';
case 'neutral': case 'skipped': return 'notApplicable';
default: return 'notSet';
}
}
// CI checks + commit statuses on the PR head, normalized like getPrStatuses.
async function getPrStatuses(owner, _project, repo, prId) {
const pr = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}`);
const sha = (pr.head && pr.head.sha) || '';
if (!sha) return [];
const out = [];
try {
const cr = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commits/${sha}/check-runs`);
for (const run of (cr.check_runs || [])) {
out.push({
id: run.id,
state: _checkState(run),
genre: 'check',
name: run.name || '',
description: (run.output && run.output.title) || run.conclusion || run.status || '',
targetUrl: run.html_url || '',
creationDate: run.started_at || run.completed_at || ''
});
}
} catch {}
try {
const st = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commits/${sha}/status`);
for (const s of (st.statuses || [])) {
const map = { success: 'succeeded', failure: 'failed', error: 'error', pending: 'pending' };
out.push({
id: s.id,
state: map[String(s.state).toLowerCase()] || 'notSet',
genre: 'status',
name: s.context || '',
description: s.description || '',
targetUrl: s.target_url || '',
creationDate: s.updated_at || s.created_at || ''
});
}
} catch {}
return out.sort((a, b) => `${a.genre}${a.name}`.localeCompare(`${b.genre}${b.name}`));
}
// Fetch branch protection, distinguishing "no protection" (404 → known, empty
// requirements) from "cannot read" (403 → unknown; readiness must degrade to
// null, never assert ready — R4). Returns { known, protection }.
async function _branchProtection(owner, repo, branch) {
if (!branch) return { known: true, protection: null };
try {
const p = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/branches/${encodeURIComponent(branch)}/protection`);
return { known: true, protection: p };
} catch (e) {
const msg = String(e && e.message || '');
// 404 = branch simply not protected → a KNOWN state (no required gates).
if (/\(404\)/.test(msg) || /not found/i.test(msg)) return { known: true, protection: null };
// 403 (or anything else) = we can't tell → unknown.
return { known: false, protection: null };
}
}
// Readiness signals (R4): NEVER derived from mergeable_state alone. Computes a
// verdict from discrete signals — mergeable (retry on null), branch-protection
// required contexts, combined check states, latest non-dismissed review per
// reviewer (changes-requested / required approving count), draft, up-to-date,
// conflicts. If branch protection can't be read (403) → ready = null (unknown),
// never true. Returns the azdo-shaped { evaluations, ready, builds } so the
// server's existing validation/readiness normalization works unchanged: the
// Status-type evaluations carry statusGenre/statusName/blocking (feeding the
// required-check marking) and the non-status gates surface as policy gates.
async function getPrPolicyEvaluations(owner, _project, prId, repo) {
// Note: repo is passed in the 4th slot to keep the azdo (org,project,prId,projectId)
// arity; server dispatch supplies repo here for GitHub.
const evaluations = [];
let pr;
try { pr = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}`); }
catch { return { evaluations, ready: null, builds: [] }; }
// mergeable is computed async by GitHub — retry once on null before trusting it.
let mergeable = pr.mergeable;
if (mergeable === null || mergeable === undefined) {
await new Promise(r => setTimeout(r, 1500));
try {
const pr2 = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}`);
mergeable = pr2.mergeable;
if (pr2.mergeable_state) pr.mergeable_state = pr2.mergeable_state;
} catch {}
}
const mergeableState = String(pr.mergeable_state || '').toLowerCase();
const baseRef = (pr.base && pr.base.ref) || '';
const isDraft = !!pr.draft;
// Latest non-dismissed review per reviewer → approvals + changes-requested.
let approvals = 0, changesRequested = false;
try {
const reviews = await apiAll(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}/reviews`, { cap: 200 });
const latest = new Map();
for (const rv of reviews) {
const login = (rv.user && rv.user.login) || '';
const st = String(rv.state || '').toUpperCase();
if (!login || st === 'PENDING' || st === 'COMMENTED') continue;
latest.set(login, st); // chronological → last meaningful wins
}
for (const st of latest.values()) {
if (st === 'APPROVED') approvals++;
else if (st === 'CHANGES_REQUESTED') changesRequested = true;
}
} catch {}
// Branch protection → required contexts, required approving count, strict.
const { known: protectionKnown, protection } = await _branchProtection(owner, repo, baseRef);
const rsc = (protection && protection.required_status_checks) || null;
const requiredContexts = rsc
? (Array.isArray(rsc.contexts) && rsc.contexts.length
? rsc.contexts
: (Array.isArray(rsc.checks) ? rsc.checks.map(c => c.context).filter(Boolean) : []))
: [];
const strict = !!(rsc && rsc.strict);
const requiredApprovals = (protection && protection.required_pull_request_reviews
&& Number(protection.required_pull_request_reviews.required_approving_review_count)) || 0;
// Required status contexts → Status-type evaluations (both possible genres, so
// the server marks the matching check-run OR commit status as Required). Their
// own status value is unused by the server (only `blocking` is read).
for (const ctx of requiredContexts) {
evaluations.push({ type: 'Status', statusGenre: 'check', statusName: ctx, blocking: true, status: 'notapplicable' });
evaluations.push({ type: 'Status', statusGenre: 'status', statusName: ctx, blocking: true, status: 'notapplicable' });
}
// Required approvals gate (visible policy gate).
if (requiredApprovals > 0) {
evaluations.push({
type: 'Minimum number of reviewers',
displayName: `Required approvals (${approvals}/${requiredApprovals})`,
blocking: true,
status: approvals >= requiredApprovals ? 'approved' : 'running'
});
}
// Changes requested → blocking rejected gate.
if (changesRequested) {
evaluations.push({ type: 'Code review', displayName: 'Changes requested', blocking: true, status: 'rejected' });
}
// Branch must be up to date with base (only when protection requires it).
if (strict && mergeableState === 'behind') {
evaluations.push({ type: 'Require branches up to date', displayName: 'Branch must be up to date', blocking: true, status: 'rejected' });
}
// Merge conflicts (independent of protection).
if (mergeable === false || mergeableState === 'dirty') {
evaluations.push({ type: 'Merge conflicts', displayName: 'Merge conflicts must be resolved', blocking: true, status: 'rejected' });
}
// Required check states (for the readiness verdict): match each required
// context to an actual check-run / commit status by name.
let requiredChecksOk = true, requiredChecksKnown = true;
if (requiredContexts.length) {
let statuses = [];
try { statuses = await getPrStatuses(owner, '', repo, prId); } catch { requiredChecksKnown = false; }
const byName = new Map();
for (const s of statuses) {
const prev = byName.get(s.name);
// worst-of when a context appears as both a check and a status
const rank = { failed: 3, error: 3, pending: 2, notSet: 1, notApplicable: 0, succeeded: 0 };
if (!prev || (rank[s.state] || 0) > (rank[prev] || 0)) byName.set(s.name, s.state);
}
for (const ctx of requiredContexts) {
const st = byName.get(ctx);
if (st === undefined) { requiredChecksOk = false; continue; } // required but not yet reported
if (st !== 'succeeded' && st !== 'notApplicable') requiredChecksOk = false;
}
}
// Readiness verdict (R4). Unknown (null) when protection unreadable (403) or
// mergeability is still indeterminate after retry — never assert ready then.
let ready;
if (!protectionKnown || mergeable === null || mergeable === undefined || !requiredChecksKnown) {
ready = null;
} else {
ready = !isDraft
&& mergeable === true
&& !changesRequested
&& approvals >= requiredApprovals
&& requiredChecksOk
&& !(strict && mergeableState === 'behind');
}
return { evaluations, ready, builds: [] };
}
async function getPrChangedFiles(owner, _project, repo, prId, limit = 100) {
const files = await apiAll(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}/files`, { cap: limit });
const out = [];
for (const f of files) {
if (f.status === 'removed') continue;
if (f.filename) out.push('/' + f.filename);
if (out.length >= limit) break;
}
return out;
}
// Issues linked from a PR body (Closes #n / #n). Returns compact issue shape.
async function getPrWorkItems(owner, _project, repo, prId) {
let pr;
try { pr = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${encodeURIComponent(prId)}`); } catch { return []; }
const body = pr.body || '';
const nums = new Set();
const re = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)?\s*#(\d+)/gi;
let m; while ((m = re.exec(body))) nums.add(Number(m[1]));
const out = [];
for (const n of [...nums].slice(0, 20)) {
try {
const it = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues/${n}`);
if (it.pull_request) continue; // skip PRs masquerading as issues
out.push({ id: it.number, title: it.title || '', state: it.state || '', type: 'Issue', url: it.html_url });
} catch {}
}
return out;
}
// Issue (GitHub "work item") — repo-scoped: (owner, repo, number).
async function getWorkItem(owner, repo, number) {
const it = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues/${encodeURIComponent(number)}`);
const labels = (it.labels || []).map(l => (typeof l === 'string' ? l : l.name)).filter(Boolean);
return {
id: it.number,
title: it.title || '',
state: it.state || '',
type: it.pull_request ? 'PullRequest' : 'Issue',
assignedTo: (it.assignee && it.assignee.login) || ((it.assignees || [])[0] && it.assignees[0].login) || '',
tags: labels.join('; '),
description: it.body || '',
url: it.html_url
};
}
async function getWorkItemComments(owner, repo, number, { top = 20 } = {}) {
let all = [];
try { all = await apiAll(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues/${encodeURIComponent(number)}/comments`, { cap: 200 }); }
catch { return { count: 0, comments: [] }; }
const comments = all
.map(c => ({ id: c.id, author: (c.user && c.user.login) || '', date: c.created_at || '', text: String(c.body || '').trim() }))
.filter(c => c.text)
.sort((a, b) => String(b.date).localeCompare(String(a.date)))
.slice(0, top);
return { count: all.length, comments };
}
async function updateWorkItemState(owner, repo, number, state) {
// GitHub issues are open|closed. Map any "done/closed/resolved" to closed.
const s = /clos|done|resolv|complet/i.test(state) ? 'closed' : 'open';
const it = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues/${encodeURIComponent(number)}`, { method: 'PATCH', body: { state: s } });
return { id: it.number, title: it.title || '', state: it.state || '', url: it.html_url };
}
// Assigned issues for the current user (parity stub). The only live call site is
// the Connect/standup ADO collector, which is AzDo-only by design and never
// forge-dispatches to GitHub — so this exists solely to keep forge dispatch
// total (R12). Returns issues assigned to the authenticated user across the
// owner's repos in the window; best-effort, never throws.
async function listMyWorkItems(owner, _project, { start, end } = {}) {
try {
const me = await getCurrentUser();
const login = me && me.login;
if (!login) return [];
const parts = [`assignee:${login}`, 'is:issue'];
if (owner) parts.push(`user:${owner}`);
if (start) parts.push(`updated:>=${String(start).slice(0, 10)}`);
const q = encodeURIComponent(parts.join(' '));
const data = await api(`/search/issues?q=${q}&per_page=50`).catch(() => null);
const items = (data && data.items) || [];
return items.map(it => ({
id: it.number,
title: it.title || '',
state: it.state || '',
type: 'Issue',
assignedTo: (it.assignee && it.assignee.login) || login,
changedDate: it.updated_at || '',
createdDate: it.created_at || '',
closedDate: it.closed_at || '',
url: it.html_url
}));
} catch { return []; }
}
// Epics don't exist on GitHub — keep parity honest (AzDo-only feature).
const EPIC_TYPES = [];
async function searchEpics() {
throw new Error('Epics are an Azure DevOps concept; GitHub has no Epic work-item type.');
}
// ---- Contributors --------------------------------------------------------
async function getRepoContributors(owner, _project, repo, days = 60, top = 300) {
try {
const contrib = await apiAll(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contributors`, { cap: top });
return contrib
.map(c => ({ name: c.login || '', email: '', login: c.login || '', count: c.contributions || 0 }))
.filter(c => c.name)
.sort((a, b) => b.count - a.count);
} catch { return []; }
}
async function getFileContributors(owner, _project, repo, filePath, days = 60, top = 30) {
if (!filePath) return [];
const since = new Date(Date.now() - days * 86400000).toISOString();
try {
const commits = await apiAll(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commits?path=${encodeURIComponent(filePath.replace(/^\//, ''))}&since=${since}`, { cap: top * 5 });
const tally = new Map();
for (const c of commits) {
const login = (c.author && c.author.login) || (c.commit && c.commit.author && c.commit.author.name) || '';
const email = (c.commit && c.commit.author && c.commit.author.email) || '';
if (!login) continue;
const key = login.toLowerCase();
const cur = tally.get(key) || { name: login, email, login, count: 0 };
cur.count++; tally.set(key, cur);
}
return [...tally.values()].sort((a, b) => b.count - a.count).slice(0, top);
} catch { return []; }
}
// ---- Tree + content (for discovery / materialization) --------------------
function _blobItems(tree) {
// Normalize GitHub tree entries to the azdo-like { path:'/a/b', objectId, gitObjectType }.
return (tree || [])
.filter(i => i.type === 'blob')
.map(i => ({ path: '/' + i.path, objectId: i.sha, gitObjectType: 'blob' }));
}
async function getTree(owner, _project, repo, branch) {
const r = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/git/trees/${encodeURIComponent(branch)}?recursive=1`;
const data = await api(r);
let items = _blobItems(data.tree);
// R13: recursive tree truncates on large monorepos. Supplement with a targeted
// recursive fetch of the top-level `.github` folder so agent/plugin discovery
// still works even when the full tree was cut off.
if (data.truncated) {
const gh = (data.tree || []).find(t => t.type === 'tree' && t.path === '.github');
if (gh && gh.sha) {
try {
const sub = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/git/trees/${gh.sha}?recursive=1`);
const subItems = (sub.tree || [])
.filter(i => i.type === 'blob')
.map(i => ({ path: '/.github/' + i.path, objectId: i.sha, gitObjectType: 'blob' }));
const seen = new Set(items.map(x => x.path));
for (const it of subItems) if (!seen.has(it.path)) items.push(it);
} catch {}
}
}
return items;
}
async function getFileText(owner, _project, repo, branch, itemPath) {
const p = String(itemPath).replace(/^\/+/, '');
return api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents/${p.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(branch)}`, { accept: 'application/vnd.github.raw' });
}
async function getObjectId(owner, _project, repo, branch, itemPath) {
const p = String(itemPath).replace(/^\/+/, '');
try {
const r = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents/${p.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(branch)}`);
return r.sha || null;
} catch { return null; }
}
// ---- Discovery (agents/plugins under any .github folder) -----------------
function parseFrontmatter(content) {
const fm = content.replace(/\r\n/g, '\n').match(/^---\s*\n([\s\S]*?)\n---/);
if (!fm) return {};
const block = fm[1];
const name = (block.match(/^name:\s*['"]?([^'"\n]+)/m) || [])[1];
const description = (block.match(/^description:\s*['"]?([^'"\n]+)/m) || [])[1];
return { name: name && name.trim(), description: description && description.trim() };
}
function titleCase(id) {
return String(id || '').split(/[-_\s]+/).filter(Boolean).map(w => w[0].toUpperCase() + w.slice(1)).join(' ');
}
const AGENT_RE = /(^|\/)\.github\/agents\/([^/]+)\.md$/i;
const PLUGIN_JSON_RE = /(^|\/)\.github\/plugin\/([^/]+)\/plugin\.json$/i;
function pluginSignature(files) {
const list = Array.isArray(files) ? files : [];
if (!list.length) return null;
const lines = list.map(f => `${f.path}:${f.objectId || ''}`).sort().join('\n');
return crypto.createHash('sha1').update(lines).digest('hex');
}
async function discover(owner, _project, repo, branch) {
const tree = await getTree(owner, '', repo, branch);
const discovered = [];
for (const it of tree.filter(i => AGENT_RE.test(i.path))) {
const p = it.path.replace(/^\//, '');
let meta = {};
try { meta = parseFrontmatter(await getFileText(owner, '', repo, branch, it.path)); } catch {}
const baseName = path.basename(p).replace(/\.md$/i, '');
const id = (meta.name || baseName).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
discovered.push({ kind: 'agent', id, agentRef: meta.name || baseName, name: meta.name || baseName, displayName: titleCase(meta.name || baseName), description: meta.description || '', path: p, objectId: it.objectId });
}
for (const it of tree.filter(i => PLUGIN_JSON_RE.test(i.path))) {
const pjPath = it.path.replace(/^\//, '');
const pluginRoot = pjPath.replace(/\/plugin\.json$/i, '');
let pj = {};
try { pj = JSON.parse(await getFileText(owner, '', repo, branch, it.path)); } catch {}
const folderName = path.basename(pluginRoot);
const id = (pj.name || folderName).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
const files = tree.filter(f => { const fp = f.path.replace(/^\//, ''); return fp === pluginRoot || fp.startsWith(pluginRoot + '/'); }).map(f => ({ path: f.path.replace(/^\//, ''), objectId: f.objectId }));
const hasMcp = files.some(f => /(^|\/)\.mcp\.json$/i.test(f.path));
discovered.push({ kind: 'plugin', id, name: pj.name || folderName, displayName: titleCase(pj.name || folderName), description: pj.description || '', version: pj.version || '', path: pluginRoot, objectId: pluginSignature(files) || it.objectId, pluginJsonObjectId: it.objectId, hasMcp, files });
}
return discovered.sort((a, b) => (a.displayName || a.id).localeCompare(b.displayName || b.id));
}
// ---- Materialization -----------------------------------------------------
function sanitize(v) { return String(v || '').replace(/[^A-Za-z0-9._-]+/g, '_'); }
function repoRoot(owner, _project, repo, branch) {
return path.join(GITHUB_STORE, sanitize(owner), sanitize(repo), sanitize(branch));
}
async function writeFileFromRepo(owner, repo, branch, root, relPath) {
const content = await getFileText(owner, '', repo, branch, '/' + relPath.replace(/^\//, ''));
const dest = path.join(root, relPath.replace(/\//g, path.sep));
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.writeFileSync(dest, content);
return dest;
}
async function materializeAgent(owner, _project, repo, branch, agentPath) {
const root = repoRoot(owner, '', repo, branch);
const rel = agentPath.replace(/^\//, '');
await writeFileFromRepo(owner, repo, branch, root, rel);
const ghIdx = rel.toLowerCase().indexOf('.github/');
const cwdRel = ghIdx > 0 ? rel.slice(0, ghIdx).replace(/\/$/, '') : '';
const cwd = cwdRel ? path.join(root, cwdRel.replace(/\//g, path.sep)) : root;
const base = cwdRel ? cwdRel.replace(/\/$/, '') + '/' : '';
let mcpConfig = null, skillCount = 0;
try {
const tree = await getTree(owner, '', repo, branch);
const inBase = p => (base ? p.startsWith(base) : true);
const wanted = [];
for (const it of tree) {
const p = it.path.replace(/^\//, '');
if (!inBase(p)) continue;
const sub = base ? p.slice(base.length) : p;
if (/^\.mcp\.json$/i.test(sub) || /^\.github\/\.mcp\.json$/i.test(sub)) wanted.push(p);
else if (/^(\.github\/)?skills\//i.test(sub)) wanted.push(p);
}
for (const w of wanted) { await writeFileFromRepo(owner, repo, branch, root, w); if (/(^|\/)SKILL\.md$/i.test(w)) skillCount++; }
const mcpAbs = path.join(cwd, '.mcp.json');
if (fs.existsSync(mcpAbs)) mcpConfig = mcpAbs;
} catch {}
return { cwd, agentMdPath: path.join(root, rel.replace(/\//g, path.sep)), mcpConfig, skillCount };
}
async function materializePlugin(owner, _project, repo, branch, item) {
const root = repoRoot(owner, '', repo, branch);
const pluginDir = path.join(root, item.path.replace(/\//g, path.sep));
try { if (fs.existsSync(pluginDir)) fs.rmSync(pluginDir, { recursive: true, force: true }); } catch {}
const files = item.files && item.files.length
? item.files
: (await getTree(owner, '', repo, branch))
.filter(f => { const fp = f.path.replace(/^\//, ''); return fp === item.path || fp.startsWith(item.path + '/'); })
.map(f => ({ path: f.path.replace(/^\//, '') }));
for (const f of files) await writeFileFromRepo(owner, repo, branch, root, f.path);
const mcpAbs = path.join(pluginDir, '.mcp.json');
return { pluginDir, mcpConfig: fs.existsSync(mcpAbs) ? mcpAbs : null };
}
// ---- Write helpers (PR create / push) ------------------------------------
// Create a GitHub issue. `labels` is an optional string[]. Returns { number, url }.
async function createIssue(owner, repo, { title, body, labels } = {}) {
const payload = { title: title || 'Feedback', body: body || '' };
if (Array.isArray(labels) && labels.length) payload.labels = labels;
const R = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues`;
let d;
try {
d = await api(R, { method: 'POST', body: payload });
} catch (e) {
// A non-existent label yields 422 — retry once without labels so feedback
// still reaches GitHub rather than being lost.
if (payload.labels && /422|label/i.test(e && e.message || '')) {
const { labels: _drop, ...noLabels } = payload;
d = await api(R, { method: 'POST', body: noLabels });
} else { throw e; }
}
return { number: d.number, url: d.html_url, webUrl: d.html_url };
}
// Best-effort: make sure a label exists so createIssue can apply it. Swallows
// the "already exists" 422 and any other error (labels are non-critical).
async function ensureLabel(owner, repo, name, color = '5319e7', description = '') {
try {
await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/labels`, {
method: 'POST', body: { name, color, description }
});
} catch { /* already exists or insufficient scope — ignore */ }
}
// Upload a binary image (base64, no data: prefix) to `branch` at `repoPath`,
// creating the branch from the repo's default branch if it doesn't exist yet.
// Returns a raw.githubusercontent.com URL that renders inline in issue markdown.
async function uploadImageToBranch(owner, repo, { branch, path: repoPath, base64, message } = {}) {
const R = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
// Ensure the destination branch exists (branch off the default branch tip).
let sha = await getRefObjectId(owner, null, repo, branch);
if (!sha) {
const meta = await getRepo(owner, null, repo);
const baseSha = await getRefObjectId(owner, null, repo, meta.defaultBranch);
if (!baseSha) throw new Error('Could not resolve a base branch to create ' + branch);
try {
await api(`${R}/git/refs`, { method: 'POST', body: { ref: `refs/heads/${branch}`, sha: baseSha } });
} catch (e) {
// Lost a race, or it exists now — tolerate "Reference already exists".
if (!/already exists|422/i.test(e && e.message || '')) throw e;
}
}
const cleanPath = String(repoPath).replace(/^\/+/, '');
const enc = cleanPath.split('/').map(encodeURIComponent).join('/');
const d = await api(`${R}/contents/${enc}`, {
method: 'PUT',
body: { message: message || 'Add feedback screenshot', branch, content: base64 }
});
const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${cleanPath}`;
return { url: raw, downloadUrl: (d.content && d.content.download_url) || raw };
}
async function createPullRequest(owner, _project, repo, { sourceBranch, targetBranch, title, description } = {}) {
const d = await api(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls`, {
method: 'POST',
body: { title: title || 'Update', head: sourceBranch, base: targetBranch, body: description || '' }
});
return { id: d.number, url: d.html_url, webUrl: d.html_url };
}
// Commit a set of file changes onto a new branch via the git data API.
// changes: [{ path, content }]. Creates newBranch from baseBranch's tip.
async function pushFiles(owner, _project, repo, { baseBranch, newBranch, changes, commitMessage } = {}) {
const R = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
const baseRef = await api(`${R}/git/ref/heads/${encodeURIComponent(baseBranch)}`);