-
-
Notifications
You must be signed in to change notification settings - Fork 859
Expand file tree
/
Copy pathaction-issue-triage-automation.yml
More file actions
2304 lines (2093 loc) · 101 KB
/
action-issue-triage-automation.yml
File metadata and controls
2304 lines (2093 loc) · 101 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
name: Issue Triage & Automation
on:
workflow_dispatch:
inputs:
issue_state:
description: Issue state to backfill
required: true
default: all
type: choice
options:
- all
- open
- closed
limit:
description: Max issues to process (0 = all)
required: true
default: "0"
type: string
ai_game_fallback:
description: Use AI only when deterministic game mapping finds no game
required: true
default: "false"
type: choice
options:
- "false"
- "true"
issues:
types:
- opened
- edited
- reopened
- labeled
- unlabeled
- assigned
- unassigned
- milestoned
- demilestoned
- transferred
- pinned
- unpinned
issue_comment:
types:
- created
- edited
- deleted
pull_request:
types:
- opened
- edited
- synchronize
- reopened
push:
branches:
- master
- develop
paths:
- "lgsm/data/serverlist.csv"
permissions:
issues: write
pull-requests: write
contents: read
models: read
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
issue-regex-labeler:
if: github.repository_owner == 'GameServerManagers' && github.event_name == 'issues' && (github.event.action == 'opened' || github.event.action == 'edited')
runs-on: ubuntu-latest
steps:
- name: Issue Labeler
uses: github/issue-labeler@v3.4
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
configuration-path: .github/labeler.yml
enable-versioned-regex: 0
include-title: 1
sync-labels: 0
issue-ai-maintenance:
if: github.repository_owner == 'GameServerManagers' && (github.event_name == 'issues' || github.event_name == 'issue_comment')
runs-on: ubuntu-latest
steps:
- name: Reconcile issue labels and AI triage
uses: actions/github-script@v9
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
script: |
const { execFileSync } = require('node:child_process');
const owner = context.repo.owner;
const repo = context.repo.repo;
const eventName = context.eventName;
const action = context.payload.action;
const issueNumber = context.payload.issue?.number;
const AI_MARKER = '<!-- ai-triage -->';
if (!issueNumber) {
console.log('No issue number found in payload.');
return;
}
// Avoid bot-to-bot relabel loops on label events.
if (
eventName === 'issues' &&
['labeled', 'unlabeled'].includes(action) &&
context.actor === 'github-actions[bot]'
) {
console.log('Skipping self-triggered label event.');
return;
}
const issueResp = await github.rest.issues.get({
owner,
repo,
issue_number: issueNumber,
});
const issue = issueResp.data;
const title = issue.title || '';
const body = issue.body || '';
const existingLabels = new Set((issue.labels || []).map((l) => l.name).filter(Boolean));
function parseTriageResponse(raw) {
const input = (raw || '').trim();
if (!input) return {};
const candidates = [input];
const fenced = input.match(/```(?:json)?\s*([\s\S]*?)```/i);
if (fenced?.[1]) candidates.push(fenced[1].trim());
const firstBrace = input.indexOf('{');
const lastBrace = input.lastIndexOf('}');
if (firstBrace !== -1 && lastBrace > firstBrace) {
candidates.push(input.slice(firstBrace, lastBrace + 1));
}
for (const candidate of candidates) {
try {
return JSON.parse(candidate);
} catch (_err) {
// Continue trying fallbacks.
}
}
return {};
}
function extractSection(sectionName) {
const escaped = sectionName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`### ${escaped}\\n\\n([\\s\\S]*?)(\\n### |$)`, 'i');
return (body.match(re)?.[1] || '').trim();
}
function normalizeName(value) {
return (value || '')
.toLowerCase()
.replace(/[’'`]/g, '')
.replace(/[^a-z0-9]+/g, ' ')
.trim();
}
function parseGameCandidates(gameField) {
if (!gameField || /^_?no response_?$/i.test(gameField)) {
return [];
}
return gameField
.replace(/\(.*?\)/g, ' ')
.split(/\n|,|\s+&\s+|\s+and\s+|\//i)
.map((v) => v.trim())
.filter(Boolean);
}
function findGamesFromText(text, gameAliasToLabel, gameAliasToScript) {
const labels = new Set();
const scripts = new Set();
const normalizedText = normalizeName(text);
if (!normalizedText) return { labels, scripts };
const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const aliases = [];
for (const [alias, label] of gameAliasToLabel.entries()) {
if (alias.length < 3) continue;
aliases.push({ alias, label, script: gameAliasToScript.get(alias) || null });
}
// Prefer longer aliases first so "killing floor 2" does not also match "killing floor".
aliases.sort((a, b) => b.alias.length - a.alias.length);
const usedRanges = [];
const isOverlapping = (start, end) =>
usedRanges.some((range) => start < range.end && end > range.start);
for (const entry of aliases) {
const pattern = new RegExp(`\\b${escapeRegex(entry.alias).replace(/\\ /g, '\\s+')}\\b`, 'g');
let match;
while ((match = pattern.exec(normalizedText)) !== null) {
const start = match.index;
const end = start + match[0].length;
if (isOverlapping(start, end)) continue;
labels.add(entry.label);
if (entry.script) scripts.add(entry.script);
usedRanges.push({ start, end });
}
}
return { labels, scripts };
}
function hasAliasHitForLabel(text, targetLabel, gameAliasToLabel) {
const normalizedText = normalizeName(text);
if (!normalizedText || !targetLabel) return false;
const paddedText = ` ${normalizedText} `;
for (const [alias, label] of gameAliasToLabel.entries()) {
if (label !== targetLabel) continue;
if (alias.length < 3) continue;
if (paddedText.includes(` ${alias} `)) return true;
// Allow obvious joined-word variants for multi-token aliases
// (e.g., "counter strike 1 6" matching "counterstrike 1.6").
const aliasTokens = alias.split(/\s+/).filter(Boolean);
if (aliasTokens.length > 1) {
const escapedTokens = aliasTokens.map((token) =>
token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
);
const flexibleAliasPattern = new RegExp(`\\b${escapedTokens.join('\\s*')}\\b`);
if (flexibleAliasPattern.test(normalizedText)) return true;
}
}
return false;
}
function runSteamCmdLinuxCheck(appId) {
if (!appId) {
return { status: 'skipped', reason: 'No Steam AppID provided.' };
}
const image = 'gameservermanagers/steamcmd:latest';
const args = [
'run',
'--rm',
'-e',
'PUID=1001',
'-e',
'PGID=1001',
image,
'+@ShutdownOnFailedCommand',
'1',
'+@NoPromptForPassword',
'1',
'+login',
'anonymous',
'+app_info_update',
'1',
'+app_info_print',
String(appId),
'+quit',
];
try {
const output = execFileSync('docker', args, {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
timeout: 120000,
maxBuffer: 10 * 1024 * 1024,
});
const normalized = output.toLowerCase();
const linuxSignals = [
/"oslist"\s+"linux"/i,
/"oslist"\s+"linux,windows"/i,
/"oslist"\s+"windows,linux"/i,
/"platforms"[\s\S]*?"linux"\s+"1"/i,
/linux32/i,
/linux64/i,
];
const windowsOnlySignals = [
/"oslist"\s+"windows"/i,
/"platforms"[\s\S]*?"windows"\s+"1"/i,
];
const hasLinuxSignal = linuxSignals.some((re) => re.test(normalized));
const hasWindowsOnlySignal =
!hasLinuxSignal && windowsOnlySignals.some((re) => re.test(normalized));
if (hasLinuxSignal) {
return {
status: 'linux',
reason: `SteamCMD app_info contains Linux platform/depot metadata for AppID ${appId}.`,
};
}
if (hasWindowsOnlySignal) {
return {
status: 'windows-only',
reason: `SteamCMD app_info contains Windows-only platform metadata for AppID ${appId}.`,
};
}
return {
status: 'unknown',
reason: `SteamCMD app_info returned no clear Linux server metadata for AppID ${appId}.`,
};
} catch (err) {
const stderr = err.stderr ? String(err.stderr).trim() : '';
const stdout = err.stdout ? String(err.stdout).trim() : '';
const message = stderr || stdout || err.message;
return {
status: 'error',
reason: `SteamCMD lookup failed: ${message}`,
};
}
}
function parseServerlistCsv(csvText) {
const rows = [];
const lines = (csvText || '').split(/\r?\n/);
for (let i = 1; i < lines.length; i += 1) {
const line = lines[i]?.trim();
if (!line) continue;
const parts = line.split(',');
if (parts.length < 3) continue;
rows.push({
shortname: parts[0].trim(),
gameservername: parts[1].trim(),
gamename: parts[2].trim(),
});
}
return rows;
}
function inferTypeFromTitle(issueTitle) {
if (/^\[bug\]/i.test(issueTitle)) return 'type: bug';
if (/\bserver\s+request\b/i.test(issueTitle)) return 'type: game server request';
const hasBracketPrefix = /^\[[^\]]+\]/.test(issueTitle || '');
const isServerCreation =
/\bserver\s+creation\b/i.test(issueTitle) ||
(hasBracketPrefix && /\bcreation\b/i.test(issueTitle));
const isServerSupportRequest =
/\bserver\s+support\b/i.test(issueTitle) ||
(/\bsupport\s+for\b/i.test(issueTitle) && /\bserver\b/i.test(issueTitle));
if (isServerCreation || isServerSupportRequest) return 'type: game server request';
if (/^\[feature\]/i.test(issueTitle)) return 'type: feature';
if (/^\[server request\]/i.test(issueTitle)) return 'type: game server request';
if (/^\[docs?\]/i.test(issueTitle)) return 'type: docs';
return null;
}
function inferDesiredType(issueTitle, labelNames) {
const titleType = inferTypeFromTitle(issueTitle);
if (titleType) return titleType;
// Prefer server requests over generic feature when both labels exist.
if (labelNames.has('type: game server request')) return 'type: game server request';
for (const label of [
'type: bug',
'type: feature',
'type: game server request',
'type: docs',
]) {
if (labelNames.has(label)) return label;
}
return null;
}
function inferIssueTypeNameFromDesiredType(typeLabel) {
if (typeLabel === 'type: bug') return 'Bug';
if (typeLabel === 'type: feature') return 'Feature';
if (typeLabel === 'type: game server request') return 'Server Request';
if (typeLabel === 'type: docs') return 'Task';
return null;
}
function parseCommandSelections(sectionValue) {
const selected = new Set();
const re = /command:\s*([a-z-]+)/gi;
let m;
while ((m = re.exec(sectionValue || '')) !== null) {
let value = m[1].toLowerCase();
if (value.startsWith('mods-')) value = 'mods';
if (value === 'auto-update') value = 'update';
selected.add(`command: ${value}`);
}
return selected;
}
function parseDistroSelections(sectionValue) {
const text = sectionValue || '';
const selected = new Set();
if (/\bUbuntu\b/i.test(text)) selected.add('distro: Ubuntu');
if (/\bDebian\b/i.test(text)) selected.add('distro: Debian');
if (/\bAlmaLinux\b/i.test(text)) selected.add('distro: AlmaLinux');
if (/\bRocky\b/i.test(text)) selected.add('distro: Rocky Linux');
if (/\bCentOS\b/i.test(text)) selected.add('distro: CentOS');
if (/\bFedora\b/i.test(text)) selected.add('distro: Fedora');
if (/\bopenSUSE\b/i.test(text)) selected.add('distro: openSUSE');
if (/\bArch Linux\b/i.test(text)) selected.add('distro: Arch Linux');
if (/\bSlackware\b/i.test(text)) selected.add('distro: Slackware');
return selected;
}
const repoLabels = await github.paginate(github.rest.issues.listLabelsForRepo, {
owner,
repo,
per_page: 100,
});
const gameLabelByNormalized = new Map();
for (const label of repoLabels) {
if (!label.name.startsWith('game: ')) continue;
gameLabelByNormalized.set(normalizeName(label.name.slice(6)), label.name);
}
const existingEngineLabels = new Set(
repoLabels.map((label) => label.name).filter((name) => name.startsWith('engine: '))
);
const gameAliasToLabel = new Map();
const gameAliasToScript = new Map();
const engineByScript = new Map();
for (const [normalizedGameName, label] of gameLabelByNormalized.entries()) {
gameAliasToLabel.set(normalizedGameName, label);
}
try {
const serverlistContent = await github.rest.repos.getContent({
owner,
repo,
path: 'lgsm/data/serverlist.csv',
});
const encoded = serverlistContent.data?.content || '';
const csvText = Buffer.from(encoded, 'base64').toString('utf8');
const serverRows = parseServerlistCsv(csvText);
for (const row of serverRows) {
const canonicalLabel = gameLabelByNormalized.get(normalizeName(row.gamename));
if (!canonicalLabel) continue;
for (const alias of [row.shortname, row.gameservername, row.gamename]) {
const key = normalizeName(alias);
if (!key) continue;
gameAliasToLabel.set(key, canonicalLabel);
gameAliasToScript.set(key, row.gameservername);
}
}
} catch (err) {
console.log(`Could not load serverlist aliases: ${err.message}`);
}
async function ensureEngineLabel(engineLabel) {
if (existingEngineLabels.has(engineLabel)) return;
try {
await github.rest.issues.createLabel({
owner,
repo,
name: engineLabel,
color: '000000',
description: `Issues related to ${engineLabel.slice(8)} engine`,
});
existingEngineLabels.add(engineLabel);
} catch (err) {
if (err.status === 422) {
existingEngineLabels.add(engineLabel);
return;
}
console.log(`Could not create engine label "${engineLabel}": ${err.message}`);
}
}
async function getEngineForScript(scriptName) {
if (!scriptName) return null;
if (engineByScript.has(scriptName)) {
return engineByScript.get(scriptName);
}
try {
const cfgContent = await github.rest.repos.getContent({
owner,
repo,
path: `lgsm/config-default/config-lgsm/${scriptName}/_default.cfg`,
});
const encoded = cfgContent.data?.content || '';
const cfgText = Buffer.from(encoded, 'base64').toString('utf8');
const engine = cfgText.match(/^engine="([^"]+)"/m)?.[1] || null;
engineByScript.set(scriptName, engine);
return engine;
} catch (err) {
console.log(`Could not detect engine for ${scriptName}: ${err.message}`);
engineByScript.set(scriptName, null);
return null;
}
}
const labelsToAdd = new Set();
const labelsToRemove = new Set();
// Deterministic reconciliation on every interaction.
const desiredType = inferDesiredType(title, existingLabels);
if (desiredType) {
labelsToAdd.add(desiredType);
for (const label of existingLabels) {
if (label.startsWith('type: ') && label !== desiredType) {
labelsToRemove.add(label);
}
}
const desiredIssueTypeName = inferIssueTypeNameFromDesiredType(desiredType);
if (desiredIssueTypeName) {
try {
const issueTypeData = await github.graphql(
`query($owner:String!,$repo:String!,$number:Int!){
repository(owner:$owner,name:$repo){
issueTypes(first:20){ nodes { id name } }
issue(number:$number){ id issueType { id name } }
}
}`,
{ owner, repo, number: issueNumber }
);
const issueNode = issueTypeData.repository?.issue;
const issueTypes = issueTypeData.repository?.issueTypes?.nodes || [];
const desiredIssueType = issueTypes.find((t) => t.name === desiredIssueTypeName);
if (issueNode?.id && desiredIssueType?.id && issueNode.issueType?.id !== desiredIssueType.id) {
await github.graphql(
`mutation($id:ID!,$issueTypeId:ID!){
updateIssue(input:{id:$id,issueTypeId:$issueTypeId}){
issue { id number issueType { id name } }
}
}`,
{ id: issueNode.id, issueTypeId: desiredIssueType.id }
);
}
} catch (err) {
console.log(`Could not sync Issue Type: ${err.message}`);
}
}
}
const commandSection = extractSection('Command');
const desiredCommands = parseCommandSelections(commandSection);
if (desiredCommands.size > 0) {
for (const label of desiredCommands) labelsToAdd.add(label);
for (const label of existingLabels) {
if (label.startsWith('command: ') && !desiredCommands.has(label)) {
labelsToRemove.add(label);
}
}
}
const distroSection = extractSection('Linux distro');
const desiredDistros = parseDistroSelections(distroSection);
if (desiredDistros.size > 0) {
for (const label of desiredDistros) labelsToAdd.add(label);
for (const label of existingLabels) {
if (label.startsWith('distro: ') && !desiredDistros.has(label)) {
labelsToRemove.add(label);
}
}
}
const tmuxContextPattern = /\b(tmuxception|check_tmuxception)\b/i;
if (existingLabels.has('info: tmux') && !tmuxContextPattern.test(`${title}\n${body}`)) {
labelsToRemove.add('info: tmux');
}
const desiredGames = new Set();
const desiredServerScripts = new Set();
// 'Game server' is the section name in server_request.yml; 'Game' is used in bug_report.yml.
const gameField = extractSection('Game server') || extractSection('Game');
const gameCandidates = parseGameCandidates(gameField);
const hasStructuredGameSelection = gameCandidates.length > 0;
for (const candidate of gameCandidates) {
const normalizedCandidate = normalizeName(candidate);
const mapped = gameAliasToLabel.get(normalizedCandidate) || gameLabelByNormalized.get(normalizedCandidate);
if (mapped) desiredGames.add(mapped);
const mappedScript = gameAliasToScript.get(normalizedCandidate);
if (mappedScript) desiredServerScripts.add(mappedScript);
}
// Legacy issues often have no form section; fall back to deterministic text matching.
// If a structured Game field exists but does not map, do not guess from free text.
if (desiredGames.size === 0 && !hasStructuredGameSelection) {
const fromText = findGamesFromText(`${title}\n${body}`, gameAliasToLabel, gameAliasToScript);
for (const label of fromText.labels) desiredGames.add(label);
for (const scriptName of fromText.scripts) desiredServerScripts.add(scriptName);
}
// AI advisory is only needed on issue opened/edited.
let triage = {};
let ranAi = false;
const shouldRunAi = eventName === 'issues' && ['opened', 'edited'].includes(action);
const shouldRunLinuxSupportCheck =
eventName === 'issues' &&
['opened', 'edited', 'reopened', 'labeled', 'unlabeled'].includes(action);
if (shouldRunAi) {
ranAi = true;
const isShortBody = body.trim().length < 80;
if (isShortBody) {
labelsToAdd.add('needs: more info');
} else {
try {
const res = await fetch(
`https://models.github.ai/orgs/${owner}/inference/chat/completions`,
{
method: 'POST',
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
'X-GitHub-Api-Version': '2026-03-10',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai/gpt-4.1-mini',
temperature: 0.1,
max_tokens: 400,
messages: [
{
role: 'system',
content:
'You are a triage assistant for LinuxGSM, an open-source Linux game server manager. ' +
'Return only JSON. Analyze issue quality, suggest missing info, detect game names, and suggest contextual labels ' +
'only when highly certain. Never set type: docs just because docs links are mentioned.',
},
{
role: 'user',
content:
`Title: ${title}\n\nBody:\n${body.slice(0, 3000)}\n\n` +
'Return JSON schema:\n' +
'{\n' +
' "quality": "good" | "ok" | "poor",\n' +
' "missing_info": ["list of specific missing fields"],\n' +
' "detected_game": "canonical game name if one is mentioned, or null",\n' +
' "game_confidence": "high" | "medium" | "low" | null,\n' +
' "context_labels": ["labels"],\n' +
' "context_confidence": "high" | "medium" | "low" | null,\n' +
' "game_note": "string",\n' +
' "comment": "string"\n' +
'}',
},
],
}),
}
);
if (res.ok) {
const data = await res.json();
const raw = data.choices?.[0]?.message?.content || '{}';
triage = parseTriageResponse(raw);
} else {
console.log(`GitHub Models returned ${res.status} - skipping AI triage.`);
}
} catch (err) {
console.log('AI triage skipped:', err.message);
}
}
}
const allowedContextLabels = new Set([
'type: docs',
'info: docs',
'info: dependency',
'info: docker',
'info: email',
'info: query',
'info: steamcmd',
'info: systemd',
'info: website',
'info: alerts',
]);
const isPoor = triage?.quality === 'poor';
const missing = Array.isArray(triage?.missing_info) ? triage.missing_info : [];
const hasIssues = isPoor || missing.length > 0;
// Fallback to AI-detected game only when no structured Game field exists.
const detectedGame = triage?.detected_game;
const gameConfidence = triage?.game_confidence;
if (desiredGames.size === 0 && !hasStructuredGameSelection && detectedGame && gameConfidence === 'high') {
const normalizedDetectedGame = normalizeName(detectedGame);
const mapped = gameLabelByNormalized.get(normalizedDetectedGame);
if (mapped) {
desiredGames.add(mapped);
}
const mappedScript = gameAliasToScript.get(normalizedDetectedGame);
if (mappedScript) desiredServerScripts.add(mappedScript);
}
// Resolve server scripts from canonical game labels when only labels were mapped.
for (const gameLabel of desiredGames) {
const gameName = gameLabel.slice(6);
const mappedScript = gameAliasToScript.get(normalizeName(gameName));
if (mappedScript) desiredServerScripts.add(mappedScript);
}
const desiredEngineLabels = new Set();
for (const scriptName of desiredServerScripts) {
const engine = await getEngineForScript(scriptName);
if (!engine) continue;
const engineLabel = `engine: ${engine}`;
await ensureEngineLabel(engineLabel);
desiredEngineLabels.add(engineLabel);
}
if (desiredEngineLabels.size > 0) {
for (const label of desiredEngineLabels) labelsToAdd.add(label);
for (const label of existingLabels) {
if (label.startsWith('engine: ') && !desiredEngineLabels.has(label)) {
labelsToRemove.add(label);
}
}
}
if (desiredGames.size > 0) {
for (const label of desiredGames) labelsToAdd.add(label);
if (hasStructuredGameSelection) {
for (const label of existingLabels) {
if (label.startsWith('game: ') && !desiredGames.has(label)) {
labelsToRemove.add(label);
}
}
} else {
// For legacy issues without structured game selection, only prune stale
// broader labels when a more specific inferred game label exists.
const desiredGameNamesNormalized = new Set(
[...desiredGames].map((label) => normalizeName(label.slice(6)))
);
for (const label of existingLabels) {
if (!label.startsWith('game: ') || desiredGames.has(label)) continue;
const existingGameName = normalizeName(label.slice(6));
const isBroaderOverlap = [...desiredGameNamesNormalized].some(
(desiredName) => desiredName !== existingGameName && desiredName.startsWith(`${existingGameName} `)
);
if (isBroaderOverlap) {
labelsToRemove.add(label);
}
}
}
}
if (triage?.context_confidence === 'high') {
const contextLabels = Array.isArray(triage.context_labels) ? triage.context_labels : [];
for (const label of contextLabels) {
if (!allowedContextLabels.has(label)) continue;
if (
label === 'type: docs' &&
(existingLabels.has('type: game server request') || desiredType === 'type: game server request')
) {
continue;
}
labelsToAdd.add(label);
}
}
if (ranAi && hasIssues) {
labelsToAdd.add('needs: more info');
}
if (ranAi && !hasIssues && existingLabels.has('needs: more info')) {
labelsToRemove.add('needs: more info');
}
// Avoid pointless API calls.
const finalAdds = [...labelsToAdd].filter((label) => !existingLabels.has(label));
const finalRemoves = [...labelsToRemove].filter((label) => existingLabels.has(label));
for (const label of finalRemoves) {
try {
await github.rest.issues.removeLabel({
owner,
repo,
issue_number: issueNumber,
name: label,
});
console.log(`Removed label: ${label}`);
} catch (err) {
console.log(`Could not remove label "${label}": ${err.message}`);
}
}
for (const label of finalAdds) {
try {
await github.rest.issues.addLabels({
owner,
repo,
issue_number: issueNumber,
labels: [label],
});
console.log(`Added label: ${label}`);
} catch (err) {
console.log(`Could not add label "${label}": ${err.message}`);
}
}
// Post AI comment only for opened/edited issues when useful.
if (ranAi) {
const gameNote = triage?.game_note || '';
const reporterComment = triage?.comment || '';
if (hasIssues || gameNote) {
const missingBlock = missing.length > 0
? `\n\n**Missing information:**\n${missing.map((m) => `- ${m}`).join('\n')}`
: '';
const gameBlock = gameNote ? `\n\n**Game name note:** ${gameNote}` : '';
const triageCommentBody =
`${AI_MARKER}\n` +
`Thanks for opening this issue!\n\n` +
`${reporterComment}` +
`${missingBlock}` +
`${gameBlock}\n\n` +
`_This note was generated automatically by AI triage and may not be perfect. ` +
`A maintainer will review shortly._`;
try {
const comments = await github.paginate(github.rest.issues.listComments, {
owner,
repo,
issue_number: issueNumber,
per_page: 100,
});
const existingAiComment = [...comments].reverse().find(
(comment) => comment.user?.type === 'Bot' && comment.body?.includes(AI_MARKER)
);
if (existingAiComment) {
await github.rest.issues.updateComment({
owner,
repo,
comment_id: existingAiComment.id,
body: triageCommentBody,
});
} else {
await github.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: triageCommentBody,
});
}
} catch (err) {
console.log('Could not post comment:', err.message);
}
}
}
// === Linux support verification for server request issues ===
// Runs only on opened/edited events to avoid reprocessing every label change.
const isServerRequest =
desiredType === 'type: game server request' ||
existingLabels.has('type: game server request') ||
/\[server request\]/i.test(title);
if (isServerRequest && shouldRunLinuxSupportCheck) {
const officialDocsSection = extractSection('Official dedicated server documentation');
const linuxBinaryProofSection = extractSection('Linux binary proof');
const guidesSection = extractSection('Guides');
const steamSection = extractSection('Steam').trim();
const isSteamNo = /^no$/i.test(steamSection);
const isSteamYes = /^yes$/i.test(steamSection);
const steamAppIdRaw = extractSection('Steam appid').trim();
const steamAppId = /^\d+$/.test(steamAppIdRaw) ? steamAppIdRaw : null;
const supportEvidenceText = [officialDocsSection, linuxBinaryProofSection, guidesSection]
.join('\n')
.trim();
// Deterministic textual checks to avoid trusting checkbox-only reports.
const windowsOnlyPatterns = [
/\bwindows\s+only\b/i,
/\bonly\s+windows\b/i,
/\bno\s+linux\s+support\b/i,
/\blinux\s+not\s+supported\b/i,
/\bdoes\s+not\s+support\s+linux\b/i,
];
const wineRequiredPatterns = [
/\brequires?\s+wine\b/i,
/\buse\s+wine\b/i,
/\brun\s+with\s+wine\b/i,
/\bvia\s+wine\b/i,
/\bproton\b/i,
];
const linuxEvidencePatterns = [
/\blinux\b/i,
/\bubuntu\b/i,
/\bdebian\b/i,
/\blinuxgsm\b/i,
/\bsteamcmd\s*\+app_update\b/i,
];
const windowsBinaryHint = /\b\.exe\b/i.test(supportEvidenceText);
const deterministicWindowsOnly = windowsOnlyPatterns.some((re) => re.test(supportEvidenceText));
const deterministicWineRequired = wineRequiredPatterns.some((re) => re.test(supportEvidenceText));
const hasLinuxEvidence = linuxEvidencePatterns.some((re) => re.test(supportEvidenceText));
// Steam store API is client-app metadata only. It is kept for comment context,
// but it is NOT used to determine dedicated server Linux support.
let steamLinuxSupport = null; // true=yes, false=no, null=unknown/informational-only
let steamAppIsServerTool = false; // success:false from store API = likely server-tool AppID
let steamCmdAssessment = null;
if (steamAppId) {
try {
const steamRes = await fetch(
`https://store.steampowered.com/api/appdetails?appids=${steamAppId}&filters=platforms`,
{ signal: AbortSignal.timeout(8000) }
);
if (steamRes.ok) {
const steamData = await steamRes.json();
const appData = steamData[steamAppId];
if (appData?.success && appData?.data?.platforms) {
steamLinuxSupport = appData.data.platforms.linux === true;
console.log(`Steam AppID ${steamAppId} linux=${steamLinuxSupport}`);
} else if (appData?.success === false) {
// Dedicated server tool AppIDs have no store page — inconclusive, not negative.
steamAppIsServerTool = true;
console.log(`Steam AppID ${steamAppId} has no store page (likely a server-tool AppID)`);
}
}
} catch (err) {
console.log(`Steam API check failed: ${err.message}`);
}
steamCmdAssessment = runSteamCmdLinuxCheck(steamAppId);
console.log(`SteamCMD assessment: ${JSON.stringify(steamCmdAssessment)}`);
}
// AI analysis of official docs/guides for Linux evidence.
let aiLinuxAssessment = null;
if (supportEvidenceText.length > 10) {
try {
const linuxAiRes = await fetch(
`https://models.github.ai/orgs/${owner}/inference/chat/completions`,
{
method: 'POST',
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
'X-GitHub-Api-Version': '2026-03-10',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai/gpt-4.1-mini',
temperature: 0.1,
max_tokens: 200,
messages: [
{
role: 'system',
content:
'You analyze game server documentation to determine Linux support. ' +
'Return only JSON. Be conservative: only say "no" if evidence clearly shows Windows-only.',
},
{
role: 'user',
content:
`Analyze for native Linux dedicated server support:\n\nOfficial docs: ${officialDocsSection.slice(0, 400)}\nLinux binary proof: ${linuxBinaryProofSection.slice(0, 500)}\nGuides: ${guidesSection.slice(0, 800)}\n\n` +
'Return JSON: {"linux_support": "yes"|"no"|"unknown", "confidence": "high"|"medium"|"low", "reason": "one sentence"}',
},
],
}),
}
);
if (linuxAiRes.ok) {
const linuxAiData = await linuxAiRes.json();
const raw = linuxAiData.choices?.[0]?.message?.content || '{}';
aiLinuxAssessment = parseTriageResponse(raw);
console.log(`AI linux assessment: ${JSON.stringify(aiLinuxAssessment)}`);
}
} catch (err) {
console.log(`Linux AI check failed: ${err.message}`);
}
}
// Linux checkbox — used as soft positive evidence only when no negative signals exist.
// We don't fully trust it (users tick it without checking) but it matters when
// server-specific evidence is still inconclusive and no negative patterns were found.
const linuxCheckboxChecked = /\[x\]/i.test(extractSection('Linux support'));
// Determine verdict: confirmed = deterministic evidence; suggested = AI advisory.
const noLinuxFromDeterministicText =
deterministicWindowsOnly ||
(deterministicWineRequired && !hasLinuxEvidence) ||
(windowsBinaryHint && !hasLinuxEvidence);
const noLinuxFromSteamCmd = steamCmdAssessment?.status === 'windows-only';
const noLinuxFromAi =
aiLinuxAssessment?.linux_support === 'no' &&
(aiLinuxAssessment?.confidence === 'high' || aiLinuxAssessment?.confidence === 'medium');
const confirmedNoLinux = noLinuxFromDeterministicText || noLinuxFromSteamCmd;
const suggestsNoLinux = noLinuxFromAi && !confirmedNoLinux;
const confirmedLinuxFromSteamCmd = steamCmdAssessment?.status === 'linux';
const linuxYesFromAi =
aiLinuxAssessment?.linux_support === 'yes' &&
(aiLinuxAssessment?.confidence === 'high' || aiLinuxAssessment?.confidence === 'medium');
const confirmedLinuxSupport =
confirmedLinuxFromSteamCmd || linuxYesFromAi;
// Soft positive: checkbox checked with no negative signals and no definitive server evidence.
const likelySupportedByCheckbox =