action-issue-triage-automation.yml 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459
  1. name: Issue Triage & Automation
  2. on:
  3. workflow_dispatch:
  4. inputs:
  5. issue_state:
  6. description: Issue state to backfill
  7. required: true
  8. default: all
  9. type: choice
  10. options:
  11. - all
  12. - open
  13. - closed
  14. limit:
  15. description: Max issues to process (0 = all)
  16. required: true
  17. default: "0"
  18. type: string
  19. ai_game_fallback:
  20. description: Use AI only when deterministic game mapping finds no game
  21. required: true
  22. default: "false"
  23. type: choice
  24. options:
  25. - "false"
  26. - "true"
  27. issues:
  28. types:
  29. - opened
  30. - edited
  31. - reopened
  32. - labeled
  33. - unlabeled
  34. - assigned
  35. - unassigned
  36. - milestoned
  37. - demilestoned
  38. - transferred
  39. - pinned
  40. - unpinned
  41. issue_comment:
  42. types:
  43. - created
  44. - edited
  45. - deleted
  46. # pull_request_target so pr-labeler can label PRs from forks (pull_request gets a read-only token for forks).
  47. # Safe here: no job checks out or runs PR code on this event.
  48. pull_request_target:
  49. types:
  50. - opened
  51. - edited
  52. - synchronize
  53. - reopened
  54. push:
  55. branches:
  56. - master
  57. - develop
  58. paths:
  59. - "lgsm/data/serverlist.csv"
  60. permissions:
  61. issues: write
  62. pull-requests: write
  63. contents: read
  64. models: read
  65. env:
  66. FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
  67. jobs:
  68. issue-regex-labeler:
  69. if: github.repository_owner == 'GameServerManagers' && github.event_name == 'issues' && github.event.issue.state == 'open' && (github.event.action == 'opened' || github.event.action == 'edited')
  70. runs-on: ubuntu-latest
  71. steps:
  72. - name: Issue Labeler
  73. uses: github/issue-labeler@v3.5
  74. with:
  75. repo-token: "${{ secrets.GITHUB_TOKEN }}"
  76. configuration-path: .github/labeler.yml
  77. enable-versioned-regex: 0
  78. include-title: 1
  79. sync-labels: 0
  80. issue-ai-maintenance:
  81. if: github.repository_owner == 'GameServerManagers' && (github.event_name == 'issues' || github.event_name == 'issue_comment') && github.event.issue.state == 'open'
  82. runs-on: ubuntu-latest
  83. steps:
  84. - name: Reconcile issue labels and AI triage
  85. uses: actions/github-script@v9
  86. env:
  87. GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  88. with:
  89. script: |
  90. const { execFileSync } = require('node:child_process');
  91. const owner = context.repo.owner;
  92. const repo = context.repo.repo;
  93. const eventName = context.eventName;
  94. const action = context.payload.action;
  95. const issueNumber = context.payload.issue?.number;
  96. const AI_MARKER = '<!-- ai-triage -->';
  97. if (!issueNumber) {
  98. console.log('No issue number found in payload.');
  99. return;
  100. }
  101. // Avoid bot-to-bot relabel loops on label events.
  102. if (
  103. eventName === 'issues' &&
  104. ['labeled', 'unlabeled'].includes(action) &&
  105. context.actor === 'github-actions[bot]'
  106. ) {
  107. console.log('Skipping self-triggered label event.');
  108. return;
  109. }
  110. const issueResp = await github.rest.issues.get({
  111. owner,
  112. repo,
  113. issue_number: issueNumber,
  114. });
  115. const issue = issueResp.data;
  116. const title = issue.title || '';
  117. const body = issue.body || '';
  118. const existingLabels = new Set((issue.labels || []).map((l) => l.name).filter(Boolean));
  119. function parseTriageResponse(raw) {
  120. const input = (raw || '').trim();
  121. if (!input) return {};
  122. const candidates = [input];
  123. const fenced = input.match(/```(?:json)?\s*([\s\S]*?)```/i);
  124. if (fenced?.[1]) candidates.push(fenced[1].trim());
  125. const firstBrace = input.indexOf('{');
  126. const lastBrace = input.lastIndexOf('}');
  127. if (firstBrace !== -1 && lastBrace > firstBrace) {
  128. candidates.push(input.slice(firstBrace, lastBrace + 1));
  129. }
  130. for (const candidate of candidates) {
  131. try {
  132. return JSON.parse(candidate);
  133. } catch (_err) {
  134. // Continue trying fallbacks.
  135. }
  136. }
  137. return {};
  138. }
  139. function extractSection(sectionName) {
  140. const escaped = sectionName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  141. const re = new RegExp(`### ${escaped}\\n\\n([\\s\\S]*?)(\\n### |$)`, 'i');
  142. return (body.match(re)?.[1] || '').trim();
  143. }
  144. function normalizeName(value) {
  145. return (value || '')
  146. .toLowerCase()
  147. .replace(/[’'`]/g, '')
  148. .replace(/[^a-z0-9]+/g, ' ')
  149. .trim();
  150. }
  151. function parseGameCandidates(gameField) {
  152. if (!gameField || /^_?no response_?$/i.test(gameField)) {
  153. return [];
  154. }
  155. return gameField
  156. .replace(/\(.*?\)/g, ' ')
  157. .split(/\n|,|\s+&\s+|\s+and\s+|\//i)
  158. .map((v) => v.trim())
  159. .filter(Boolean);
  160. }
  161. function findGamesFromText(text, gameAliasToLabel, gameAliasToScript) {
  162. const labels = new Set();
  163. const scripts = new Set();
  164. const normalizedText = normalizeName(text);
  165. if (!normalizedText) return { labels, scripts };
  166. const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  167. const aliases = [];
  168. for (const [alias, label] of gameAliasToLabel.entries()) {
  169. if (alias.length < 3) continue;
  170. aliases.push({ alias, label, script: gameAliasToScript.get(alias) || null });
  171. }
  172. // Prefer longer aliases first so "killing floor 2" does not also match "killing floor".
  173. aliases.sort((a, b) => b.alias.length - a.alias.length);
  174. const usedRanges = [];
  175. const isOverlapping = (start, end) =>
  176. usedRanges.some((range) => start < range.end && end > range.start);
  177. for (const entry of aliases) {
  178. const pattern = new RegExp(`\\b${escapeRegex(entry.alias).replace(/\\ /g, '\\s+')}\\b`, 'g');
  179. let match;
  180. while ((match = pattern.exec(normalizedText)) !== null) {
  181. const start = match.index;
  182. const end = start + match[0].length;
  183. if (isOverlapping(start, end)) continue;
  184. labels.add(entry.label);
  185. if (entry.script) scripts.add(entry.script);
  186. usedRanges.push({ start, end });
  187. }
  188. }
  189. return { labels, scripts };
  190. }
  191. function hasAliasHitForLabel(text, targetLabel, gameAliasToLabel) {
  192. const normalizedText = normalizeName(text);
  193. if (!normalizedText || !targetLabel) return false;
  194. const paddedText = ` ${normalizedText} `;
  195. for (const [alias, label] of gameAliasToLabel.entries()) {
  196. if (label !== targetLabel) continue;
  197. if (alias.length < 3) continue;
  198. if (paddedText.includes(` ${alias} `)) return true;
  199. // Allow obvious joined-word variants for multi-token aliases
  200. // (e.g., "counter strike 1 6" matching "counterstrike 1.6").
  201. const aliasTokens = alias.split(/\s+/).filter(Boolean);
  202. if (aliasTokens.length > 1) {
  203. const escapedTokens = aliasTokens.map((token) =>
  204. token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  205. );
  206. const flexibleAliasPattern = new RegExp(`\\b${escapedTokens.join('\\s*')}\\b`);
  207. if (flexibleAliasPattern.test(normalizedText)) return true;
  208. }
  209. }
  210. return false;
  211. }
  212. function parseVdf(text) {
  213. const root = {};
  214. const stack = [root];
  215. let pendingKey = null;
  216. const tokenPattern = /"((?:[^"\\]|\\.)*)"|([{}])/g;
  217. let match;
  218. while ((match = tokenPattern.exec(text)) !== null) {
  219. const current = stack[stack.length - 1];
  220. if (match[2] === '{') {
  221. const child = {};
  222. if (pendingKey !== null) current[pendingKey] = child;
  223. stack.push(child);
  224. pendingKey = null;
  225. } else if (match[2] === '}') {
  226. if (stack.length > 1) stack.pop();
  227. pendingKey = null;
  228. } else if (pendingKey === null) {
  229. pendingKey = match[1];
  230. } else {
  231. current[pendingKey] = match[1];
  232. pendingKey = null;
  233. }
  234. }
  235. return root;
  236. }
  237. function parseSteamAppInfo(output, appId) {
  238. const start = output.search(new RegExp(`^"${appId}"\\s*$`, 'm'));
  239. if (start === -1) return null;
  240. return parseVdf(output.slice(start))[String(appId)] ?? null;
  241. }
  242. function runSteamCmdLinuxCheck(appId) {
  243. if (!appId) {
  244. return { status: 'skipped', reason: 'No Steam AppID provided.' };
  245. }
  246. const image = 'gameservermanagers/steamcmd:latest';
  247. const args = [
  248. 'run',
  249. '--rm',
  250. '-e',
  251. 'PUID=1001',
  252. '-e',
  253. 'PGID=1001',
  254. image,
  255. '+@ShutdownOnFailedCommand',
  256. '1',
  257. '+@NoPromptForPassword',
  258. '1',
  259. '+login',
  260. 'anonymous',
  261. '+app_info_update',
  262. '1',
  263. '+app_info_print',
  264. String(appId),
  265. '+quit',
  266. ];
  267. try {
  268. const output = execFileSync('docker', args, {
  269. encoding: 'utf8',
  270. stdio: ['ignore', 'pipe', 'pipe'],
  271. timeout: 120000,
  272. maxBuffer: 10 * 1024 * 1024,
  273. });
  274. const appInfo = parseSteamAppInfo(output, appId);
  275. if (!appInfo) {
  276. return {
  277. status: 'unknown',
  278. reason: `SteamCMD app_info returned no data for AppID ${appId}.`,
  279. };
  280. }
  281. const osListOf = (node) => String(node?.config?.oslist ?? '').toLowerCase();
  282. const isObject = (value) => value && typeof value === 'object';
  283. const commonOsList = String(appInfo.common?.oslist ?? '').toLowerCase();
  284. const launches = Object.values(appInfo.config?.launch ?? {}).filter(isObject);
  285. const serverDepots = Object.entries(appInfo.depots ?? {}).filter(
  286. ([id, depot]) =>
  287. /^\d+$/.test(id) &&
  288. isObject(depot) &&
  289. !['1004', '1005', '1006'].includes(id) &&
  290. depot.depotfromapp === undefined &&
  291. depot.sharedinstall !== '1'
  292. );
  293. const hasLinuxSignal =
  294. commonOsList.includes('linux') ||
  295. launches.some(
  296. (launch) =>
  297. osListOf(launch).includes('linux') ||
  298. (!osListOf(launch) && /\.(sh|x86_64)$/i.test(launch.executable ?? ''))
  299. ) ||
  300. serverDepots.some(([, depot]) => osListOf(depot).includes('linux'));
  301. const hasWindowsOnlySignal =
  302. !hasLinuxSignal &&
  303. (commonOsList === 'windows' ||
  304. (launches.length > 0 &&
  305. launches.every(
  306. (launch) =>
  307. osListOf(launch) === 'windows' ||
  308. /\.(exe|bat|cmd)$/i.test(launch.executable ?? '')
  309. )));
  310. if (hasLinuxSignal) {
  311. return {
  312. status: 'linux',
  313. reason: `SteamCMD app_info contains Linux platform/depot metadata for AppID ${appId}.`,
  314. };
  315. }
  316. if (hasWindowsOnlySignal) {
  317. return {
  318. status: 'windows-only',
  319. reason: `SteamCMD app_info contains Windows-only platform metadata for AppID ${appId}.`,
  320. };
  321. }
  322. return {
  323. status: 'unknown',
  324. reason: `SteamCMD app_info returned no clear Linux server metadata for AppID ${appId}.`,
  325. };
  326. } catch (err) {
  327. const stderr = err.stderr ? String(err.stderr).trim() : '';
  328. const stdout = err.stdout ? String(err.stdout).trim() : '';
  329. const message = stderr || stdout || err.message;
  330. return {
  331. status: 'error',
  332. reason: `SteamCMD lookup failed: ${message}`,
  333. };
  334. }
  335. }
  336. function parseServerlistCsv(csvText) {
  337. const rows = [];
  338. const lines = (csvText || '').split(/\r?\n/);
  339. for (let i = 1; i < lines.length; i += 1) {
  340. const line = lines[i]?.trim();
  341. if (!line) continue;
  342. const parts = line.split(',');
  343. if (parts.length < 3) continue;
  344. rows.push({
  345. shortname: parts[0].trim(),
  346. gameservername: parts[1].trim(),
  347. gamename: parts[2].trim(),
  348. });
  349. }
  350. return rows;
  351. }
  352. function inferTypeFromTitle(issueTitle) {
  353. if (/^\[bug\]/i.test(issueTitle)) return 'type: bug';
  354. if (/\bserver\s+request\b/i.test(issueTitle)) return 'type: game server request';
  355. const hasBracketPrefix = /^\[[^\]]+\]/.test(issueTitle || '');
  356. const isServerCreation =
  357. /\bserver\s+creation\b/i.test(issueTitle) ||
  358. (hasBracketPrefix && /\bcreation\b/i.test(issueTitle));
  359. const isServerSupportRequest =
  360. /\bserver\s+support\b/i.test(issueTitle) ||
  361. (/\bsupport\s+for\b/i.test(issueTitle) && /\bserver\b/i.test(issueTitle));
  362. if (isServerCreation || isServerSupportRequest) return 'type: game server request';
  363. if (/^\[feature\]/i.test(issueTitle)) return 'type: feature';
  364. if (/^\[server request\]/i.test(issueTitle)) return 'type: game server request';
  365. if (/^\[docs?\]/i.test(issueTitle)) return 'type: docs';
  366. return null;
  367. }
  368. function inferDesiredType(issueTitle, labelNames) {
  369. const titleType = inferTypeFromTitle(issueTitle);
  370. if (titleType) return titleType;
  371. // Prefer server requests over generic feature when both labels exist.
  372. if (labelNames.has('type: game server request')) return 'type: game server request';
  373. for (const label of [
  374. 'type: bug',
  375. 'type: feature',
  376. 'type: game server request',
  377. 'type: docs',
  378. ]) {
  379. if (labelNames.has(label)) return label;
  380. }
  381. return null;
  382. }
  383. function inferIssueTypeNameFromDesiredType(typeLabel) {
  384. if (typeLabel === 'type: bug') return 'Bug';
  385. if (typeLabel === 'type: feature') return 'Feature';
  386. if (typeLabel === 'type: game server request') return 'Server Request';
  387. if (typeLabel === 'type: docs') return 'Task';
  388. return null;
  389. }
  390. function parseCommandSelections(sectionValue) {
  391. const selected = new Set();
  392. const re = /command:\s*([a-z-]+)/gi;
  393. let m;
  394. while ((m = re.exec(sectionValue || '')) !== null) {
  395. let value = m[1].toLowerCase();
  396. if (value.startsWith('mods-')) value = 'mods';
  397. if (value === 'auto-update') value = 'update';
  398. selected.add(`command: ${value}`);
  399. }
  400. return selected;
  401. }
  402. function parseDistroSelections(sectionValue) {
  403. const text = sectionValue || '';
  404. const selected = new Set();
  405. if (/\bUbuntu\b/i.test(text)) selected.add('distro: Ubuntu');
  406. if (/\bDebian\b/i.test(text)) selected.add('distro: Debian');
  407. if (/\bAlmaLinux\b/i.test(text)) selected.add('distro: AlmaLinux');
  408. if (/\bRocky\b/i.test(text)) selected.add('distro: Rocky Linux');
  409. if (/\bCentOS\b/i.test(text)) selected.add('distro: CentOS');
  410. if (/\bFedora\b/i.test(text)) selected.add('distro: Fedora');
  411. if (/\bopenSUSE\b/i.test(text)) selected.add('distro: openSUSE');
  412. if (/\bArch Linux\b/i.test(text)) selected.add('distro: Arch Linux');
  413. if (/\bSlackware\b/i.test(text)) selected.add('distro: Slackware');
  414. return selected;
  415. }
  416. const repoLabels = await github.paginate(github.rest.issues.listLabelsForRepo, {
  417. owner,
  418. repo,
  419. per_page: 100,
  420. });
  421. const gameLabelByNormalized = new Map();
  422. for (const label of repoLabels) {
  423. if (!label.name.startsWith('game: ')) continue;
  424. gameLabelByNormalized.set(normalizeName(label.name.slice(6)), label.name);
  425. }
  426. const existingEngineLabels = new Set(
  427. repoLabels.map((label) => label.name).filter((name) => name.startsWith('engine: '))
  428. );
  429. const gameAliasToLabel = new Map();
  430. const gameAliasToScript = new Map();
  431. const engineByScript = new Map();
  432. for (const [normalizedGameName, label] of gameLabelByNormalized.entries()) {
  433. gameAliasToLabel.set(normalizedGameName, label);
  434. }
  435. try {
  436. const serverlistContent = await github.rest.repos.getContent({
  437. owner,
  438. repo,
  439. path: 'lgsm/data/serverlist.csv',
  440. });
  441. const encoded = serverlistContent.data?.content || '';
  442. const csvText = Buffer.from(encoded, 'base64').toString('utf8');
  443. const serverRows = parseServerlistCsv(csvText);
  444. for (const row of serverRows) {
  445. const canonicalLabel = gameLabelByNormalized.get(normalizeName(row.gamename));
  446. if (!canonicalLabel) continue;
  447. for (const alias of [row.shortname, row.gameservername, row.gamename]) {
  448. const key = normalizeName(alias);
  449. if (!key) continue;
  450. gameAliasToLabel.set(key, canonicalLabel);
  451. gameAliasToScript.set(key, row.gameservername);
  452. }
  453. }
  454. } catch (err) {
  455. console.log(`Could not load serverlist aliases: ${err.message}`);
  456. }
  457. async function ensureEngineLabel(engineLabel) {
  458. if (existingEngineLabels.has(engineLabel)) return;
  459. try {
  460. await github.rest.issues.createLabel({
  461. owner,
  462. repo,
  463. name: engineLabel,
  464. color: '000000',
  465. description: `Issues related to ${engineLabel.slice(8)} engine`,
  466. });
  467. existingEngineLabels.add(engineLabel);
  468. } catch (err) {
  469. if (err.status === 422) {
  470. existingEngineLabels.add(engineLabel);
  471. return;
  472. }
  473. console.log(`Could not create engine label "${engineLabel}": ${err.message}`);
  474. }
  475. }
  476. async function getEngineForScript(scriptName) {
  477. if (!scriptName) return null;
  478. if (engineByScript.has(scriptName)) {
  479. return engineByScript.get(scriptName);
  480. }
  481. try {
  482. const cfgContent = await github.rest.repos.getContent({
  483. owner,
  484. repo,
  485. path: `lgsm/config-default/config-lgsm/${scriptName}/_default.cfg`,
  486. });
  487. const encoded = cfgContent.data?.content || '';
  488. const cfgText = Buffer.from(encoded, 'base64').toString('utf8');
  489. const engine = cfgText.match(/^engine="([^"]+)"/m)?.[1] || null;
  490. engineByScript.set(scriptName, engine);
  491. return engine;
  492. } catch (err) {
  493. console.log(`Could not detect engine for ${scriptName}: ${err.message}`);
  494. engineByScript.set(scriptName, null);
  495. return null;
  496. }
  497. }
  498. const labelsToAdd = new Set();
  499. const labelsToRemove = new Set();
  500. // Deterministic reconciliation on every interaction.
  501. const desiredType = inferDesiredType(title, existingLabels);
  502. if (desiredType) {
  503. labelsToAdd.add(desiredType);
  504. for (const label of existingLabels) {
  505. if (label.startsWith('type: ') && label !== desiredType) {
  506. labelsToRemove.add(label);
  507. }
  508. }
  509. const desiredIssueTypeName = inferIssueTypeNameFromDesiredType(desiredType);
  510. if (desiredIssueTypeName) {
  511. try {
  512. const issueTypeData = await github.graphql(
  513. `query($owner:String!,$repo:String!,$number:Int!){
  514. repository(owner:$owner,name:$repo){
  515. issueTypes(first:20){ nodes { id name } }
  516. issue(number:$number){ id issueType { id name } }
  517. }
  518. }`,
  519. { owner, repo, number: issueNumber }
  520. );
  521. const issueNode = issueTypeData.repository?.issue;
  522. const issueTypes = issueTypeData.repository?.issueTypes?.nodes || [];
  523. const desiredIssueType = issueTypes.find((t) => t.name === desiredIssueTypeName);
  524. if (issueNode?.id && desiredIssueType?.id && issueNode.issueType?.id !== desiredIssueType.id) {
  525. await github.graphql(
  526. `mutation($id:ID!,$issueTypeId:ID!){
  527. updateIssue(input:{id:$id,issueTypeId:$issueTypeId}){
  528. issue { id number issueType { id name } }
  529. }
  530. }`,
  531. { id: issueNode.id, issueTypeId: desiredIssueType.id }
  532. );
  533. }
  534. } catch (err) {
  535. console.log(`Could not sync Issue Type: ${err.message}`);
  536. }
  537. }
  538. }
  539. const commandSection = extractSection('Command');
  540. const desiredCommands = parseCommandSelections(commandSection);
  541. if (desiredCommands.size > 0) {
  542. for (const label of desiredCommands) labelsToAdd.add(label);
  543. for (const label of existingLabels) {
  544. if (label.startsWith('command: ') && !desiredCommands.has(label)) {
  545. labelsToRemove.add(label);
  546. }
  547. }
  548. }
  549. const distroSection = extractSection('Linux distro');
  550. const desiredDistros = parseDistroSelections(distroSection);
  551. if (desiredDistros.size > 0) {
  552. for (const label of desiredDistros) labelsToAdd.add(label);
  553. for (const label of existingLabels) {
  554. if (label.startsWith('distro: ') && !desiredDistros.has(label)) {
  555. labelsToRemove.add(label);
  556. }
  557. }
  558. }
  559. const tmuxContextPattern = /\b(tmuxception|check_tmuxception)\b/i;
  560. if (existingLabels.has('info: tmux') && !tmuxContextPattern.test(`${title}\n${body}`)) {
  561. labelsToRemove.add('info: tmux');
  562. }
  563. const desiredGames = new Set();
  564. const desiredServerScripts = new Set();
  565. // 'Game server' is the section name in server_request.yml; 'Game' is used in bug_report.yml.
  566. const gameField = extractSection('Game server') || extractSection('Game');
  567. const gameCandidates = parseGameCandidates(gameField);
  568. const hasStructuredGameSelection = gameCandidates.length > 0;
  569. for (const candidate of gameCandidates) {
  570. const normalizedCandidate = normalizeName(candidate);
  571. const mapped = gameAliasToLabel.get(normalizedCandidate) || gameLabelByNormalized.get(normalizedCandidate);
  572. if (mapped) desiredGames.add(mapped);
  573. const mappedScript = gameAliasToScript.get(normalizedCandidate);
  574. if (mappedScript) desiredServerScripts.add(mappedScript);
  575. }
  576. // Legacy issues often have no form section; fall back to deterministic text matching.
  577. // If a structured Game field exists but does not map, do not guess from free text.
  578. if (desiredGames.size === 0 && !hasStructuredGameSelection) {
  579. const fromText = findGamesFromText(`${title}\n${body}`, gameAliasToLabel, gameAliasToScript);
  580. for (const label of fromText.labels) desiredGames.add(label);
  581. for (const scriptName of fromText.scripts) desiredServerScripts.add(scriptName);
  582. }
  583. // AI advisory is only needed on issue opened/edited.
  584. let triage = {};
  585. let ranAi = false;
  586. const shouldRunAi = eventName === 'issues' && ['opened', 'edited'].includes(action);
  587. const shouldRunLinuxSupportCheck =
  588. eventName === 'issues' &&
  589. ['opened', 'edited', 'reopened', 'labeled', 'unlabeled'].includes(action);
  590. if (shouldRunAi) {
  591. ranAi = true;
  592. const isShortBody = body.trim().length < 80;
  593. if (isShortBody) {
  594. labelsToAdd.add('needs: more info');
  595. } else {
  596. try {
  597. const res = await fetch(
  598. `https://models.github.ai/orgs/${owner}/inference/chat/completions`,
  599. {
  600. method: 'POST',
  601. headers: {
  602. Accept: 'application/vnd.github+json',
  603. Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
  604. 'X-GitHub-Api-Version': '2026-03-10',
  605. 'Content-Type': 'application/json',
  606. },
  607. body: JSON.stringify({
  608. model: 'openai/gpt-4.1-mini',
  609. temperature: 0.1,
  610. max_tokens: 400,
  611. messages: [
  612. {
  613. role: 'system',
  614. content:
  615. 'You are a triage assistant for LinuxGSM, an open-source Linux game server manager. ' +
  616. 'Return only JSON. Analyze issue quality, suggest missing info, detect game names, and suggest contextual labels ' +
  617. 'only when highly certain. Never set type: docs just because docs links are mentioned.',
  618. },
  619. {
  620. role: 'user',
  621. content:
  622. `Title: ${title}\n\nBody:\n${body.slice(0, 3000)}\n\n` +
  623. 'Return JSON schema:\n' +
  624. '{\n' +
  625. ' "quality": "good" | "ok" | "poor",\n' +
  626. ' "missing_info": ["list of specific missing fields"],\n' +
  627. ' "detected_game": "canonical game name if one is mentioned, or null",\n' +
  628. ' "game_confidence": "high" | "medium" | "low" | null,\n' +
  629. ' "context_labels": ["labels"],\n' +
  630. ' "context_confidence": "high" | "medium" | "low" | null,\n' +
  631. ' "game_note": "string",\n' +
  632. ' "comment": "string"\n' +
  633. '}',
  634. },
  635. ],
  636. }),
  637. }
  638. );
  639. if (res.ok) {
  640. const data = await res.json();
  641. const raw = data.choices?.[0]?.message?.content || '{}';
  642. triage = parseTriageResponse(raw);
  643. } else {
  644. console.log(`GitHub Models returned ${res.status} - skipping AI triage.`);
  645. }
  646. } catch (err) {
  647. console.log('AI triage skipped:', err.message);
  648. }
  649. }
  650. }
  651. const allowedContextLabels = new Set([
  652. 'type: docs',
  653. 'info: docs',
  654. 'info: dependency',
  655. 'info: docker',
  656. 'info: email',
  657. 'info: query',
  658. 'info: steamcmd',
  659. 'info: systemd',
  660. 'info: website',
  661. 'info: alerts',
  662. ]);
  663. const isPoor = triage?.quality === 'poor';
  664. const missing = Array.isArray(triage?.missing_info) ? triage.missing_info : [];
  665. const hasIssues = isPoor || missing.length > 0;
  666. // Fallback to AI-detected game only when no structured Game field exists.
  667. const detectedGame = triage?.detected_game;
  668. const gameConfidence = triage?.game_confidence;
  669. if (desiredGames.size === 0 && !hasStructuredGameSelection && detectedGame && gameConfidence === 'high') {
  670. const normalizedDetectedGame = normalizeName(detectedGame);
  671. const mapped = gameLabelByNormalized.get(normalizedDetectedGame);
  672. if (mapped) {
  673. desiredGames.add(mapped);
  674. }
  675. const mappedScript = gameAliasToScript.get(normalizedDetectedGame);
  676. if (mappedScript) desiredServerScripts.add(mappedScript);
  677. }
  678. // Resolve server scripts from canonical game labels when only labels were mapped.
  679. for (const gameLabel of desiredGames) {
  680. const gameName = gameLabel.slice(6);
  681. const mappedScript = gameAliasToScript.get(normalizeName(gameName));
  682. if (mappedScript) desiredServerScripts.add(mappedScript);
  683. }
  684. const desiredEngineLabels = new Set();
  685. for (const scriptName of desiredServerScripts) {
  686. const engine = await getEngineForScript(scriptName);
  687. if (!engine) continue;
  688. const engineLabel = `engine: ${engine}`;
  689. await ensureEngineLabel(engineLabel);
  690. desiredEngineLabels.add(engineLabel);
  691. }
  692. if (desiredEngineLabels.size > 0) {
  693. for (const label of desiredEngineLabels) labelsToAdd.add(label);
  694. for (const label of existingLabels) {
  695. if (label.startsWith('engine: ') && !desiredEngineLabels.has(label)) {
  696. labelsToRemove.add(label);
  697. }
  698. }
  699. }
  700. if (desiredGames.size > 0) {
  701. for (const label of desiredGames) labelsToAdd.add(label);
  702. if (hasStructuredGameSelection) {
  703. for (const label of existingLabels) {
  704. if (label.startsWith('game: ') && !desiredGames.has(label)) {
  705. labelsToRemove.add(label);
  706. }
  707. }
  708. } else {
  709. // For legacy issues without structured game selection, only prune stale
  710. // broader labels when a more specific inferred game label exists.
  711. const desiredGameNamesNormalized = new Set(
  712. [...desiredGames].map((label) => normalizeName(label.slice(6)))
  713. );
  714. for (const label of existingLabels) {
  715. if (!label.startsWith('game: ') || desiredGames.has(label)) continue;
  716. const existingGameName = normalizeName(label.slice(6));
  717. const isBroaderOverlap = [...desiredGameNamesNormalized].some(
  718. (desiredName) => desiredName !== existingGameName && desiredName.startsWith(`${existingGameName} `)
  719. );
  720. if (isBroaderOverlap) {
  721. labelsToRemove.add(label);
  722. }
  723. }
  724. }
  725. }
  726. if (triage?.context_confidence === 'high') {
  727. const contextLabels = Array.isArray(triage.context_labels) ? triage.context_labels : [];
  728. for (const label of contextLabels) {
  729. if (!allowedContextLabels.has(label)) continue;
  730. if (
  731. label === 'type: docs' &&
  732. (existingLabels.has('type: game server request') || desiredType === 'type: game server request')
  733. ) {
  734. continue;
  735. }
  736. labelsToAdd.add(label);
  737. }
  738. }
  739. if (ranAi && hasIssues) {
  740. labelsToAdd.add('needs: more info');
  741. }
  742. if (ranAi && !hasIssues && existingLabels.has('needs: more info')) {
  743. labelsToRemove.add('needs: more info');
  744. }
  745. // Avoid pointless API calls.
  746. let finalAdds = [...labelsToAdd].filter((label) => !existingLabels.has(label));
  747. let finalRemoves = [...labelsToRemove].filter((label) => existingLabels.has(label));
  748. const isGameOrEngineLabel = (label) => label.startsWith('game: ') || label.startsWith('engine: ');
  749. if ([...finalAdds, ...finalRemoves].some(isGameOrEngineLabel)) {
  750. try {
  751. const issueEvents = await github.paginate(github.rest.issues.listEvents, {
  752. owner,
  753. repo,
  754. issue_number: issueNumber,
  755. per_page: 100,
  756. });
  757. const lastManualLabelEvent = new Map();
  758. for (const e of issueEvents) {
  759. if (!['labeled', 'unlabeled'].includes(e.event) || !e.label?.name) continue;
  760. lastManualLabelEvent.set(e.label.name, e.actor?.type === 'Bot' ? null : e.event);
  761. }
  762. finalAdds = finalAdds.filter((label) => {
  763. if (!isGameOrEngineLabel(label) || lastManualLabelEvent.get(label) !== 'unlabeled') return true;
  764. console.log(`Label "${label}" was removed manually; not adding it back.`);
  765. return false;
  766. });
  767. finalRemoves = finalRemoves.filter((label) => {
  768. if (!isGameOrEngineLabel(label) || lastManualLabelEvent.get(label) !== 'labeled') return true;
  769. console.log(`Label "${label}" was added manually; keeping it.`);
  770. return false;
  771. });
  772. } catch (err) {
  773. console.log(`Could not read issue events: ${err.message}`);
  774. }
  775. }
  776. for (const label of finalRemoves) {
  777. try {
  778. await github.rest.issues.removeLabel({
  779. owner,
  780. repo,
  781. issue_number: issueNumber,
  782. name: label,
  783. });
  784. console.log(`Removed label: ${label}`);
  785. } catch (err) {
  786. console.log(`Could not remove label "${label}": ${err.message}`);
  787. }
  788. }
  789. for (const label of finalAdds) {
  790. try {
  791. await github.rest.issues.addLabels({
  792. owner,
  793. repo,
  794. issue_number: issueNumber,
  795. labels: [label],
  796. });
  797. console.log(`Added label: ${label}`);
  798. } catch (err) {
  799. console.log(`Could not add label "${label}": ${err.message}`);
  800. }
  801. }
  802. // Post AI comment only for opened/edited issues when useful.
  803. if (ranAi) {
  804. const gameNote = triage?.game_note || '';
  805. const reporterComment = triage?.comment || '';
  806. if (hasIssues || gameNote) {
  807. const missingBlock = missing.length > 0
  808. ? `\n\n**Missing information:**\n${missing.map((m) => `- ${m}`).join('\n')}`
  809. : '';
  810. const gameBlock = gameNote ? `\n\n**Game name note:** ${gameNote}` : '';
  811. const triageCommentBody =
  812. `${AI_MARKER}\n` +
  813. `Thanks for opening this issue!\n\n` +
  814. `${reporterComment}` +
  815. `${missingBlock}` +
  816. `${gameBlock}\n\n` +
  817. `_This note was generated automatically by AI triage and may not be perfect. ` +
  818. `A maintainer will review shortly._`;
  819. try {
  820. const comments = await github.paginate(github.rest.issues.listComments, {
  821. owner,
  822. repo,
  823. issue_number: issueNumber,
  824. per_page: 100,
  825. });
  826. const existingAiComment = [...comments].reverse().find(
  827. (comment) => comment.user?.type === 'Bot' && comment.body?.includes(AI_MARKER)
  828. );
  829. if (existingAiComment) {
  830. await github.rest.issues.updateComment({
  831. owner,
  832. repo,
  833. comment_id: existingAiComment.id,
  834. body: triageCommentBody,
  835. });
  836. } else {
  837. await github.rest.issues.createComment({
  838. owner,
  839. repo,
  840. issue_number: issueNumber,
  841. body: triageCommentBody,
  842. });
  843. }
  844. } catch (err) {
  845. console.log('Could not post comment:', err.message);
  846. }
  847. }
  848. }
  849. // === Linux support verification for server request issues ===
  850. // Runs only on opened/edited events to avoid reprocessing every label change.
  851. const isServerRequest =
  852. desiredType === 'type: game server request' ||
  853. existingLabels.has('type: game server request') ||
  854. /\[server request\]/i.test(title);
  855. if (isServerRequest && shouldRunLinuxSupportCheck) {
  856. const officialDocsSection = extractSection('Official dedicated server documentation');
  857. const linuxBinaryProofSection = extractSection('Linux binary proof');
  858. const guidesSection = extractSection('Guides');
  859. const steamSection = extractSection('Steam').trim();
  860. const isSteamNo = /^no$/i.test(steamSection);
  861. const isSteamYes = /^yes$/i.test(steamSection);
  862. const steamAppIdRaw = extractSection('Steam appid').trim();
  863. const steamAppId = /^\d+$/.test(steamAppIdRaw) ? steamAppIdRaw : null;
  864. const supportEvidenceText = [officialDocsSection, linuxBinaryProofSection, guidesSection]
  865. .join('\n')
  866. .trim();
  867. // Deterministic textual checks to avoid trusting checkbox-only reports.
  868. const windowsOnlyPatterns = [
  869. /\bwindows\s+only\b/i,
  870. /\bonly\s+windows\b/i,
  871. /\bno\s+linux\s+support\b/i,
  872. /\blinux\s+not\s+supported\b/i,
  873. /\bdoes\s+not\s+support\s+linux\b/i,
  874. ];
  875. const wineRequiredPatterns = [
  876. /\brequires?\s+wine\b/i,
  877. /\buse\s+wine\b/i,
  878. /\brun\s+with\s+wine\b/i,
  879. /\bvia\s+wine\b/i,
  880. /\bproton\b/i,
  881. ];
  882. const linuxEvidencePatterns = [
  883. /\blinux\b/i,
  884. /\bubuntu\b/i,
  885. /\bdebian\b/i,
  886. /\blinuxgsm\b/i,
  887. /\bsteamcmd\s*\+app_update\b/i,
  888. ];
  889. const windowsBinaryHint = /\b\.exe\b/i.test(supportEvidenceText);
  890. const deterministicWindowsOnly = windowsOnlyPatterns.some((re) => re.test(supportEvidenceText));
  891. const deterministicWineRequired = wineRequiredPatterns.some((re) => re.test(supportEvidenceText));
  892. const hasLinuxEvidence = linuxEvidencePatterns.some((re) => re.test(supportEvidenceText));
  893. // Steam store API is client-app metadata only. It is kept for comment context,
  894. // but it is NOT used to determine dedicated server Linux support.
  895. let steamLinuxSupport = null; // true=yes, false=no, null=unknown/informational-only
  896. let steamAppIsServerTool = false; // success:false from store API = likely server-tool AppID
  897. let steamCmdAssessment = null;
  898. if (steamAppId) {
  899. try {
  900. const steamRes = await fetch(
  901. `https://store.steampowered.com/api/appdetails?appids=${steamAppId}&filters=platforms`,
  902. { signal: AbortSignal.timeout(8000) }
  903. );
  904. if (steamRes.ok) {
  905. const steamData = await steamRes.json();
  906. const appData = steamData[steamAppId];
  907. if (appData?.success && appData?.data?.platforms) {
  908. steamLinuxSupport = appData.data.platforms.linux === true;
  909. console.log(`Steam AppID ${steamAppId} linux=${steamLinuxSupport}`);
  910. } else if (appData?.success === false) {
  911. // Dedicated server tool AppIDs have no store page — inconclusive, not negative.
  912. steamAppIsServerTool = true;
  913. console.log(`Steam AppID ${steamAppId} has no store page (likely a server-tool AppID)`);
  914. }
  915. }
  916. } catch (err) {
  917. console.log(`Steam API check failed: ${err.message}`);
  918. }
  919. steamCmdAssessment = runSteamCmdLinuxCheck(steamAppId);
  920. console.log(`SteamCMD assessment: ${JSON.stringify(steamCmdAssessment)}`);
  921. }
  922. // AI analysis of official docs/guides for Linux evidence.
  923. let aiLinuxAssessment = null;
  924. if (supportEvidenceText.length > 10) {
  925. try {
  926. const linuxAiRes = await fetch(
  927. `https://models.github.ai/orgs/${owner}/inference/chat/completions`,
  928. {
  929. method: 'POST',
  930. headers: {
  931. Accept: 'application/vnd.github+json',
  932. Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
  933. 'X-GitHub-Api-Version': '2026-03-10',
  934. 'Content-Type': 'application/json',
  935. },
  936. body: JSON.stringify({
  937. model: 'openai/gpt-4.1-mini',
  938. temperature: 0.1,
  939. max_tokens: 200,
  940. messages: [
  941. {
  942. role: 'system',
  943. content:
  944. 'You analyze game server documentation to determine Linux support. ' +
  945. 'Return only JSON. Be conservative: only say "no" if evidence clearly shows Windows-only.',
  946. },
  947. {
  948. role: 'user',
  949. content:
  950. `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` +
  951. 'Return JSON: {"linux_support": "yes"|"no"|"unknown", "confidence": "high"|"medium"|"low", "reason": "one sentence"}',
  952. },
  953. ],
  954. }),
  955. }
  956. );
  957. if (linuxAiRes.ok) {
  958. const linuxAiData = await linuxAiRes.json();
  959. const raw = linuxAiData.choices?.[0]?.message?.content || '{}';
  960. aiLinuxAssessment = parseTriageResponse(raw);
  961. console.log(`AI linux assessment: ${JSON.stringify(aiLinuxAssessment)}`);
  962. }
  963. } catch (err) {
  964. console.log(`Linux AI check failed: ${err.message}`);
  965. }
  966. }
  967. // Linux checkbox — used as soft positive evidence only when no negative signals exist.
  968. // We don't fully trust it (users tick it without checking) but it matters when
  969. // server-specific evidence is still inconclusive and no negative patterns were found.
  970. const linuxCheckboxChecked = /\[x\]/i.test(extractSection('Linux support'));
  971. // Determine verdict: confirmed = deterministic evidence; suggested = AI advisory.
  972. const noLinuxFromDeterministicText =
  973. deterministicWindowsOnly ||
  974. (deterministicWineRequired && !hasLinuxEvidence) ||
  975. (windowsBinaryHint && !hasLinuxEvidence);
  976. const noLinuxFromSteamCmd = steamCmdAssessment?.status === 'windows-only';
  977. const noLinuxFromAi =
  978. aiLinuxAssessment?.linux_support === 'no' &&
  979. (aiLinuxAssessment?.confidence === 'high' || aiLinuxAssessment?.confidence === 'medium');
  980. const confirmedNoLinux = noLinuxFromDeterministicText || noLinuxFromSteamCmd;
  981. const suggestsNoLinux = noLinuxFromAi && !confirmedNoLinux;
  982. const confirmedLinuxFromSteamCmd = steamCmdAssessment?.status === 'linux';
  983. const linuxYesFromAi =
  984. aiLinuxAssessment?.linux_support === 'yes' &&
  985. (aiLinuxAssessment?.confidence === 'high' || aiLinuxAssessment?.confidence === 'medium');
  986. const confirmedLinuxSupport =
  987. confirmedLinuxFromSteamCmd || linuxYesFromAi;
  988. // Soft positive: checkbox checked with no negative signals and no definitive server evidence.
  989. const likelySupportedByCheckbox =
  990. linuxCheckboxChecked &&
  991. !confirmedNoLinux &&
  992. !suggestsNoLinux &&
  993. !confirmedLinuxFromSteamCmd &&
  994. !linuxYesFromAi;
  995. const NO_LINUX_LABEL = 'status: no linux support';
  996. const CONFIRMED_LINUX_LABEL = 'status: linux support confirmed';
  997. const LINUX_MARKER = '<!-- linux-support-check -->';
  998. const steamDbLink = steamAppId ? `https://steamdb.info/app/${steamAppId}/` : null;
  999. let linuxLabelOverrideBy = null;
  1000. try {
  1001. const issueEvents = await github.paginate(github.rest.issues.listEvents, {
  1002. owner,
  1003. repo,
  1004. issue_number: issueNumber,
  1005. per_page: 100,
  1006. });
  1007. const lastLinuxLabelEvent = issueEvents
  1008. .filter(
  1009. (e) =>
  1010. ['labeled', 'unlabeled'].includes(e.event) &&
  1011. [NO_LINUX_LABEL, CONFIRMED_LINUX_LABEL].includes(e.label?.name)
  1012. )
  1013. .at(-1);
  1014. if (lastLinuxLabelEvent && lastLinuxLabelEvent.actor?.type !== 'Bot') {
  1015. linuxLabelOverrideBy = lastLinuxLabelEvent.actor?.login ?? 'a maintainer';
  1016. console.log(`Linux support label last set by ${linuxLabelOverrideBy}; keeping it.`);
  1017. }
  1018. } catch (err) {
  1019. console.log(`Could not read issue events: ${err.message}`);
  1020. }
  1021. const shouldApplyNoLinuxLabel = linuxLabelOverrideBy
  1022. ? existingLabels.has(NO_LINUX_LABEL)
  1023. : confirmedNoLinux || suggestsNoLinux;
  1024. const shouldApplyConfirmedLinuxLabel = linuxLabelOverrideBy
  1025. ? existingLabels.has(CONFIRMED_LINUX_LABEL) && !existingLabels.has(NO_LINUX_LABEL)
  1026. : confirmedLinuxSupport && !confirmedNoLinux && !suggestsNoLinux;
  1027. if (shouldApplyNoLinuxLabel) {
  1028. // Auto-create the label if it does not exist yet.
  1029. try {
  1030. await github.rest.issues.getLabel({ owner, repo, name: NO_LINUX_LABEL });
  1031. } catch (err) {
  1032. if (err.status === 404) {
  1033. try {
  1034. await github.rest.issues.createLabel({
  1035. owner,
  1036. repo,
  1037. name: NO_LINUX_LABEL,
  1038. color: 'd73a4a',
  1039. description: 'Game server does not have confirmed native Linux support',
  1040. });
  1041. } catch (createErr) {
  1042. console.log(`Could not create label "${NO_LINUX_LABEL}": ${createErr.message}`);
  1043. }
  1044. }
  1045. }
  1046. if (!existingLabels.has(NO_LINUX_LABEL)) {
  1047. try {
  1048. await github.rest.issues.addLabels({ owner, repo, issue_number: issueNumber, labels: [NO_LINUX_LABEL] });
  1049. console.log(`Added label: ${NO_LINUX_LABEL}`);
  1050. } catch (err) {
  1051. console.log(`Could not add label "${NO_LINUX_LABEL}": ${err.message}`);
  1052. }
  1053. }
  1054. if (existingLabels.has(CONFIRMED_LINUX_LABEL)) {
  1055. try {
  1056. await github.rest.issues.removeLabel({ owner, repo, issue_number: issueNumber, name: CONFIRMED_LINUX_LABEL });
  1057. console.log(`Removed label: ${CONFIRMED_LINUX_LABEL}`);
  1058. } catch (err) {
  1059. console.log(`Could not remove label "${CONFIRMED_LINUX_LABEL}": ${err.message}`);
  1060. }
  1061. }
  1062. } else if (existingLabels.has(NO_LINUX_LABEL)) {
  1063. try {
  1064. await github.rest.issues.removeLabel({ owner, repo, issue_number: issueNumber, name: NO_LINUX_LABEL });
  1065. console.log(`Removed label: ${NO_LINUX_LABEL}`);
  1066. } catch (err) {
  1067. console.log(`Could not remove label "${NO_LINUX_LABEL}": ${err.message}`);
  1068. }
  1069. }
  1070. if (shouldApplyConfirmedLinuxLabel) {
  1071. try {
  1072. await github.rest.issues.getLabel({ owner, repo, name: CONFIRMED_LINUX_LABEL });
  1073. } catch (err) {
  1074. if (err.status === 404) {
  1075. try {
  1076. await github.rest.issues.createLabel({
  1077. owner,
  1078. repo,
  1079. name: CONFIRMED_LINUX_LABEL,
  1080. color: '0e8a16',
  1081. description: 'Game server has confirmed native Linux support',
  1082. });
  1083. } catch (createErr) {
  1084. console.log(`Could not create label "${CONFIRMED_LINUX_LABEL}": ${createErr.message}`);
  1085. }
  1086. }
  1087. }
  1088. if (!existingLabels.has(CONFIRMED_LINUX_LABEL)) {
  1089. try {
  1090. await github.rest.issues.addLabels({ owner, repo, issue_number: issueNumber, labels: [CONFIRMED_LINUX_LABEL] });
  1091. console.log(`Added label: ${CONFIRMED_LINUX_LABEL}`);
  1092. } catch (err) {
  1093. console.log(`Could not add label "${CONFIRMED_LINUX_LABEL}": ${err.message}`);
  1094. }
  1095. }
  1096. } else if (existingLabels.has(CONFIRMED_LINUX_LABEL)) {
  1097. try {
  1098. await github.rest.issues.removeLabel({ owner, repo, issue_number: issueNumber, name: CONFIRMED_LINUX_LABEL });
  1099. console.log(`Removed label: ${CONFIRMED_LINUX_LABEL}`);
  1100. } catch (err) {
  1101. console.log(`Could not remove label "${CONFIRMED_LINUX_LABEL}": ${err.message}`);
  1102. }
  1103. }
  1104. const reasons = [];
  1105. if (deterministicWindowsOnly) reasons.push('the provided docs/guides explicitly indicate Windows-only or no Linux support');
  1106. if (deterministicWineRequired && !hasLinuxEvidence) reasons.push('the provided docs/guides indicate a Wine/Proton requirement rather than native Linux binaries');
  1107. if (windowsBinaryHint && !hasLinuxEvidence) reasons.push('the provided evidence appears to reference Windows binaries (.exe) without clear Linux server evidence');
  1108. if (isSteamNo) reasons.push('request is marked as non-Steam, so Steam platform checks were intentionally skipped');
  1109. if (steamAppIsServerTool) reasons.push(`AppID ${steamAppId} has no Steam store page (typical for dedicated server tool AppIDs)`);
  1110. if (noLinuxFromSteamCmd && steamCmdAssessment?.reason) reasons.push(steamCmdAssessment.reason);
  1111. if (confirmedLinuxFromSteamCmd && steamCmdAssessment?.reason) reasons.push(steamCmdAssessment.reason);
  1112. if (steamCmdAssessment?.status === 'unknown' && steamCmdAssessment?.reason) reasons.push(steamCmdAssessment.reason);
  1113. if (steamCmdAssessment?.status === 'error' && steamCmdAssessment?.reason) reasons.push(steamCmdAssessment.reason);
  1114. if (noLinuxFromAi && aiLinuxAssessment?.reason) reasons.push(`AI analysis of provided documentation: ${aiLinuxAssessment.reason}`);
  1115. if (linuxYesFromAi && aiLinuxAssessment?.reason) reasons.push(`AI analysis indicates Linux support: ${aiLinuxAssessment.reason}`);
  1116. if (likelySupportedByCheckbox) reasons.push('requester confirmed Linux support via the form checkbox; no contradicting evidence found');
  1117. let verdictLine = 'Linux support could not be confirmed automatically from the submitted details.';
  1118. if (linuxLabelOverrideBy && shouldApplyNoLinuxLabel) {
  1119. verdictLine = 'A maintainer has confirmed this server has no native Linux support.';
  1120. } else if (linuxLabelOverrideBy && shouldApplyConfirmedLinuxLabel) {
  1121. verdictLine = 'A maintainer has confirmed native Linux support.';
  1122. } else if (confirmedNoLinux) {
  1123. verdictLine = 'This server request does **not** appear to have native Linux support, which is required for LinuxGSM.';
  1124. } else if (suggestsNoLinux) {
  1125. verdictLine = 'This server request **may not** have native Linux support based on submitted evidence.';
  1126. } else if (confirmedLinuxFromSteamCmd) {
  1127. verdictLine = 'SteamCMD metadata indicates this server has Linux platform/depot support.';
  1128. } else if (linuxYesFromAi) {
  1129. verdictLine = 'Submitted documentation appears to indicate Linux server support.';
  1130. } else if (likelySupportedByCheckbox) {
  1131. verdictLine = 'Linux support is **likely** — the requester confirmed it and no contradicting evidence was found. A maintainer should verify before accepting.';
  1132. }
  1133. const steamApiStatus = isSteamNo
  1134. ? 'Not applicable'
  1135. : steamLinuxSupport === true
  1136. ? 'Client app marked Linux-supported (informational only)'
  1137. : steamLinuxSupport === false
  1138. ? 'Client app marked Linux-unsupported (informational only)'
  1139. : steamAppIsServerTool
  1140. ? 'No store page for this AppID (informational only)'
  1141. : 'No definitive platform response';
  1142. const steamCmdStatus = isSteamNo
  1143. ? 'Not applicable'
  1144. : !steamAppId
  1145. ? 'Skipped until valid AppID is provided'
  1146. : steamCmdAssessment?.status === 'linux'
  1147. ? 'Linux platform/depot metadata found'
  1148. : steamCmdAssessment?.status === 'windows-only'
  1149. ? 'Windows-only platform metadata found'
  1150. : steamCmdAssessment?.status === 'unknown'
  1151. ? 'No clear Linux server metadata found'
  1152. : steamCmdAssessment?.status === 'error'
  1153. ? 'Lookup failed'
  1154. : 'Not run';
  1155. const steamBlock = isSteamNo
  1156. ? '**Steam:** No (non-Steam request)\n**Steam Store API:** Not applicable\n\n'
  1157. : steamAppId
  1158. ? `**Steam:** ${isSteamYes ? 'Yes' : 'Unspecified'}\n` +
  1159. `**Steam AppID:** ${steamAppId}\n` +
  1160. `**Steam Store API:** ${steamApiStatus}\n` +
  1161. `**SteamCMD:** ${steamCmdStatus}\n` +
  1162. `**SteamDB:** ${steamDbLink}\n\n`
  1163. : `**Steam:** ${isSteamYes ? 'Yes' : 'Unspecified'}\n` +
  1164. '**Steam AppID:** Not provided in the issue form.\n' +
  1165. (isSteamYes ? '**Steam Store API:** Skipped until valid AppID is provided.\n**SteamCMD:** Skipped until valid AppID is provided.\n\n' : '\n');
  1166. const linuxCommentHeader = shouldApplyConfirmedLinuxLabel
  1167. ? '**Linux Support Check** :rocket:'
  1168. : '**Linux Support Check**';
  1169. const confirmedLinuxLabelBlock = shouldApplyConfirmedLinuxLabel
  1170. ? `**Label applied:** ${CONFIRMED_LINUX_LABEL}\n\n`
  1171. : '';
  1172. const overrideBlock = linuxLabelOverrideBy
  1173. ? `**Maintainer override:** the Linux support label was set manually by @${linuxLabelOverrideBy} and is no longer changed automatically.\n\n`
  1174. : '';
  1175. const linuxCommentBody =
  1176. `${LINUX_MARKER}\n` +
  1177. `${linuxCommentHeader}\n\n` +
  1178. `${overrideBlock}` +
  1179. `${verdictLine}\n\n` +
  1180. `${confirmedLinuxLabelBlock}` +
  1181. `${steamBlock}` +
  1182. (reasons.length > 0
  1183. ? `**Evidence:**\n${reasons.map((r) => `- ${r}`).join('\n')}\n\n`
  1184. : '') +
  1185. `LinuxGSM only supports **native Linux dedicated servers**. Wine and Windows-only servers are not supported.\n\n` +
  1186. `If support is unclear, please provide:\n` +
  1187. `- Official Linux dedicated server documentation\n` +
  1188. `- Linux server binaries or release notes\n` +
  1189. `- Linux startup instructions or commands\n\n` +
  1190. `_This check was performed automatically using SteamCMD, submitted issue details, and AI assistance for document interpretation. Steam store data is shown only as client-app context and is not used to determine server support._`;
  1191. try {
  1192. const allComments = await github.paginate(github.rest.issues.listComments, {
  1193. owner,
  1194. repo,
  1195. issue_number: issueNumber,
  1196. per_page: 100,
  1197. });
  1198. const existingLinuxComment = [...allComments].reverse().find(
  1199. (c) => c.user?.type === 'Bot' && c.body?.includes(LINUX_MARKER)
  1200. );
  1201. if (existingLinuxComment) {
  1202. await github.rest.issues.updateComment({
  1203. owner,
  1204. repo,
  1205. comment_id: existingLinuxComment.id,
  1206. body: linuxCommentBody,
  1207. });
  1208. } else {
  1209. await github.rest.issues.createComment({
  1210. owner,
  1211. repo,
  1212. issue_number: issueNumber,
  1213. body: linuxCommentBody,
  1214. });
  1215. }
  1216. } catch (err) {
  1217. console.log(`Could not post Linux support comment: ${err.message}`);
  1218. }
  1219. }
  1220. issue-potential-duplicates:
  1221. if: github.repository_owner == 'GameServerManagers' && github.event_name == 'issues' && (github.event.action == 'opened' || github.event.action == 'edited' || github.event.action == 'reopened')
  1222. runs-on: ubuntu-latest
  1223. steps:
  1224. - name: Detect potential duplicates
  1225. uses: actions/github-script@v9
  1226. with:
  1227. script: |
  1228. const owner = context.repo.owner;
  1229. const repo = context.repo.repo;
  1230. const issueNumber = context.payload.issue?.number;
  1231. const DUPLICATE_LABEL = 'potential-duplicate';
  1232. const DUPLICATE_MARKER = '<!-- potential-duplicate-check -->';
  1233. const MAX_CANDIDATES = 5;
  1234. const THRESHOLD = 0.45;
  1235. if (!issueNumber) {
  1236. console.log('No issue number found in payload.');
  1237. return;
  1238. }
  1239. const issueResp = await github.rest.issues.get({
  1240. owner,
  1241. repo,
  1242. issue_number: issueNumber,
  1243. });
  1244. const issue = issueResp.data;
  1245. if (issue.pull_request) {
  1246. console.log('Skipping pull request payload.');
  1247. return;
  1248. }
  1249. function normalizeText(value) {
  1250. return (value || '')
  1251. .toLowerCase()
  1252. .replace(/[`'"’]/g, '')
  1253. .replace(/[^a-z0-9\s]/g, ' ')
  1254. .replace(/\s+/g, ' ')
  1255. .trim();
  1256. }
  1257. function tokenize(value) {
  1258. const stopwords = new Set([
  1259. 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'how', 'i', 'in', 'is', 'it', 'its',
  1260. 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'when', 'with', 'wont', 'cannot', 'cant', 'fails', 'fail',
  1261. 'issue', 'bug', 'request', 'server', 'command', 'linuxgsm'
  1262. ]);
  1263. return new Set(
  1264. normalizeText(value)
  1265. .split(' ')
  1266. .filter((token) => token.length > 2 && !stopwords.has(token))
  1267. );
  1268. }
  1269. function jaccard(aSet, bSet) {
  1270. if (aSet.size === 0 || bSet.size === 0) return 0;
  1271. let intersection = 0;
  1272. for (const v of aSet) {
  1273. if (bSet.has(v)) intersection += 1;
  1274. }
  1275. const union = new Set([...aSet, ...bSet]).size;
  1276. return union === 0 ? 0 : intersection / union;
  1277. }
  1278. function bodySignature(text) {
  1279. return normalizeText(text).split(' ').slice(0, 200).join(' ');
  1280. }
  1281. const currentTitleTokens = tokenize(issue.title || '');
  1282. const currentBodyTokens = tokenize(bodySignature(issue.body || ''));
  1283. const recentIssues = await github.paginate(github.rest.issues.listForRepo, {
  1284. owner,
  1285. repo,
  1286. state: 'all',
  1287. sort: 'updated',
  1288. direction: 'desc',
  1289. per_page: 100,
  1290. });
  1291. const ranked = [];
  1292. for (const candidate of recentIssues) {
  1293. if (!candidate || candidate.number === issueNumber || candidate.pull_request) continue;
  1294. const candidateTitleTokens = tokenize(candidate.title || '');
  1295. const candidateBodyTokens = tokenize(bodySignature(candidate.body || ''));
  1296. const titleScore = jaccard(currentTitleTokens, candidateTitleTokens);
  1297. const bodyScore = jaccard(currentBodyTokens, candidateBodyTokens);
  1298. const score = titleScore * 0.8 + bodyScore * 0.2;
  1299. if (score < THRESHOLD) continue;
  1300. ranked.push({
  1301. number: candidate.number,
  1302. title: candidate.title,
  1303. state: candidate.state,
  1304. html_url: candidate.html_url,
  1305. score,
  1306. });
  1307. }
  1308. ranked.sort((a, b) => b.score - a.score);
  1309. const topMatches = ranked.slice(0, MAX_CANDIDATES);
  1310. async function ensurePotentialDuplicateLabel() {
  1311. try {
  1312. await github.rest.issues.getLabel({ owner, repo, name: DUPLICATE_LABEL });
  1313. } catch (err) {
  1314. if (err.status !== 404) throw err;
  1315. await github.rest.issues.createLabel({
  1316. owner,
  1317. repo,
  1318. name: DUPLICATE_LABEL,
  1319. color: 'd4c5f9',
  1320. description: 'Potentially duplicates another existing issue',
  1321. });
  1322. }
  1323. }
  1324. const existingLabelNames = new Set((issue.labels || []).map((l) => l.name));
  1325. const comments = await github.paginate(github.rest.issues.listComments, {
  1326. owner,
  1327. repo,
  1328. issue_number: issueNumber,
  1329. per_page: 100,
  1330. });
  1331. const existingComment = [...comments]
  1332. .reverse()
  1333. .find((comment) => comment.user?.type === 'Bot' && comment.body?.includes(DUPLICATE_MARKER));
  1334. if (topMatches.length === 0) {
  1335. if (existingLabelNames.has(DUPLICATE_LABEL)) {
  1336. try {
  1337. await github.rest.issues.removeLabel({
  1338. owner,
  1339. repo,
  1340. issue_number: issueNumber,
  1341. name: DUPLICATE_LABEL,
  1342. });
  1343. } catch (err) {
  1344. console.log(`Could not remove ${DUPLICATE_LABEL}: ${err.message}`);
  1345. }
  1346. }
  1347. if (existingComment) {
  1348. try {
  1349. await github.rest.issues.updateComment({
  1350. owner,
  1351. repo,
  1352. comment_id: existingComment.id,
  1353. body:
  1354. `${DUPLICATE_MARKER}\n` +
  1355. `Potential duplicate scan did not find strong matches at this time.\n\n` +
  1356. `_This note is maintained automatically._`,
  1357. });
  1358. } catch (err) {
  1359. console.log(`Could not update duplicate comment: ${err.message}`);
  1360. }
  1361. }
  1362. return;
  1363. }
  1364. await ensurePotentialDuplicateLabel();
  1365. if (!existingLabelNames.has(DUPLICATE_LABEL)) {
  1366. try {
  1367. await github.rest.issues.addLabels({
  1368. owner,
  1369. repo,
  1370. issue_number: issueNumber,
  1371. labels: [DUPLICATE_LABEL],
  1372. });
  1373. } catch (err) {
  1374. console.log(`Could not add ${DUPLICATE_LABEL}: ${err.message}`);
  1375. }
  1376. }
  1377. const lines = topMatches
  1378. .map((m) => `- #${m.number} (${Math.round(m.score * 100)}%) ${m.title}`)
  1379. .join('\n');
  1380. const commentBody =
  1381. `${DUPLICATE_MARKER}\n` +
  1382. `Potential duplicates:\n${lines}\n\n` +
  1383. `_This note is generated automatically using repository issue similarity and may include false positives._`;
  1384. if (existingComment) {
  1385. await github.rest.issues.updateComment({
  1386. owner,
  1387. repo,
  1388. comment_id: existingComment.id,
  1389. body: commentBody,
  1390. });
  1391. } else {
  1392. await github.rest.issues.createComment({
  1393. owner,
  1394. repo,
  1395. issue_number: issueNumber,
  1396. body: commentBody,
  1397. });
  1398. }
  1399. backfill-relabel:
  1400. if: github.repository_owner == 'GameServerManagers' && github.event_name == 'workflow_dispatch'
  1401. runs-on: ubuntu-latest
  1402. env:
  1403. ISSUE_STATE: ${{ inputs.issue_state }}
  1404. ISSUE_LIMIT: ${{ inputs.limit }}
  1405. AI_GAME_FALLBACK: ${{ inputs.ai_game_fallback }}
  1406. steps:
  1407. - name: Trigger relabel backfill
  1408. uses: actions/github-script@v9
  1409. env:
  1410. GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  1411. with:
  1412. script: |
  1413. const owner = context.repo.owner;
  1414. const repo = context.repo.repo;
  1415. const state = process.env.ISSUE_STATE || 'all';
  1416. const rawLimit = Number.parseInt(process.env.ISSUE_LIMIT || '0', 10);
  1417. const limit = Number.isFinite(rawLimit) && rawLimit > 0 ? rawLimit : 0;
  1418. const useAiGameFallback = String(process.env.AI_GAME_FALLBACK || 'false').toLowerCase() === 'true';
  1419. const processedIssues = [];
  1420. const failedIssues = [];
  1421. let aiGameAttempts = 0;
  1422. let aiGameMatches = 0;
  1423. let aiGameRateLimited = 0;
  1424. let aiFallbackDisabledReason = '';
  1425. let stoppedForApiRateLimit = false;
  1426. let apiRateLimitStopReason = '';
  1427. // === Helpers (mirrored from issue-ai-maintenance) ===
  1428. function normalizeName(value) {
  1429. return (value || '')
  1430. .toLowerCase()
  1431. .replace(/[''`]/g, '')
  1432. .replace(/[^a-z0-9]+/g, ' ')
  1433. .trim();
  1434. }
  1435. function parseGameCandidates(gameField) {
  1436. if (!gameField || /^_?no response_?$/i.test(gameField)) return [];
  1437. return gameField
  1438. .replace(/\(.*?\)/g, ' ')
  1439. .split(/\n|,|\s+&\s+|\s+and\s+|\//i)
  1440. .map((v) => v.trim())
  1441. .filter(Boolean);
  1442. }
  1443. function findGamesFromText(text, gameAliasToLabel, gameAliasToScript) {
  1444. const labels = new Set();
  1445. const scripts = new Set();
  1446. const normalizedText = normalizeName(text);
  1447. if (!normalizedText) return { labels, scripts };
  1448. const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  1449. const aliases = [];
  1450. for (const [alias, label] of gameAliasToLabel.entries()) {
  1451. if (alias.length < 3) continue;
  1452. aliases.push({ alias, label, script: gameAliasToScript.get(alias) || null });
  1453. }
  1454. // Prefer longer aliases first so "killing floor 2" does not also match "killing floor".
  1455. aliases.sort((a, b) => b.alias.length - a.alias.length);
  1456. const usedRanges = [];
  1457. const isOverlapping = (start, end) =>
  1458. usedRanges.some((range) => start < range.end && end > range.start);
  1459. for (const entry of aliases) {
  1460. const pattern = new RegExp(`\\b${escapeRegex(entry.alias).replace(/\\ /g, '\\s+')}\\b`, 'g');
  1461. let match;
  1462. while ((match = pattern.exec(normalizedText)) !== null) {
  1463. const start = match.index;
  1464. const end = start + match[0].length;
  1465. if (isOverlapping(start, end)) continue;
  1466. labels.add(entry.label);
  1467. if (entry.script) scripts.add(entry.script);
  1468. usedRanges.push({ start, end });
  1469. }
  1470. }
  1471. return { labels, scripts };
  1472. }
  1473. function parseAiGameResponse(raw) {
  1474. const input = (raw || '').trim();
  1475. if (!input) return {};
  1476. const candidates = [input];
  1477. const fenced = input.match(/```(?:json)?\s*([\s\S]*?)```/i);
  1478. if (fenced?.[1]) candidates.push(fenced[1].trim());
  1479. const firstBrace = input.indexOf('{');
  1480. const lastBrace = input.lastIndexOf('}');
  1481. if (firstBrace !== -1 && lastBrace > firstBrace) {
  1482. candidates.push(input.slice(firstBrace, lastBrace + 1));
  1483. }
  1484. for (const candidate of candidates) {
  1485. try {
  1486. return JSON.parse(candidate);
  1487. } catch (_err) {
  1488. // Continue trying fallbacks.
  1489. }
  1490. }
  1491. return {};
  1492. }
  1493. function isGenericNonGameDetection(value) {
  1494. const normalized = normalizeName(value);
  1495. if (!normalized) return false;
  1496. return [
  1497. 'srcds',
  1498. 'source dedicated server',
  1499. 'dedicated server',
  1500. 'source engine',
  1501. 'goldsrc',
  1502. 'steamcmd',
  1503. 'linuxgsm',
  1504. 'lgsm',
  1505. ].some((term) => normalized.includes(term));
  1506. }
  1507. function parseAiRateLimitInfo(response) {
  1508. const retryAfter = response.headers.get('retry-after') || response.headers.get('Retry-After') || '';
  1509. const limit = response.headers.get('x-ratelimit-limit') || '';
  1510. const remaining = response.headers.get('x-ratelimit-remaining') || '';
  1511. const resetEpoch = response.headers.get('x-ratelimit-reset') || '';
  1512. const requestId = response.headers.get('x-github-request-id') || '';
  1513. let resetIso = '';
  1514. const parsedReset = Number.parseInt(resetEpoch, 10);
  1515. if (Number.isFinite(parsedReset) && parsedReset > 0) {
  1516. resetIso = new Date(parsedReset * 1000).toISOString();
  1517. }
  1518. return {
  1519. retryAfter,
  1520. limit,
  1521. remaining,
  1522. resetEpoch,
  1523. resetIso,
  1524. requestId,
  1525. };
  1526. }
  1527. function formatAiRateLimitInfo(info) {
  1528. const parts = [];
  1529. if (info.retryAfter) parts.push(`retry-after=${info.retryAfter}s`);
  1530. if (info.limit) parts.push(`limit=${info.limit}`);
  1531. if (info.remaining) parts.push(`remaining=${info.remaining}`);
  1532. if (info.resetEpoch) parts.push(`reset=${info.resetEpoch}${info.resetIso ? ` (${info.resetIso})` : ''}`);
  1533. if (info.requestId) parts.push(`request-id=${info.requestId}`);
  1534. return parts.length > 0 ? parts.join(', ') : 'no rate-limit headers returned';
  1535. }
  1536. function isApiRateLimitError(err) {
  1537. const message = String(err?.message || '').toLowerCase();
  1538. return (
  1539. err?.status === 429 ||
  1540. message.includes('api rate limit exceeded') ||
  1541. message.includes('secondary rate limit') ||
  1542. (message.includes('rate limit') && err?.status === 403)
  1543. );
  1544. }
  1545. function formatApiRateLimitError(err) {
  1546. const headers = err?.response?.headers || err?.headers || {};
  1547. const limit = headers['x-ratelimit-limit'] || '';
  1548. const remaining = headers['x-ratelimit-remaining'] || '';
  1549. const resetEpoch = headers['x-ratelimit-reset'] || '';
  1550. const requestId = headers['x-github-request-id'] || '';
  1551. let resetIso = '';
  1552. const parsedReset = Number.parseInt(resetEpoch || '', 10);
  1553. if (Number.isFinite(parsedReset) && parsedReset > 0) {
  1554. resetIso = new Date(parsedReset * 1000).toISOString();
  1555. }
  1556. const parts = [];
  1557. if (limit) parts.push(`limit=${limit}`);
  1558. if (remaining) parts.push(`remaining=${remaining}`);
  1559. if (resetEpoch) parts.push(`reset=${resetEpoch}${resetIso ? ` (${resetIso})` : ''}`);
  1560. if (requestId) parts.push(`request-id=${requestId}`);
  1561. return parts.length > 0 ? parts.join(', ') : 'no rate-limit headers returned';
  1562. }
  1563. function hasAliasHitForLabel(text, targetLabel, gameAliasToLabel) {
  1564. const normalizedText = normalizeName(text);
  1565. if (!normalizedText || !targetLabel) return false;
  1566. const paddedText = ` ${normalizedText} `;
  1567. for (const [alias, label] of gameAliasToLabel.entries()) {
  1568. if (label !== targetLabel) continue;
  1569. if (alias.length < 3) continue;
  1570. if (paddedText.includes(` ${alias} `)) return true;
  1571. // Allow obvious joined-word variants for multi-token aliases
  1572. // (e.g., "counter strike 1 6" matching "counterstrike 1.6").
  1573. const aliasTokens = alias.split(/\s+/).filter(Boolean);
  1574. if (aliasTokens.length > 1) {
  1575. const escapedTokens = aliasTokens.map((token) =>
  1576. token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  1577. );
  1578. const flexibleAliasPattern = new RegExp(`\\b${escapedTokens.join('\\s*')}\\b`);
  1579. if (flexibleAliasPattern.test(normalizedText)) return true;
  1580. }
  1581. }
  1582. return false;
  1583. }
  1584. function parseServerlistCsv(csvText) {
  1585. const rows = [];
  1586. const lines = (csvText || '').split(/\r?\n/);
  1587. for (let i = 1; i < lines.length; i += 1) {
  1588. const line = lines[i]?.trim();
  1589. if (!line) continue;
  1590. const parts = line.split(',');
  1591. if (parts.length < 3) continue;
  1592. rows.push({
  1593. shortname: parts[0].trim(),
  1594. gameservername: parts[1].trim(),
  1595. gamename: parts[2].trim(),
  1596. });
  1597. }
  1598. return rows;
  1599. }
  1600. function inferTypeFromTitle(issueTitle) {
  1601. if (/^\[bug\]/i.test(issueTitle)) return 'type: bug';
  1602. if (/\bserver\s+request\b/i.test(issueTitle)) return 'type: game server request';
  1603. const hasBracketPrefix = /^\[[^\]]+\]/.test(issueTitle || '');
  1604. const isServerCreation =
  1605. /\bserver\s+creation\b/i.test(issueTitle) ||
  1606. (hasBracketPrefix && /\bcreation\b/i.test(issueTitle));
  1607. const isServerSupportRequest =
  1608. /\bserver\s+support\b/i.test(issueTitle) ||
  1609. (/\bsupport\s+for\b/i.test(issueTitle) && /\bserver\b/i.test(issueTitle));
  1610. if (isServerCreation || isServerSupportRequest) return 'type: game server request';
  1611. if (/^\[feature\]/i.test(issueTitle)) return 'type: feature';
  1612. if (/^\[server request\]/i.test(issueTitle)) return 'type: game server request';
  1613. if (/^\[docs?\]/i.test(issueTitle)) return 'type: docs';
  1614. return null;
  1615. }
  1616. function inferDesiredType(issueTitle, labelNames) {
  1617. const titleType = inferTypeFromTitle(issueTitle);
  1618. if (titleType) return titleType;
  1619. // Prefer server requests over generic feature when both labels exist.
  1620. if (labelNames.has('type: game server request')) return 'type: game server request';
  1621. for (const label of [
  1622. 'type: bug',
  1623. 'type: feature',
  1624. 'type: game server request',
  1625. 'type: docs',
  1626. ]) {
  1627. if (labelNames.has(label)) return label;
  1628. }
  1629. return null;
  1630. }
  1631. function inferIssueTypeNameFromDesiredType(typeLabel) {
  1632. if (typeLabel === 'type: bug') return 'Bug';
  1633. if (typeLabel === 'type: feature') return 'Feature';
  1634. if (typeLabel === 'type: game server request') return 'Server Request';
  1635. if (typeLabel === 'type: docs') return 'Task';
  1636. return null;
  1637. }
  1638. function parseCommandSelections(sectionValue) {
  1639. const selected = new Set();
  1640. const re = /command:\s*([a-z-]+)/gi;
  1641. let m;
  1642. while ((m = re.exec(sectionValue || '')) !== null) {
  1643. let value = m[1].toLowerCase();
  1644. if (value.startsWith('mods-')) value = 'mods';
  1645. if (value === 'auto-update') value = 'update';
  1646. selected.add(`command: ${value}`);
  1647. }
  1648. return selected;
  1649. }
  1650. function parseDistroSelections(sectionValue) {
  1651. const text = sectionValue || '';
  1652. const selected = new Set();
  1653. if (/\bUbuntu\b/i.test(text)) selected.add('distro: Ubuntu');
  1654. if (/\bDebian\b/i.test(text)) selected.add('distro: Debian');
  1655. if (/\bAlmaLinux\b/i.test(text)) selected.add('distro: AlmaLinux');
  1656. if (/\bRocky\b/i.test(text)) selected.add('distro: Rocky Linux');
  1657. if (/\bCentOS\b/i.test(text)) selected.add('distro: CentOS');
  1658. if (/\bFedora\b/i.test(text)) selected.add('distro: Fedora');
  1659. if (/\bopenSUSE\b/i.test(text)) selected.add('distro: openSUSE');
  1660. if (/\bArch Linux\b/i.test(text)) selected.add('distro: Arch Linux');
  1661. if (/\bSlackware\b/i.test(text)) selected.add('distro: Slackware');
  1662. return selected;
  1663. }
  1664. function extractSection(body, sectionName) {
  1665. const escaped = sectionName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  1666. const re = new RegExp(`### ${escaped}\\n\\n([\\s\\S]*?)(\\n### |$)`, 'i');
  1667. return (body.match(re)?.[1] || '').trim();
  1668. }
  1669. // === Load shared data once ===
  1670. const repoLabels = await github.paginate(github.rest.issues.listLabelsForRepo, {
  1671. owner,
  1672. repo,
  1673. per_page: 100,
  1674. });
  1675. const gameLabelByNormalized = new Map();
  1676. for (const label of repoLabels) {
  1677. if (!label.name.startsWith('game: ')) continue;
  1678. gameLabelByNormalized.set(normalizeName(label.name.slice(6)), label.name);
  1679. }
  1680. const existingEngineLabels = new Set(
  1681. repoLabels.map((l) => l.name).filter((name) => name.startsWith('engine: '))
  1682. );
  1683. const gameAliasToLabel = new Map();
  1684. const gameAliasToScript = new Map();
  1685. const engineByScript = new Map();
  1686. for (const [normalizedGameName, label] of gameLabelByNormalized.entries()) {
  1687. gameAliasToLabel.set(normalizedGameName, label);
  1688. }
  1689. try {
  1690. const serverlistContent = await github.rest.repos.getContent({
  1691. owner,
  1692. repo,
  1693. path: 'lgsm/data/serverlist.csv',
  1694. });
  1695. const csvText = Buffer.from(serverlistContent.data?.content || '', 'base64').toString('utf8');
  1696. const serverRows = parseServerlistCsv(csvText);
  1697. for (const row of serverRows) {
  1698. const canonicalLabel = gameLabelByNormalized.get(normalizeName(row.gamename));
  1699. if (!canonicalLabel) continue;
  1700. for (const alias of [row.shortname, row.gameservername, row.gamename]) {
  1701. const key = normalizeName(alias);
  1702. if (!key) continue;
  1703. gameAliasToLabel.set(key, canonicalLabel);
  1704. gameAliasToScript.set(key, row.gameservername);
  1705. }
  1706. }
  1707. } catch (err) {
  1708. console.log(`Could not load serverlist aliases: ${err.message}`);
  1709. }
  1710. async function ensureEngineLabel(engineLabel) {
  1711. if (existingEngineLabels.has(engineLabel)) return;
  1712. try {
  1713. await github.rest.issues.createLabel({
  1714. owner,
  1715. repo,
  1716. name: engineLabel,
  1717. color: '000000',
  1718. description: `Issues related to ${engineLabel.slice(8)} engine`,
  1719. });
  1720. existingEngineLabels.add(engineLabel);
  1721. } catch (err) {
  1722. if (err.status === 422) {
  1723. existingEngineLabels.add(engineLabel);
  1724. return;
  1725. }
  1726. console.log(`Could not create engine label "${engineLabel}": ${err.message}`);
  1727. }
  1728. }
  1729. async function getEngineForScript(scriptName) {
  1730. if (!scriptName) return null;
  1731. if (engineByScript.has(scriptName)) return engineByScript.get(scriptName);
  1732. try {
  1733. const cfgContent = await github.rest.repos.getContent({
  1734. owner,
  1735. repo,
  1736. path: `lgsm/config-default/config-lgsm/${scriptName}/_default.cfg`,
  1737. });
  1738. const cfgText = Buffer.from(cfgContent.data?.content || '', 'base64').toString('utf8');
  1739. const engine = cfgText.match(/^engine="([^"]+)"/m)?.[1] || null;
  1740. engineByScript.set(scriptName, engine);
  1741. return engine;
  1742. } catch (_err) {
  1743. engineByScript.set(scriptName, null);
  1744. return null;
  1745. }
  1746. }
  1747. // === Process issues ===
  1748. const issues = await github.paginate(github.rest.issues.listForRepo, {
  1749. owner,
  1750. repo,
  1751. state,
  1752. sort: 'created',
  1753. direction: 'asc',
  1754. per_page: 100,
  1755. });
  1756. const targets = issues.filter((issue) => !issue.pull_request);
  1757. const selectedTargets = limit > 0 ? targets.slice(0, limit) : targets;
  1758. console.log(
  1759. `Starting relabel backfill for ${selectedTargets.length} issue(s) ` +
  1760. `(state=${state}, limit=${limit === 0 ? 'all' : limit}).`
  1761. );
  1762. let processed = 0;
  1763. for (const rawIssue of selectedTargets) {
  1764. if (stoppedForApiRateLimit) break;
  1765. console.log(`Processing issue #${rawIssue.number}: ${rawIssue.title}`);
  1766. try {
  1767. const issueResp = await github.rest.issues.get({
  1768. owner,
  1769. repo,
  1770. issue_number: rawIssue.number,
  1771. });
  1772. const issue = issueResp.data;
  1773. const title = issue.title || '';
  1774. const body = issue.body || '';
  1775. const existingLabels = new Set((issue.labels || []).map((l) => l.name).filter(Boolean));
  1776. const labelsToAdd = new Set();
  1777. const labelsToRemove = new Set();
  1778. const isLocked = issue.locked === true;
  1779. let issueTypeSet = null;
  1780. // Type reconciliation
  1781. const desiredType = inferDesiredType(title, existingLabels);
  1782. if (desiredType) {
  1783. labelsToAdd.add(desiredType);
  1784. for (const label of existingLabels) {
  1785. if (label.startsWith('type: ') && label !== desiredType) labelsToRemove.add(label);
  1786. }
  1787. const desiredIssueTypeName = inferIssueTypeNameFromDesiredType(desiredType);
  1788. if (desiredIssueTypeName) {
  1789. try {
  1790. const issueTypeData = await github.graphql(
  1791. `query($owner:String!,$repo:String!,$number:Int!){
  1792. repository(owner:$owner,name:$repo){
  1793. issueTypes(first:20){ nodes { id name } }
  1794. issue(number:$number){ id issueType { id name } }
  1795. }
  1796. }`,
  1797. { owner, repo, number: rawIssue.number }
  1798. );
  1799. const issueNode = issueTypeData.repository?.issue;
  1800. const issueTypes = issueTypeData.repository?.issueTypes?.nodes || [];
  1801. const desiredIssueType = issueTypes.find((t) => t.name === desiredIssueTypeName);
  1802. if (
  1803. issueNode?.id &&
  1804. desiredIssueType?.id &&
  1805. issueNode.issueType?.id !== desiredIssueType.id
  1806. ) {
  1807. await github.graphql(
  1808. `mutation($id:ID!,$issueTypeId:ID!){
  1809. updateIssue(input:{id:$id,issueTypeId:$issueTypeId}){
  1810. issue { id number issueType { id name } }
  1811. }
  1812. }`,
  1813. { id: issueNode.id, issueTypeId: desiredIssueType.id }
  1814. );
  1815. issueTypeSet = desiredIssueTypeName;
  1816. console.log(`#${rawIssue.number}: set Issue Type to ${desiredIssueTypeName}`);
  1817. }
  1818. } catch (err) {
  1819. if (isApiRateLimitError(err)) throw err;
  1820. console.log(`#${rawIssue.number}: could not sync Issue Type: ${err.message}`);
  1821. }
  1822. }
  1823. }
  1824. // Commands
  1825. const commandSection = extractSection(body, 'Command');
  1826. const desiredCommands = parseCommandSelections(commandSection);
  1827. if (desiredCommands.size > 0) {
  1828. for (const label of desiredCommands) labelsToAdd.add(label);
  1829. for (const label of existingLabels) {
  1830. if (label.startsWith('command: ') && !desiredCommands.has(label)) labelsToRemove.add(label);
  1831. }
  1832. }
  1833. // Distros
  1834. const distroSection = extractSection(body, 'Linux distro');
  1835. const desiredDistros = parseDistroSelections(distroSection);
  1836. if (desiredDistros.size > 0) {
  1837. for (const label of desiredDistros) labelsToAdd.add(label);
  1838. for (const label of existingLabels) {
  1839. if (label.startsWith('distro: ') && !desiredDistros.has(label)) labelsToRemove.add(label);
  1840. }
  1841. }
  1842. // Tmux false positive cleanup
  1843. if (
  1844. existingLabels.has('info: tmux') &&
  1845. !/\b(tmuxception|check_tmuxception)\b/i.test(`${title}\n${body}`)
  1846. ) {
  1847. labelsToRemove.add('info: tmux');
  1848. }
  1849. // Games and engines
  1850. const desiredGames = new Set();
  1851. const gameLabelSource = new Map(); // label → 'form-field' | 'text-match' | 'ai-fallback'
  1852. const desiredServerScripts = new Set();
  1853. // 'Game server' is the section name in server_request.yml; 'Game' is used in bug_report.yml.
  1854. const gameField = extractSection(body, 'Game server') || extractSection(body, 'Game');
  1855. const gameCandidates = parseGameCandidates(gameField);
  1856. const hasStructuredGameSelection = gameCandidates.length > 0;
  1857. for (const candidate of gameCandidates) {
  1858. const normalizedCandidate = normalizeName(candidate);
  1859. const mapped =
  1860. gameAliasToLabel.get(normalizedCandidate) || gameLabelByNormalized.get(normalizedCandidate);
  1861. if (mapped) {
  1862. desiredGames.add(mapped);
  1863. gameLabelSource.set(mapped, 'form-field');
  1864. }
  1865. const mappedScript = gameAliasToScript.get(normalizedCandidate);
  1866. if (mappedScript) desiredServerScripts.add(mappedScript);
  1867. }
  1868. // Legacy issues often have no form section; fall back to deterministic text matching.
  1869. if (desiredGames.size === 0) {
  1870. const fromText = findGamesFromText(`${title}\n${body}`, gameAliasToLabel, gameAliasToScript);
  1871. for (const label of fromText.labels) {
  1872. desiredGames.add(label);
  1873. gameLabelSource.set(label, 'text-match');
  1874. }
  1875. for (const scriptName of fromText.scripts) desiredServerScripts.add(scriptName);
  1876. }
  1877. // Optional AI fallback for legacy issues where deterministic matching finds nothing.
  1878. if (useAiGameFallback && desiredGames.size === 0) {
  1879. if (aiFallbackDisabledReason) {
  1880. console.log(`#${rawIssue.number}: AI fallback skipped (${aiFallbackDisabledReason})`);
  1881. } else {
  1882. aiGameAttempts += 1;
  1883. const aiPayload = {
  1884. model: 'openai/gpt-4.1-mini',
  1885. temperature: 0.1,
  1886. max_tokens: 120,
  1887. messages: [
  1888. {
  1889. role: 'system',
  1890. content:
  1891. 'Return JSON only. Identify the specific game referenced in this LinuxGSM issue with high precision. ' +
  1892. 'If only generic platform/engine terms are present (e.g. srcds, source dedicated server, steamcmd), return detected_game as null.',
  1893. },
  1894. {
  1895. role: 'user',
  1896. content:
  1897. `Title: ${title}\n\nBody:\n${body.slice(0, 2500)}\n\n` +
  1898. 'Return JSON: {"detected_game":"string or null","game_confidence":"high|medium|low|null"}',
  1899. },
  1900. ],
  1901. };
  1902. const aiUrl = `https://models.github.ai/orgs/${owner}/inference/chat/completions`;
  1903. const aiHeaders = {
  1904. Accept: 'application/vnd.github+json',
  1905. Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
  1906. 'X-GitHub-Api-Version': '2026-03-10',
  1907. 'Content-Type': 'application/json',
  1908. };
  1909. try {
  1910. let res = await fetch(aiUrl, { method: 'POST', headers: aiHeaders, body: JSON.stringify(aiPayload) });
  1911. // On 429 honour Retry-After (capped at 60 s) then retry once.
  1912. if (res.status === 429) {
  1913. aiGameRateLimited += 1;
  1914. const rateInfo = parseAiRateLimitInfo(res);
  1915. const rawRetryAfter = Number.parseInt(rateInfo.retryAfter || '10', 10);
  1916. const retryAfter = Math.min(Number.isFinite(rawRetryAfter) ? rawRetryAfter : 10, 60);
  1917. if (Number.isFinite(rawRetryAfter) && rawRetryAfter > 300) {
  1918. aiFallbackDisabledReason = `global cooldown active (retry-after=${rawRetryAfter}s)`;
  1919. console.log(
  1920. `#${rawIssue.number}: AI fallback disabled for remaining run (${aiFallbackDisabledReason}; ${formatAiRateLimitInfo(rateInfo)})`
  1921. );
  1922. } else {
  1923. console.log(
  1924. `#${rawIssue.number}: AI fallback rate-limited - waiting ${retryAfter}s then retrying (${formatAiRateLimitInfo(rateInfo)})`
  1925. );
  1926. await new Promise((r) => setTimeout(r, retryAfter * 1000));
  1927. res = await fetch(aiUrl, { method: 'POST', headers: aiHeaders, body: JSON.stringify(aiPayload) });
  1928. }
  1929. }
  1930. if (res.ok) {
  1931. const data = await res.json();
  1932. const raw = data.choices?.[0]?.message?.content || '{}';
  1933. const parsed = parseAiGameResponse(raw);
  1934. const detectedGame = normalizeName(parsed?.detected_game || '');
  1935. const confidence = (parsed?.game_confidence || '').toLowerCase();
  1936. if (detectedGame && confidence === 'high') {
  1937. const mappedLabel =
  1938. gameAliasToLabel.get(detectedGame) || gameLabelByNormalized.get(detectedGame);
  1939. if (mappedLabel) {
  1940. const hasAliasEvidence = hasAliasHitForLabel(
  1941. `${title}\n${body}`,
  1942. mappedLabel,
  1943. gameAliasToLabel
  1944. );
  1945. if (hasAliasEvidence) {
  1946. desiredGames.add(mappedLabel);
  1947. gameLabelSource.set(mappedLabel, 'ai-fallback');
  1948. const mappedScript = gameAliasToScript.get(detectedGame);
  1949. if (mappedScript) desiredServerScripts.add(mappedScript);
  1950. aiGameMatches += 1;
  1951. console.log(
  1952. `#${rawIssue.number}: AI fallback accepted game "${mappedLabel}" from "${parsed?.detected_game}"`
  1953. );
  1954. } else {
  1955. console.log(
  1956. `#${rawIssue.number}: AI fallback rejected game "${mappedLabel}" (no literal alias evidence in issue text)`
  1957. );
  1958. }
  1959. } else {
  1960. if (isGenericNonGameDetection(parsed?.detected_game || '')) {
  1961. console.log(
  1962. `#${rawIssue.number}: AI fallback skipped generic non-game detection "${parsed?.detected_game}"`
  1963. );
  1964. } else {
  1965. console.log(
  1966. `#${rawIssue.number}: AI fallback returned unmapped game "${parsed?.detected_game}"`
  1967. );
  1968. }
  1969. }
  1970. }
  1971. } else {
  1972. if (res.status === 429) {
  1973. const rateInfo = parseAiRateLimitInfo(res);
  1974. console.log(
  1975. `#${rawIssue.number}: AI fallback skipped (HTTP 429, ${formatAiRateLimitInfo(rateInfo)})`
  1976. );
  1977. } else {
  1978. console.log(`#${rawIssue.number}: AI fallback skipped (HTTP ${res.status})`);
  1979. }
  1980. }
  1981. } catch (err) {
  1982. console.log(`#${rawIssue.number}: AI fallback error: ${err.message}`);
  1983. }
  1984. }
  1985. }
  1986. for (const gameLabel of desiredGames) {
  1987. const mappedScript = gameAliasToScript.get(normalizeName(gameLabel.slice(6)));
  1988. if (mappedScript) desiredServerScripts.add(mappedScript);
  1989. }
  1990. const desiredEngineLabels = new Set();
  1991. for (const scriptName of desiredServerScripts) {
  1992. const engine = await getEngineForScript(scriptName);
  1993. if (!engine) continue;
  1994. const engineLabel = `engine: ${engine}`;
  1995. await ensureEngineLabel(engineLabel);
  1996. desiredEngineLabels.add(engineLabel);
  1997. }
  1998. if (desiredEngineLabels.size > 0) {
  1999. for (const label of desiredEngineLabels) labelsToAdd.add(label);
  2000. for (const label of existingLabels) {
  2001. if (label.startsWith('engine: ') && !desiredEngineLabels.has(label)) labelsToRemove.add(label);
  2002. }
  2003. }
  2004. if (desiredGames.size > 0) {
  2005. for (const label of desiredGames) labelsToAdd.add(label);
  2006. if (hasStructuredGameSelection) {
  2007. for (const label of existingLabels) {
  2008. if (label.startsWith('game: ') && !desiredGames.has(label)) labelsToRemove.add(label);
  2009. }
  2010. } else {
  2011. // For legacy issues without structured game selection, only prune stale
  2012. // broader labels when a more specific inferred game label exists.
  2013. const desiredGameNamesNormalized = new Set(
  2014. [...desiredGames].map((label) => normalizeName(label.slice(6)))
  2015. );
  2016. for (const label of existingLabels) {
  2017. if (!label.startsWith('game: ') || desiredGames.has(label)) continue;
  2018. const existingGameName = normalizeName(label.slice(6));
  2019. const isBroaderOverlap = [...desiredGameNamesNormalized].some(
  2020. (desiredName) => desiredName !== existingGameName && desiredName.startsWith(`${existingGameName} `)
  2021. );
  2022. if (isBroaderOverlap) labelsToRemove.add(label);
  2023. }
  2024. }
  2025. }
  2026. // Apply changes
  2027. let finalAdds = [...labelsToAdd].filter((label) => !existingLabels.has(label));
  2028. let finalRemoves = [...labelsToRemove].filter((label) => existingLabels.has(label));
  2029. const isGameOrEngineLabel = (label) => label.startsWith('game: ') || label.startsWith('engine: ');
  2030. if ([...finalAdds, ...finalRemoves].some(isGameOrEngineLabel)) {
  2031. try {
  2032. const issueEvents = await github.paginate(github.rest.issues.listEvents, {
  2033. owner,
  2034. repo,
  2035. issue_number: rawIssue.number,
  2036. per_page: 100,
  2037. });
  2038. const lastManualLabelEvent = new Map();
  2039. for (const e of issueEvents) {
  2040. if (!['labeled', 'unlabeled'].includes(e.event) || !e.label?.name) continue;
  2041. lastManualLabelEvent.set(e.label.name, e.actor?.type === 'Bot' ? null : e.event);
  2042. }
  2043. finalAdds = finalAdds.filter((label) => {
  2044. if (!isGameOrEngineLabel(label) || lastManualLabelEvent.get(label) !== 'unlabeled') return true;
  2045. console.log(`#${rawIssue.number}: "${label}" was removed manually; not adding it back`);
  2046. return false;
  2047. });
  2048. finalRemoves = finalRemoves.filter((label) => {
  2049. if (!isGameOrEngineLabel(label) || lastManualLabelEvent.get(label) !== 'labeled') return true;
  2050. console.log(`#${rawIssue.number}: "${label}" was added manually; keeping it`);
  2051. return false;
  2052. });
  2053. } catch (err) {
  2054. if (isApiRateLimitError(err)) throw err;
  2055. console.log(`#${rawIssue.number}: could not read issue events: ${err.message}`);
  2056. }
  2057. }
  2058. let labelAdded = 0;
  2059. let labelRemoved = 0;
  2060. for (const label of finalRemoves) {
  2061. try {
  2062. await github.rest.issues.removeLabel({
  2063. owner,
  2064. repo,
  2065. issue_number: rawIssue.number,
  2066. name: label,
  2067. });
  2068. labelRemoved += 1;
  2069. console.log(`#${rawIssue.number}: removed "${label}"`);
  2070. } catch (err) {
  2071. if (isApiRateLimitError(err)) throw err;
  2072. console.log(`#${rawIssue.number}: could not remove "${label}": ${err.message}`);
  2073. }
  2074. }
  2075. for (const label of finalAdds) {
  2076. try {
  2077. await github.rest.issues.addLabels({
  2078. owner,
  2079. repo,
  2080. issue_number: rawIssue.number,
  2081. labels: [label],
  2082. });
  2083. labelAdded += 1;
  2084. const gameSource = gameLabelSource.get(label);
  2085. console.log(`#${rawIssue.number}: added "${label}"${gameSource ? ` (${gameSource})` : ''}`);
  2086. } catch (err) {
  2087. if (isApiRateLimitError(err)) throw err;
  2088. console.log(`#${rawIssue.number}: could not add "${label}": ${err.message}`);
  2089. }
  2090. }
  2091. processed += 1;
  2092. processedIssues.push({
  2093. number: rawIssue.number,
  2094. title: rawIssue.title,
  2095. adds: labelAdded,
  2096. removes: labelRemoved,
  2097. issueTypeSet,
  2098. locked: isLocked,
  2099. });
  2100. console.log(
  2101. `#${rawIssue.number}: done (+${labelAdded} added, -${labelRemoved} removed${
  2102. issueTypeSet ? `, type→${issueTypeSet}` : ''
  2103. }${isLocked ? ', locked' : ''})`
  2104. );
  2105. } catch (err) {
  2106. if (isApiRateLimitError(err)) {
  2107. stoppedForApiRateLimit = true;
  2108. apiRateLimitStopReason = formatApiRateLimitError(err);
  2109. console.log(
  2110. `Stopping backfill due to API rate limit at #${rawIssue.number} (${apiRateLimitStopReason})`
  2111. );
  2112. failedIssues.push({
  2113. number: rawIssue.number,
  2114. title: rawIssue.title,
  2115. stage: 'rate-limit',
  2116. error: err.message,
  2117. });
  2118. break;
  2119. } else {
  2120. console.log(`Error processing #${rawIssue.number}: ${err.message}`);
  2121. failedIssues.push({
  2122. number: rawIssue.number,
  2123. title: rawIssue.title,
  2124. stage: 'process',
  2125. error: err.message,
  2126. });
  2127. }
  2128. }
  2129. }
  2130. console.log(
  2131. `Relabel backfill complete: ${processed} processed, ${failedIssues.length} failed${
  2132. stoppedForApiRateLimit ? `, stopped early (${apiRateLimitStopReason})` : ''
  2133. }.`
  2134. );
  2135. await core.summary
  2136. .addHeading('Relabel Backfill Summary')
  2137. .addTable([
  2138. [
  2139. { data: 'Requested state', header: true },
  2140. { data: 'Limit', header: true },
  2141. { data: 'AI fallback', header: true },
  2142. { data: 'AI attempts', header: true },
  2143. { data: 'AI matches', header: true },
  2144. { data: 'AI 429s', header: true },
  2145. { data: 'AI disabled reason', header: true },
  2146. { data: 'Stopped early', header: true },
  2147. { data: 'Target issues', header: true },
  2148. { data: 'Processed', header: true },
  2149. { data: 'Failures', header: true },
  2150. ],
  2151. [
  2152. state,
  2153. limit === 0 ? 'all' : String(limit),
  2154. useAiGameFallback ? 'enabled' : 'disabled',
  2155. String(aiGameAttempts),
  2156. String(aiGameMatches),
  2157. String(aiGameRateLimited),
  2158. aiFallbackDisabledReason || '—',
  2159. stoppedForApiRateLimit ? apiRateLimitStopReason : 'no',
  2160. String(selectedTargets.length),
  2161. String(processed),
  2162. String(failedIssues.length),
  2163. ],
  2164. ])
  2165. .write();
  2166. if (processedIssues.length > 0) {
  2167. const processedRows = processedIssues.slice(0, 50).map((issue) => [
  2168. `#${issue.number}${issue.locked ? ' 🔒' : ''}`,
  2169. `[${issue.title}](https://github.com/${owner}/${repo}/issues/${issue.number})`,
  2170. `+${issue.adds} / -${issue.removes}`,
  2171. issue.issueTypeSet || '—',
  2172. ]);
  2173. await core.summary
  2174. .addHeading('Processed Issues')
  2175. .addTable([
  2176. [
  2177. { data: 'Issue', header: true },
  2178. { data: 'Title', header: true },
  2179. { data: 'Label changes', header: true },
  2180. { data: 'Issue Type set', header: true },
  2181. ],
  2182. ...processedRows,
  2183. ])
  2184. .write();
  2185. }
  2186. if (failedIssues.length > 0) {
  2187. const failureRows = failedIssues.slice(0, 50).map((issue) => [
  2188. `#${issue.number}`,
  2189. issue.stage,
  2190. issue.error,
  2191. ]);
  2192. await core.summary
  2193. .addHeading('Failures')
  2194. .addTable([
  2195. [
  2196. { data: 'Issue', header: true },
  2197. { data: 'Stage', header: true },
  2198. { data: 'Error', header: true },
  2199. ],
  2200. ...failureRows,
  2201. ])
  2202. .write();
  2203. }
  2204. pr-labeler:
  2205. if: github.repository_owner == 'GameServerManagers' && github.event_name == 'pull_request_target'
  2206. runs-on: ubuntu-latest
  2207. permissions:
  2208. contents: read
  2209. issues: write
  2210. pull-requests: write
  2211. steps:
  2212. - name: PR Labeler
  2213. uses: github/issue-labeler@v3.5
  2214. with:
  2215. repo-token: "${{ secrets.GITHUB_TOKEN }}"
  2216. configuration-path: .github/labeler.yml
  2217. enable-versioned-regex: 0
  2218. include-title: 1
  2219. include-body: 0
  2220. sync-labels: 1
  2221. is-sponsor-label:
  2222. if: github.repository_owner == 'GameServerManagers' && github.event_name == 'issues' && github.event.action == 'opened'
  2223. runs-on: ubuntu-latest
  2224. steps:
  2225. - name: Is Sponsor Label
  2226. uses: JasonEtco/is-sponsor-label-action@v2
  2227. env:
  2228. GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  2229. sync-game-labels:
  2230. if: github.repository_owner == 'GameServerManagers' && github.event_name == 'push' && contains(github.event.head_commit.modified, 'lgsm/data/serverlist.csv')
  2231. runs-on: ubuntu-latest
  2232. steps:
  2233. - name: Checkout
  2234. uses: actions/checkout@v7
  2235. - name: Sync game labels from serverlist
  2236. env:
  2237. GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  2238. run: |
  2239. chmod +x .github/scripts/sync-game-labels.sh
  2240. .github/scripts/sync-game-labels.sh