action-issue-triage-automation.yml 106 KB

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