action-issue-triage-automation.yml 102 KB

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