From 4fb82e8ce2087da158a3e872a4b8cf2367ce0d6d Mon Sep 17 00:00:00 2001 From: "Yaxun (Sam) Liu" Date: Tue, 7 Oct 2025 12:33:39 -0400 Subject: [PATCH 01/11] add clang for rocm-7.0.1 (#8168) --- etc/config/c++.amazon.properties | 6 +++++- etc/config/cuda.amazon.properties | 24 ++++++++++++++++++++++-- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/etc/config/c++.amazon.properties b/etc/config/c++.amazon.properties index 2d5138b47..73224aaf1 100644 --- a/etc/config/c++.amazon.properties +++ b/etc/config/c++.amazon.properties @@ -748,7 +748,7 @@ compiler.clang211assert.semver=21.1.0 (assertions) compiler.clang211assert.options=--gcc-toolchain=/opt/compiler-explorer/gcc-15.2.0 compiler.clang211assert.ldPath=${exePath}/../lib|${exePath}/../lib/x86_64-unknown-linux-gnu -group.clang-rocm.compilers=clang-rocm-trunk:clang-rocm-40502:clang-rocm-50002:clang-rocm-50103:clang-rocm-50203:clang-rocm-50303:clang-rocm-50700:clang-rocm-60002:clang-rocm-60102:clang-rocm-60204:clang-rocm-60303:clang-rocm-60400 +group.clang-rocm.compilers=clang-rocm-trunk:clang-rocm-40502:clang-rocm-50002:clang-rocm-50103:clang-rocm-50203:clang-rocm-50303:clang-rocm-50700:clang-rocm-60002:clang-rocm-60102:clang-rocm-60204:clang-rocm-60303:clang-rocm-60400:clang-rocm-70001 group.clang-rocm.intelAsm=-mllvm --x86-asm-syntax=intel group.clang-rocm.groupName=ROCm clang x86-64 group.clang-rocm.instructionSet=amd64 @@ -818,6 +818,10 @@ compiler.clang-rocm-60400.exe=/opt/compiler-explorer/clang-rocm-6.4.0/bin/clang+ compiler.clang-rocm-60400.semver=rocm-6.4.0 compiler.clang-rocm-60400.options=--gcc-toolchain=/opt/compiler-explorer/gcc-14.2.0 compiler.clang-rocm-60400.ldPath=${exePath}/../lib|${exePath}/../lib/x86_64-unknown-linux-gnu +compiler.clang-rocm-70001.exe=/opt/compiler-explorer/clang-rocm-7.0.1/bin/clang++ +compiler.clang-rocm-70001.semver=rocm-7.0.1 +compiler.clang-rocm-70001.options=--gcc-toolchain=/opt/compiler-explorer/gcc-14.2.0 +compiler.clang-rocm-70001.ldPath=${exePath}/../lib|${exePath}/../lib/x86_64-unknown-linux-gnu ################################ # Clang for Arm diff --git a/etc/config/cuda.amazon.properties b/etc/config/cuda.amazon.properties index b429352d8..9ea84fe6f 100644 --- a/etc/config/cuda.amazon.properties +++ b/etc/config/cuda.amazon.properties @@ -362,7 +362,7 @@ compiler.cltrunk.exe=/opt/compiler-explorer/clang-trunk/bin/clang++ compiler.cltrunk.demangler=/opt/compiler-explorer/gcc-snapshot/bin/c++filt compiler.cltrunk.options=--gcc-toolchain=/opt/compiler-explorer/gcc-snapshot --cuda-path=/opt/compiler-explorer/cuda/12.8.1 --cuda-gpu-arch=sm_100a --cuda-device-only -Wno-unknown-cuda-version -D_ALLOW_UNSUPPORTED_LIBCPP -group.hipclang.compilers=hiptrunk:hipclang-rocm-40502:hipclang-rocm-50002:hipclang-rocm-50103:hipclang-rocm-50203:hipclang-rocm-50302:hipclang-rocm-50700:hipclang-rocm-60002:hipclang-rocm-60102:hipclang-trunk-rocm-60102:hipclang-staging-rocm-60102:hipclang-rocm-60204:hipclang-trunk-rocm-60204:hipclang-staging-rocm-60204:hipclang-rocm-60303:hipclang-trunk-rocm-60303:hipclang-staging-rocm-60303:hipclang-rocm-60400:hipclang-trunk-rocm-60400:hipclang-staging-rocm-60400 +group.hipclang.compilers=hiptrunk:hipclang-rocm-40502:hipclang-rocm-50002:hipclang-rocm-50103:hipclang-rocm-50203:hipclang-rocm-50302:hipclang-rocm-50700:hipclang-rocm-60002:hipclang-rocm-60102:hipclang-trunk-rocm-60102:hipclang-staging-rocm-60102:hipclang-rocm-60204:hipclang-trunk-rocm-60204:hipclang-staging-rocm-60204:hipclang-rocm-60303:hipclang-trunk-rocm-60303:hipclang-staging-rocm-60303:hipclang-rocm-60400:hipclang-trunk-rocm-60400:hipclang-staging-rocm-60400:hipclang-rocm-70001:hipclang-trunk-rocm-70001:hipclang-staging-rocm-70001 group.hipclang.isSemVer=true group.hipclang.baseName=clang group.hipclang.compilerType=clang-hip @@ -491,6 +491,24 @@ compiler.hipclang-staging-rocm-60400.name=clang staging rocm-6.4.0 compiler.hipclang-staging-rocm-60400.nvdisasm=/opt/compiler-explorer/clang-rocm-trunk/bin/llvm-objdump compiler.hipclang-staging-rocm-60400.objdumper=/opt/compiler-explorer/clang-rocm-trunk/bin/llvm-objdump compiler.hipclang-staging-rocm-60400.options=-x hip --cuda-device-only -O3 --rocm-path=/opt/compiler-explorer/libs/rocm/6.4.0 -include hip/hip_runtime.h +compiler.hipclang-rocm-70001.exe=/opt/compiler-explorer/clang-rocm-7.0.1/bin/clang++ +compiler.hipclang-rocm-70001.semver=7.0.1 +compiler.hipclang-rocm-70001.name=clang rocm-7.0.1 +compiler.hipclang-rocm-70001.nvdisasm=/opt/compiler-explorer/clang-rocm-7.0.1/bin/llvm-objdump +compiler.hipclang-rocm-70001.objdumper=/opt/compiler-explorer/clang-rocm-7.0.1/bin/llvm-objdump +compiler.hipclang-rocm-70001.options=-x hip --cuda-device-only -O3 --rocm-path=/opt/compiler-explorer/libs/rocm/7.0.1 -include hip/hip_runtime.h +compiler.hipclang-trunk-rocm-70001.exe=/opt/compiler-explorer/clang-assertions-trunk/bin/clang++ +compiler.hipclang-trunk-rocm-70001.semver=trunk-7.0.1 +compiler.hipclang-trunk-rocm-70001.name=clang trunk rocm-7.0.1 +compiler.hipclang-trunk-rocm-70001.nvdisasm=/opt/compiler-explorer/clang-assertions-trunk/bin/llvm-objdump +compiler.hipclang-trunk-rocm-70001.objdumper=/opt/compiler-explorer/clang-assertions-trunk/bin/llvm-objdump +compiler.hipclang-trunk-rocm-70001.options=-x hip --cuda-device-only -O3 --rocm-path=/opt/compiler-explorer/libs/rocm/7.0.1 -include hip/hip_runtime.h +compiler.hipclang-staging-rocm-70001.exe=/opt/compiler-explorer/clang-rocm-trunk/bin/clang++ +compiler.hipclang-staging-rocm-70001.semver=staging-7.0.1 +compiler.hipclang-staging-rocm-70001.name=clang staging rocm-7.0.1 +compiler.hipclang-staging-rocm-70001.nvdisasm=/opt/compiler-explorer/clang-rocm-trunk/bin/llvm-objdump +compiler.hipclang-staging-rocm-70001.objdumper=/opt/compiler-explorer/clang-rocm-trunk/bin/llvm-objdump +compiler.hipclang-staging-rocm-70001.options=-x hip --cuda-device-only -O3 --rocm-path=/opt/compiler-explorer/libs/rocm/7.0.1 -include hip/hip_runtime.h group.nvrtc.compilers=nvrtc130u1:nvrtc130:nvrtc129u1:nvrtc129:nvrtc128u1:nvrtc126u2:nvrtc126u1:nvrtc125u1:nvrtc124u1:nvrtc123u1:nvrtc122u1:nvrtc121:nvrtc120u1:nvrtc120:nvrtc118:nvrtc117u1:nvrtc117:nvrtc116u2:nvrtc116u1:nvrtc116:nvrtc115u2:nvrtc115u1:nvrtc115:nvrtc114u1:nvrtc114:nvrtc113u1:nvrtc113:nvrtc112u2:nvrtc112u1:nvrtc112:nvrtc111u1:nvrtc111:nvrtc11u1:nvrtc11 group.nvrtc.compilerType=nvrtc @@ -752,7 +770,7 @@ libs.nsimd.versions.22.path=/opt/compiler-explorer/libs/nsimd/v2.2/cuda/include libs.nsimd.versions.301.version=3.0.1 libs.nsimd.versions.301.path=/opt/compiler-explorer/libs/nsimd/v3.0.1/cuda/include libs.hip-amd.name=HIP (AMD Platform) -libs.hip-amd.versions=60400:60303:60204:60102:60002:50700:50203:50103:50002:40502 +libs.hip-amd.versions=70001:60400:60303:60204:60102:60002:50700:50203:50103:50002:40502 libs.hip-amd.url=https://github.com/ROCm-Developer-Tools/hipamd libs.hip-amd.versions.40502.version=4.5.2 libs.hip-amd.versions.40502.path=/opt/compiler-explorer/libs/rocm/4.5.2 @@ -774,3 +792,5 @@ libs.hip-amd.versions.60303.version=6.3.3 libs.hip-amd.versions.60303.path=/opt/compiler-explorer/libs/rocm/6.3.3 libs.hip-amd.versions.60400.version=6.4.0 libs.hip-amd.versions.60400.path=/opt/compiler-explorer/libs/rocm/6.4.0 +libs.hip-amd.versions.70001.version=7.0.1 +libs.hip-amd.versions.70001.path=/opt/compiler-explorer/libs/rocm/7.0.1 From 6e87d568449307865ddcb8364170002c5734c2f6 Mon Sep 17 00:00:00 2001 From: Matt Godbolt Date: Tue, 7 Oct 2025 11:34:26 -0500 Subject: [PATCH 02/11] Fix embedded iframe links not updating with code state (#8166) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Fixes the issue where the "Edit on Compiler Explorer" link in embedded iframes doesn't update with the current code state, staying as "/" instead of including the serialized state. ## Changes - Refactored `Sharing` class into a base class `SharingBase` that handles state tracking and embedded link updates - `Sharing` class now extends `SharingBase` and adds the full sharing UI features - Created `initialiseSharing()` function that instantiates the appropriate class based on embedded mode - Updated `main.ts` to use the new initialization function - Updated `history.ts` to use `SharingBase.filterComponentState()` instead of `Sharing.filterComponentState()` ## Testing - TypeScript compilation passes (`npm run ts-check`) - Linting passes (`npm run lint`) - Tests pass (`npm run test-min`) - Manual browser testing confirms embedded links now update correctly Closes #8097 πŸ€– Generated with [Claude Code](https://claude.ai/code) --------- Co-authored-by: Claude --- static/history.ts | 4 +- static/main.ts | 4 +- static/sharing.ts | 119 +++++++++++++++++++++++++++------------------- 3 files changed, 73 insertions(+), 54 deletions(-) diff --git a/static/history.ts b/static/history.ts index e3c0df11f..451b196bd 100644 --- a/static/history.ts +++ b/static/history.ts @@ -24,7 +24,7 @@ import _ from 'underscore'; import {localStorage} from './local.js'; -import {Sharing} from './sharing.js'; +import {SharingBase} from './sharing.js'; const maxHistoryEntries = 30; export type HistorySource = {dt: number; source: string}; @@ -100,7 +100,7 @@ export function trackHistory(layout: any) { let lastState: string | null = null; const debouncedPush = _.debounce(push, 500); layout.on('stateChanged', () => { - const stringifiedConfig = JSON.stringify(Sharing.filterComponentState(layout.toConfig())); + const stringifiedConfig = JSON.stringify(SharingBase.filterComponentState(layout.toConfig())); if (stringifiedConfig !== lastState) { lastState = stringifiedConfig; debouncedPush(stringifiedConfig); diff --git a/static/main.ts b/static/main.ts index 6ddd0a57f..7f2686a0c 100644 --- a/static/main.ts +++ b/static/main.ts @@ -64,7 +64,7 @@ import {Presentation} from './presentation.js'; import {Printerinator} from './print-view.js'; import {setupRealDark, takeUsersOutOfRealDark} from './real-dark.js'; import {Settings, SiteSettings} from './settings.js'; -import {Sharing} from './sharing.js'; +import {initialiseSharing} from './sharing.js'; import {Themer} from './themes.js'; import * as url from './url.js'; import {formatISODate, updateAndCalcTopBarHeight} from './utils.js'; @@ -779,7 +779,7 @@ function start() { History.trackHistory(layout); setupSiteTemplateWidgetButton(layout); - if (!options.embedded) new Sharing(layout); + initialiseSharing(layout, !!options.embedded); new Printerinator(hub, themer); hub.layout.eventHub.emit('settingsChange', settings); // Ensure everyone knows the settings diff --git a/static/sharing.ts b/static/sharing.ts index bdb1d1268..0bd150a95 100644 --- a/static/sharing.ts +++ b/static/sharing.ts @@ -85,10 +85,61 @@ const shareServices = { }, }; -export class Sharing { - private layout: GoldenLayout; - private lastState: any; +// Base class that handles state tracking and embedded link updates +export class SharingBase { + protected layout: GoldenLayout; + protected lastState: string | null = null; + constructor(layout: GoldenLayout) { + this.layout = layout; + this.initCallbacks(); + } + + protected initCallbacks(): void { + this.layout.on('stateChanged', this.onStateChanged.bind(this)); + } + + protected onStateChanged(): void { + const config = SharingBase.filterComponentState(this.layout.toConfig()); + this.ensureUrlIsNotOutdated(config); + + // Update embedded links if present (works in both modes) + if (options.embedded) { + const strippedToLast = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1); + $('a.link').prop('href', strippedToLast + '#' + url.serialiseState(config)); + } + } + + protected ensureUrlIsNotOutdated(config: any): void { + const stringifiedConfig = JSON.stringify(config); + if (stringifiedConfig !== this.lastState) { + if (this.lastState != null && window.location.pathname !== window.httpRoot) { + window.history.replaceState(null, '', window.httpRoot); + } + this.lastState = stringifiedConfig; + } + } + + public static filterComponentState(config: any): any { + function filterComponentStateImpl(component: any) { + if (component.content) { + for (let i = 0; i < component.content.length; i++) { + filterComponentStateImpl(component.content[i]); + } + } + + if (component.componentState) { + delete component.componentState.selection; + } + } + + config = cloneDeep(config); + filterComponentStateImpl(config); + return config; + } +} + +export class Sharing extends SharingBase { private readonly share: JQuery; private readonly shareTooltipTarget: JQuery; private readonly shareShort: JQuery; @@ -100,9 +151,8 @@ export class Sharing { private clippyButton: ClipboardJS | null; private readonly shareLinkDialog: HTMLElement; - constructor(layout: any) { - this.layout = layout; - this.lastState = null; + constructor(layout: GoldenLayout) { + super(layout); this.shareLinkDialog = unwrap(document.getElementById('sharelinkdialog'), 'Share modal element not found'); this.share = $('#share'); @@ -119,17 +169,16 @@ export class Sharing { this.clippyButton = null; this.initButtons(); - this.initCallbacks(); + this.initFullCallbacks(); } - private initCallbacks(): void { + private initFullCallbacks(): void { this.layout.eventHub.on('displaySharingPopover', () => { this.openShareModalForType(LinkType.Short); }); this.layout.eventHub.on('copyShortLinkToClip', () => { this.copyLinkTypeToClipboard(LinkType.Short); }); - this.layout.on('stateChanged', this.onStateChanged.bind(this)); this.shareLinkDialog.addEventListener('show.bs.modal', this.onOpenModalPane.bind(this)); this.shareLinkDialog.addEventListener('hidden.bs.modal', this.onCloseModalPane.bind(this)); @@ -152,25 +201,6 @@ export class Sharing { }); } - private onStateChanged(): void { - const config = Sharing.filterComponentState(this.layout.toConfig()); - this.ensureUrlIsNotOutdated(config); - if (options.embedded) { - const strippedToLast = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1); - $('a.link').prop('href', strippedToLast + '#' + url.serialiseState(config)); - } - } - - private ensureUrlIsNotOutdated(config: any): void { - const stringifiedConfig = JSON.stringify(config); - if (stringifiedConfig !== this.lastState) { - if (this.lastState != null && window.location.pathname !== window.httpRoot) { - window.history.replaceState(null, '', window.httpRoot); - } - this.lastState = stringifiedConfig; - } - } - private static bindToLinkType(bind: string): LinkType { switch (bind) { case 'Full': @@ -466,28 +496,6 @@ export class Sharing { return (navigator.clipboard as Clipboard | undefined) !== undefined; } - public static filterComponentState(config: any, keysToRemove: [string] = ['selection']): any { - function filterComponentStateImpl(component: any) { - if (component.content) { - for (let i = 0; i < component.content.length; i++) { - filterComponentStateImpl(component.content[i]); - } - } - - if (component.componentState) { - Object.keys(component.componentState) - .filter(e => keysToRemove.includes(e)) - .forEach(key => { - delete component.componentState[key]; - }); - } - } - - config = cloneDeep(config); - filterComponentStateImpl(config); - return config; - } - private static updateShares(container: JQuery, url: string): void { const baseTemplate = $('#share-item'); _.each(shareServices, (service, serviceName) => { @@ -508,3 +516,14 @@ export class Sharing { }); } } + +// Initialize sharing functionality based on whether we're in embedded mode or not +export function initialiseSharing(layout: GoldenLayout, isEmbedded: boolean): void { + if (isEmbedded) { + // Just create the base class for state tracking and link updates + new SharingBase(layout); + } else { + // Create full Sharing with all features + new Sharing(layout); + } +} From 4cb1416c2a22967802deb9f92ce048b2fa1a5fe8 Mon Sep 17 00:00:00 2001 From: Matt Godbolt Date: Tue, 7 Oct 2025 14:50:22 -0500 Subject: [PATCH 03/11] Add gh_tool CLI for GitHub repository automation (#8170) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR adds a new Python CLI tool for automating GitHub repository management tasks. ## Overview The initial implementation provides duplicate issue detection using text similarity analysis. This is the first step toward automating repository triage tasks. ## Features - **Click-based CLI** with subcommands for future extensibility - **find-duplicates command** for detecting duplicate issues using text similarity - Uses **gh CLI** for GitHub API access (no token management needed) - Text similarity using `difflib.SequenceMatcher` (ratio-based algorithm) - Configurable similarity threshold (default: 0.6) - Progress bar for long-running comparisons - Age filtering support (`--min-age` parameter) - Standard Python src-layout with **uv** for dependency management - **Comprehensive test suite** with pytest (integrated into CI) ## Project Structure ``` etc/scripts/gh_tool/ β”œβ”€β”€ src/gh_tool/ # Main package β”‚ β”œβ”€β”€ cli.py # Click-based CLI interface β”‚ └── duplicate_finder.py # Core duplicate detection logic β”œβ”€β”€ tests/ # Test suite β”‚ └── test_duplicate_finder.py β”œβ”€β”€ docs/ # Documentation β”‚ β”œβ”€β”€ TRIAGE-CRITERIA.md # Triage guidelines from manual review β”‚ └── PHASE1-FINDINGS.md # Historical analysis of 855 issues β”œβ”€β”€ pyproject.toml # Package configuration └── README.md # Usage documentation ``` ## Usage ```bash cd etc/scripts/gh_tool uv sync uv run gh_tool find-duplicates /tmp/report.md ``` **Options:** - `--threshold FLOAT` - Similarity threshold 0-1 (default: 0.6) - `--state {all,open,closed}` - Issue state to check (default: open) - `--min-age DAYS` - Only check issues older than N days (default: 0) - `--limit INTEGER` - Maximum number of issues to fetch (default: 1000) - `--repo TEXT` - GitHub repository in owner/repo format (default: compiler-explorer/compiler-explorer) **Example:** ```bash # Find high-confidence duplicates in open issues uv run gh_tool find-duplicates /tmp/report.md --threshold 0.85 # Check all issues older than 30 days uv run gh_tool find-duplicates /tmp/report.md --state all --min-age 30 ``` ## Testing The tool includes comprehensive test coverage: - Unit tests for similarity calculation - Integration tests for duplicate detection - Edge case handling (transitive grouping, age filtering, threshold sensitivity) - Report generation validation **Run tests:** ```bash cd etc/scripts/gh_tool uv run pytest -v ``` Tests are integrated into CI and run on every push. ## Documentation - **`README.md`**: Complete usage guide with examples - **`docs/TRIAGE-CRITERIA.md`**: Comprehensive triage guidelines developed during manual review of 22+ issues - **`docs/PHASE1-FINDINGS.md`**: Historical analysis context from initial 855 issue review ## CI Integration The tool is integrated into the GitHub Actions workflow: - `uv` is installed via `astral-sh/setup-uv@v6` - Tests run automatically on every push - Ensures tool remains functional as codebase evolves ## Next Steps Future enhancements planned for follow-up PRs: - GitHub Action for automatic duplicate detection on new issues - Additional automation tools (upstream health checker, label validator, etc.) - Automated triage reports ## Changes in this PR - βœ… Core duplicate detection implementation - βœ… Comprehensive test suite (192 lines) - βœ… CI integration - βœ… Complete documentation - βœ… Example triage criteria and findings --------- Co-authored-by: Claude --- .github/workflows/test-and-deploy.yml | 3 + etc/scripts/gh_tool/.gitignore | 16 ++ etc/scripts/gh_tool/README.md | 125 ++++++++ etc/scripts/gh_tool/docs/PHASE1-FINDINGS.md | 200 +++++++++++++ etc/scripts/gh_tool/docs/TRIAGE-CRITERIA.md | 271 ++++++++++++++++++ etc/scripts/gh_tool/pyproject.toml | 35 +++ etc/scripts/gh_tool/src/gh_tool/__init__.py | 3 + etc/scripts/gh_tool/src/gh_tool/cli.py | 82 ++++++ .../gh_tool/src/gh_tool/duplicate_finder.py | 144 ++++++++++ .../gh_tool/tests/test_duplicate_finder.py | 192 +++++++++++++ 10 files changed, 1071 insertions(+) create mode 100644 etc/scripts/gh_tool/.gitignore create mode 100644 etc/scripts/gh_tool/README.md create mode 100644 etc/scripts/gh_tool/docs/PHASE1-FINDINGS.md create mode 100644 etc/scripts/gh_tool/docs/TRIAGE-CRITERIA.md create mode 100644 etc/scripts/gh_tool/pyproject.toml create mode 100644 etc/scripts/gh_tool/src/gh_tool/__init__.py create mode 100644 etc/scripts/gh_tool/src/gh_tool/cli.py create mode 100755 etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py create mode 100644 etc/scripts/gh_tool/tests/test_duplicate_finder.py diff --git a/.github/workflows/test-and-deploy.yml b/.github/workflows/test-and-deploy.yml index 9dae21819..79ea3eee0 100644 --- a/.github/workflows/test-and-deploy.yml +++ b/.github/workflows/test-and-deploy.yml @@ -21,6 +21,8 @@ jobs: run: | make prereqs python3 -m pip install numba + - name: Install uv + uses: astral-sh/setup-uv@v6 - name: Run checks run: | npm run lint-check @@ -29,6 +31,7 @@ jobs: python3 ./etc/scripts/util/propscheck.py python3 ./etc/scripts/util/propschecktest.py python3 ./etc/scripts/test_numba_wrapper.py + uv run --directory etc/scripts/gh_tool pytest -v - uses: codecov/codecov-action@v5 with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/etc/scripts/gh_tool/.gitignore b/etc/scripts/gh_tool/.gitignore new file mode 100644 index 000000000..cf707e0ce --- /dev/null +++ b/etc/scripts/gh_tool/.gitignore @@ -0,0 +1,16 @@ +# Python +__pycache__/ +*.pyc +*.pyo +*.pyd +.Python + +# uv +uv.lock +.venv/ +*.egg-info/ + +# IDE +.vscode/ +.idea/ +*.swp diff --git a/etc/scripts/gh_tool/README.md b/etc/scripts/gh_tool/README.md new file mode 100644 index 000000000..980bf0f1d --- /dev/null +++ b/etc/scripts/gh_tool/README.md @@ -0,0 +1,125 @@ +# GitHub Tools for Compiler Explorer + +CLI tools for automating GitHub repository management tasks. + +## Setup + +This project uses [`uv`](https://docs.astral.sh/uv/) for Python version and dependency management. + +Install dependencies: + +```bash +cd etc/scripts/gh_tool +uv sync +``` + +## Usage + +Run from the gh_tool directory: + +```bash +cd etc/scripts/gh_tool + +# Get help +uv run gh_tool --help + +# Get help for a specific command +uv run gh_tool find-duplicates --help +``` + +## Commands + +### find-duplicates + +Finds potential duplicate issues in the compiler-explorer repository using text similarity analysis (difflib.SequenceMatcher). + +**Usage:** + +```bash +# Basic usage (checks all open issues) +uv run gh_tool find-duplicates /tmp/duplicates-report.md + +# Check all issues (including closed) +uv run gh_tool find-duplicates /tmp/all-duplicates.md --state all + +# Adjust similarity threshold for higher confidence matches +uv run gh_tool find-duplicates /tmp/high-confidence.md --threshold 0.85 + +# Combine options +uv run gh_tool find-duplicates /tmp/report.md --threshold 0.7 --state all --min-age 30 + +# Use with a different repository +uv run gh_tool find-duplicates /tmp/other-repo.md --repo owner/repository +``` + +**Arguments:** + +- `OUTPUT_FILE` (required) - Path to output markdown file + +**Options:** + +- `--threshold FLOAT` - Similarity threshold between 0 and 1 (default: 0.6) + - 0.6 = 60% similar titles + - Higher values = fewer, more confident matches +- `--state {all,open,closed}` - Which issues to check (default: open) +- `--min-age DAYS` - Only check issues older than N days (default: 0) +- `--limit INTEGER` - Maximum number of issues to fetch (default: 1000) +- `--repo TEXT` - GitHub repository in owner/repo format (default: compiler-explorer/compiler-explorer) + +**Example Output:** + +```markdown +# Potential Duplicate Issues + +Found 5 potential duplicate groups: + +## Group 1 (85% similar) +- #3201 [LIB REQUEST] numpy (12 comments, created 2021-03-15) +- #7778 [LIB REQUEST] numpy (0 comments, created 2024-01-10) + +## Group 2 (72% similar) +- #4336 [COMPILER REQUEST]: Groovy (3 comments, created 2022-05-20) +- #6526 [COMPILER REQUEST]: Groovy (1 comments, created 2023-08-15) +``` + +**Performance:** + +The duplicate detection algorithm uses O(nΒ²) pairwise comparisons. For reference: +- ~850 issues: ~362,000 comparisons (~1-2 minutes) +- ~1,000 issues: ~500,000 comparisons (~2-3 minutes) + +A progress bar shows real-time progress during the comparison phase. + +**Requirements:** + +- `gh` CLI must be installed and authenticated +- Read access to compiler-explorer/compiler-explorer repository + +## Future Tools + +This directory is intended to house additional GitHub automation scripts such as: + +- Upstream project health checker (detect abandoned compiler/library projects) +- Label consistency validator +- Issue template compliance checker +- Automated triage reports + +## Development + +Run tests: + +```bash +uv run pytest -v +``` + +Run linting: + +```bash +uv run ruff check . +``` + +Format code: + +```bash +uv run ruff format . +``` diff --git a/etc/scripts/gh_tool/docs/PHASE1-FINDINGS.md b/etc/scripts/gh_tool/docs/PHASE1-FINDINGS.md new file mode 100644 index 000000000..3cfe37864 --- /dev/null +++ b/etc/scripts/gh_tool/docs/PHASE1-FINDINGS.md @@ -0,0 +1,200 @@ +# Compiler Explorer Issue Analysis - Phase 1 Findings +**Date:** 2025-10-06 +**Total Open Issues:** 855 + +## Executive Summary + +The issue backlog reveals clear patterns that can guide systematic triage: + +- **46% (398) are stale** (>2 years old, <5 comments) - prime candidates for review +- **35% (297) have zero engagement** - likely duplicates, invalid, or need clarification +- **48% (412) are poorly labeled** - only generic labels, impeding organization +- **51% (439) are generic "requests"** - mostly compiler/library additions +- **28% (239) are bugs** - actual functionality issues +- **5% (42) marked "probably-wont-happen"** but still open - should be closed kindly + +## Key Statistics + +### Age Distribution +``` +>5 years old: 137 (16.0%) ← Ancient, likely obsolete or philosophical +3-5 years old: 189 (22.1%) ← Old, likely stale +2-3 years old: 181 (21.2%) ← Getting stale +1-2 years old: 151 (17.7%) +6-12 months: 102 (11.9%) +3-6 months: 53 (6.2%) +<3 months: 42 (4.9%) ← Recent +``` + +**Key Insight:** 59% of issues are >2 years old. This suggests either low prioritization or lack of contributor bandwidth. + +### Label Distribution (Top 10) +``` +request 439 (51.3%) ← Mostly compiler/library requests +bug 239 (28.0%) +new-compilers 121 (14.2%) +new-libs 93 (10.9%) +enhancement 79 (9.2%) +ui 51 (6.0%) +help wanted 44 (5.1%) +probably-wont-happen 42 (4.9%) +Status: triaged 35 (4.1%) +lang-c++ 29 (3.4%) +``` + +### Engagement Patterns + +**Top 3 Most-Commented:** +1. #82 (39 comments) - "C(++) Compiler Master List" - META-ISSUE tracking compilers +2. #891 (37 comments) - "Add pgroup compiler" +3. #264 (35 comments) - "Add D8 JavaScript assembly output" + +**Zero Comments:** 297 issues (35%) have NO engagement whatsoever +- Many are recent (<6 months) and may just need time +- Many are 5+ years old and likely forgotten/obsolete + +## Critical Findings + +### 1. Tracking/Meta Issues + +**Issue #82** (10 years old) is a "Master List" with checkboxes tracking compiler support. This was useful historically but now creates confusion: +- 39 comments of various requests +- Acts as a catch-all for "add this compiler" requests +- Should probably be closed with pointer to proper issue templates + +### 2. "Probably Won't Happen" Issues (42 total) + +These are already flagged but remain open. Examples: +- #187 (8.9y) - "Add support for MMIX" - niche educational architecture +- #264 (8.7y) - "Add D8 JavaScript assembly" - 35 comments, out of scope +- #341 (8.5y) - "classic GCC versions" - limited value vs maintenance cost +- #514 (8.1y) - "ARM GCC 6.3.0 standard libraries missing" - old compiler version + +**Action:** These should be kindly closed with explanations. + +### 3. Stale Issues (398 total) + +**Criteria:** >2 years old AND <5 comments + +These show minimal community interest and are likely: +- Overtaken by events (e.g., new compiler versions available) +- Niche requests with no PR momentum +- Questions that were never answered + +**Sample oldest stale issues:** +- #187 (8.9y, 0 comments) - MMIX support +- #297 (8.6y, 0 comments) - GCC7 verbose-asm format +- #341 (8.5y, 0 comments) - Classic GCC versions +- #425 (8.4y, 0 comments) - libfirm/cparser + +### 4. Duplicate/Similar Requests + +**GCC versions:** 11 issues requesting various GCC versions/configurations +**Clang variants:** 9 issues for different Clang forks/versions +**MSVC versions:** 3+ issues for recent MSVC versions (could be consolidated) +**ROCm/AMD:** 3 issues about ROCm compiler versions + +These could be consolidated into tracking issues or closed as duplicates. + +### 5. Poorly Labeled Issues (412 total) + +Many issues have only generic labels like "request" or "bug" without specifics: +- No language tag (lang-c++, lang-rust, etc.) +- No area tag (ui, compiler-issue, etc.) +- No priority indication + +This makes filtering and prioritization difficult. + +## Common Themes in Titles + +**Top keywords:** +- "request" (437) - the label shows up in titles too +- "compiler" (183) +- "support" (97) +- "clang" (62) +- "library" (35) +- "msvc" (27) + +**Pattern:** Most issues are straightforward "add X compiler" or "add Y library" requests. + +## Recommendations for Phase 2 + +### Immediate Actions + +1. **Close "Probably Won't Happen" Issues (42)** + - Draft kind, clear explanation template + - Close with rationale and link to contribution docs if applicable + - Expected impact: -5% issue count + +2. **Close Ancient Zero-Comment Issues (estimate ~50-100)** + - Issues >5 years old with 0 comments and no activity + - Use "stale bot" type reasoning: "no activity, assumed no longer relevant" + - Allow 2 weeks for objections before closing + - Expected impact: -6-12% issue count + +3. **Close Obvious Duplicates (estimate ~20-30)** + - Multiple GCC/Clang version requests β†’ consolidate or close with "use latest" + - Expected impact: -2-4% issue count + +### Medium-Term Actions + +4. **Improve Labeling (412 issues)** + - Add language-specific labels (lang-*) + - Add area labels (ui, execution, api, etc.) + - Add priority labels where clear + - This enables better filtering and assignment + +5. **Create "Good First Issue" Pipeline (~50 issues)** + - Review "help wanted" (44 issues) for suitable ones + - Look for well-defined, isolated tasks + - Add good-first-issue label and mentorship notes + +6. **Consolidate Request Tracking** + - Create wiki/doc page for "Compiler Request Guidelines" + - Explain: how to request, how to contribute, what makes requests likely + - Close #82 meta-issue with pointer to new docs + +### Long-Term Strategy + +7. **Implement Stale Bot** + - Auto-label issues >1 year old with no activity + - Auto-close after warning period if still no activity + - Keep it friendly: "seems resolved, please reopen if still relevant" + +8. **Improve Issue Templates** + - Separate templates for: compiler requests, library requests, bug reports, feature requests + - Require more details (version numbers, error messages, why needed) + - Auto-label based on template used + +9. **Regular Triage Cadence** + - Weekly review of new issues (label, prioritize, close if needed) + - Monthly review of old issues (close stale, consolidate duplicates) + - Quarterly review of "help wanted" (ensure still relevant) + +## Estimated Impact + +**Conservative cleanup estimate:** +- Close "probably-wont-happen": -42 issues +- Close ancient zero-comment: -50 issues +- Close duplicates: -20 issues +- **Total: -112 issues (13% reduction)** + +**Aggressive cleanup estimate:** +- Above plus stale >3 years: -200+ additional +- **Total: -300+ issues (35% reduction)** + +## Next Steps + +**Proposed Plan:** +1. Review sample of "probably-wont-happen" issues together +2. Draft closure message templates (kind but clear) +3. Review sample of stale issues together +4. Implement Phase 2: Systematic triage with your approval +5. Consider automation (stale bot, better templates) + +## Files Generated + +- `all-issues-raw.json` - Full issue data from GitHub +- `issues-summary.json` - Simplified format +- `full-analysis.txt` - Complete statistical analysis +- `PHASE1-FINDINGS.md` - This document diff --git a/etc/scripts/gh_tool/docs/TRIAGE-CRITERIA.md b/etc/scripts/gh_tool/docs/TRIAGE-CRITERIA.md new file mode 100644 index 000000000..522c98c26 --- /dev/null +++ b/etc/scripts/gh_tool/docs/TRIAGE-CRITERIA.md @@ -0,0 +1,271 @@ +# Compiler Explorer Issue Triage Criteria + +Based on manual review of 22+ issues (October 2025), here are the established triage patterns and decisions. + +## Quick Reference: Triage Decisions + +| Category | Keep/Close | Labels to Add | +|----------|-----------|---------------| +| Active projects (compiler/lib requests) | KEEP | help wanted | +| Abandoned upstream projects (8+ years) | CLOSE | - | +| Zero-demand features (7+ years, 0 comments) | CLOSE | - | +| External tools (already work via API) | CLOSE | - | +| Stale reminders/TODOs (6+ years) | CLOSE | - | +| Duplicates | CLOSE newest | - | +| Related but not duplicates | KEEP both | Link in comments | + +--- + +## 1. Core Principles + +### Conservative Approach +- **Age alone is NOT a proxy for value** +- Each issue needs explicit review before closing +- When in doubt, keep it open +- Look for recent interest (CppCon mentions, user questions, etc.) + +### Priority Areas +1. Close obvious duplicates +2. Close abandoned/dead projects +3. Better organize remaining issues with labels +4. Identify "help wanted" opportunities + +--- + +## 2. Compiler & Library Requests + +### KEEP if: +- βœ… Upstream project is actively maintained (check last commit date) +- βœ… Project has legitimate use cases +- βœ… Zero comments but project is real/active (just needs contributor) + +### CLOSE if: +- ❌ Upstream project is abandoned (8+ years with no activity) +- ❌ Author confirmed they don't have patches/support for newer versions +- ❌ Project was experimental and never went mainstream + +### Examples: + +**KEEP:** +- #425 (libfirm/cparser) - Active: cparser updated Jan 2025, libfirm March 2025 +- #1232 (PCL Point Cloud Library) - Active, legitimate library +- #503 (Cython) - Active project, add "help wanted" +- #341 (classic GCC versions) - User interest confirmed at CppCon + +**CLOSE:** +- #2063 (static_print GCC) - Abandoned (last commit 2017), author has no patches +- #1018 (clang-contracts) - CE already has alternative contract compilers + +--- + +## 3. Feature Requests + +### KEEP if: +- βœ… Technically feasible +- βœ… Aligns with CE's mission +- βœ… Recent interest or discussion +- βœ… "Probably-wont-happen" but PRs would be accepted + +### CLOSE if: +- ❌ Implementation complexity outweighs value +- ❌ Encourages bad practices (e.g., #797 BUILT_ON_COMPILER_EXPLORER macro) +- ❌ Tool already exists externally and works via CE's API + +### Examples: + +**KEEP:** +- #297 (-fverbose-asm filtering bug) - Real usability issue, fixable +- #1004 (verbose-asm UI button) - Related to #297, useful convenience +- #187 (MMIX) - Recent CppCon interest + +**CLOSE:** +- #547 (FXC shader compiler) - Not a good fit for CE +- #797 (BUILT_ON_COMPILER_EXPLORER macro) - Encourages bad practices +- #1203 (SIMD-Visualiser integration) - Already works externally via API + +--- + +## 4. Bugs & Issues + +### Bug Validation Process: +1. Test if bug still reproduces using Compiler Explorer MCP +2. Read ALL comments, not just the first one +3. Check if workarounds exist +4. Verify affected compiler versions still exist in CE + +### KEEP if: +- βœ… Bug still reproduces +- βœ… Affects multiple compiler versions +- βœ… No reasonable workaround exists + +### Examples: + +**KEEP:** +- #514 (ARM GCC hard float) - Tested, still fails with `-mfloat-abi=hard` on 6 ARM GCC versions + +**CLOSE:** +- Issues that were already fixed but not closed +- Issues with trivial workarounds + +--- + +## 5. Internal Tasks & Reminders + +### CLOSE if: +- ❌ 6+ year old reminder with no action taken +- ❌ Decision was implicitly made (kept the code/feature) +- ❌ No longer relevant to current codebase + +### Examples: + +**CLOSE:** +- #1357 (binutils-multi reminder) - 6.5 years old, still installed, serves a purpose +- Accidental duplicates from batch operations + +--- + +## 6. Related vs Duplicate Issues + +### Not Duplicates if: +- Issues address different aspects of the same problem +- One is prerequisite for the other +- Different implementation approaches + +### Duplicates if: +- Identical title and description +- Same request posted multiple times +- Accidental double-posts + +### Examples: + +**Related (NOT duplicates):** +- #297 (fix filter bug) + #1004 (add UI button) - Related but distinct + +**Duplicates (CLOSE):** +- #3201, #7778, #8111 - All requesting NumPy +- #4336, #6526 - Both requesting Groovy +- #3426, #5972 - Both requesting OpenBLAS +- #7601, #7602 - Accidental double-post + +--- + +## 7. Labeling Strategy + +### Add "help wanted" when: +- Valid request but maintainer doesn't have time +- Clear scope, would accept PRs +- Not marked "probably-wont-happen" + +### Keep "probably-wont-happen" when: +- Low priority but PRs would still be accepted +- Niche use case +- High complexity/low demand + +### Remove "probably-wont-happen" when: +- Recent interest or demand emerges +- Project confirmed active and relevant +- Better candidate for "help wanted" + +--- + +## 8. Label Changes Made + +### Reviewed Issues - Actions Taken: + +| Issue | Action | Labels | Reason | +|-------|--------|--------|--------| +| #264 | KEEP | Remove probably-wont-happen | CE supports interpreted languages | +| #187 | KEEP | Add help wanted | Recent CppCon interest | +| #503 | KEEP | Add help wanted | Active project, PRs welcome | +| #341 | KEEP | Add help wanted | User interest confirmed | +| #514 | KEEP | Remove probably-wont-happen | Bug still exists, affects 6 versions | +| #547 | CLOSE | - | Not a good fit | +| #797 | CLOSE | - | Encourages bad practices | +| #297 | KEEP | Add bug/usability | Filter breaks verbose-asm | +| #1004 | KEEP | Link to #297 | UI convenience, related to #297 | +| #1018 | CLOSE | - | Satisfied by alternative compilers | +| #2063 | CLOSE | - | Abandoned upstream | +| #425 | KEEP | Add help wanted | Active project | +| #668 | CLOSE | - | Zero demand, very niche | +| #1203 | CLOSE | - | Works externally already | +| #1232 | KEEP | Add help wanted | Legitimate library | +| #1357 | CLOSE | - | Stale reminder, implicitly resolved | +| #7778 | CLOSE | Duplicate of #3201 | NumPy duplicate | +| #8111 | CLOSE | Duplicate of #3201 | NumPy duplicate | +| #5972 | CLOSE | Duplicate of #3426 | OpenBLAS duplicate | +| #6526 | CLOSE | Duplicate of #4336 | Groovy duplicate | +| #7601 | CLOSE | Duplicate of #7602 | Accidental duplicate | + +--- + +## 9. Triage Process Recommendations + +### Monthly Triage Workflow: +1. **Identify duplicates** (automated similarity matching) +2. **Check upstream status** for compiler/library requests (last commit date) +3. **Test bugs** using Compiler Explorer MCP +4. **Review engagement** (comments, reactions, recent activity) +5. **Apply labels** (help wanted, good first issue, etc.) +6. **Close obvious cases** (duplicates, abandoned projects, stale reminders) + +### Tools Used: +- GitHub API for bulk data extraction +- Python scripts for similarity analysis +- Compiler Explorer MCP for live testing +- Web search for upstream project status + +--- + +## 10. Communication Templates + +### Closing Duplicates: +``` +Closing as duplicate of #XXXX which has more discussion/history. +Please follow that issue for updates. +``` + +### Closing Abandoned Projects: +``` +Closing as the upstream project appears abandoned (last commit [date]). +If the project becomes active again, please feel free to reopen or create a new issue. +``` + +### Closing External Tools: +``` +Closing as this tool already works externally using Compiler Explorer's public API. +Integration would not provide significant additional value. +See: [tool URL] +``` + +### Keeping with "help wanted": +``` +This is a valid request but requires a contributor with expertise in [area]. +Marking as "help wanted" - PRs are welcome! +``` + +--- + +## Statistics from This Triage Session + +- **Issues reviewed**: 22 +- **Issues to close**: 12 (5 duplicates + 7 other) +- **Issues to keep**: 10 +- **"help wanted" added**: 5 +- **Relationships identified**: 1 pair (#297 + #1004) + +**Impact**: +- Closed duplicates: -5 issues +- Closed abandoned/unviable: -7 issues +- Net reduction: -12 issues (~1.4% of 855 total) +- Better organized: 10 issues now have clearer status + +--- + +## Next Steps + +1. Apply label changes to reviewed issues +2. Close duplicates with appropriate comments +3. Close abandoned/stale issues with appropriate comments +4. Link related issues (#297 ↔ #1004) +5. Continue triage with next batch of issues +6. Update this document as new patterns emerge diff --git a/etc/scripts/gh_tool/pyproject.toml b/etc/scripts/gh_tool/pyproject.toml new file mode 100644 index 000000000..e39054fef --- /dev/null +++ b/etc/scripts/gh_tool/pyproject.toml @@ -0,0 +1,35 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "compiler-explorer-gh-tool" +version = "0.0.1" +description = "GitHub automation tool for Compiler Explorer" +requires-python = ">=3.12" +dependencies = [ + "click>=8.1.0", + "pytest>=8.0.0", +] + +[project.scripts] +gh_tool = "gh_tool.cli:main" + +[tool.uv] +package = true + +[tool.ruff] +line-length = 120 +target-version = "py312" + +[tool.ruff.lint] +select = [ + "E", # pycodestyle errors + "W", # pycodestyle warnings + "F", # pyflake + "I", # isort + "UP", # pyupgrade +] +ignore = [ + "E501", # line length +] diff --git a/etc/scripts/gh_tool/src/gh_tool/__init__.py b/etc/scripts/gh_tool/src/gh_tool/__init__.py new file mode 100644 index 000000000..1b917703e --- /dev/null +++ b/etc/scripts/gh_tool/src/gh_tool/__init__.py @@ -0,0 +1,3 @@ +"""GitHub automation tools for Compiler Explorer.""" + +__version__ = "0.0.1" diff --git a/etc/scripts/gh_tool/src/gh_tool/cli.py b/etc/scripts/gh_tool/src/gh_tool/cli.py new file mode 100644 index 000000000..1325f8848 --- /dev/null +++ b/etc/scripts/gh_tool/src/gh_tool/cli.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""CLI for GitHub automation tools for Compiler Explorer.""" + +import sys + +import click + +from gh_tool.duplicate_finder import fetch_issues, find_duplicates, generate_report + + +@click.group() +def main(): + """GitHub automation tools for Compiler Explorer.""" + pass + + +@main.command("find-duplicates") +@click.argument("output_file", type=click.Path()) +@click.option( + "--threshold", + default=0.6, + type=click.FloatRange(0, 1), + help="Similarity threshold between 0 and 1 (default: 0.6)", +) +@click.option( + "--state", + type=click.Choice(["all", "open", "closed"]), + default="open", + help="Issue state to check (default: open)", +) +@click.option( + "--min-age", + default=0, + type=int, + help="Only check issues older than N days (default: 0)", +) +@click.option( + "--limit", + default=1000, + type=int, + help="Maximum number of issues to fetch (default: 1000)", +) +@click.option( + "--repo", + default="compiler-explorer/compiler-explorer", + type=str, + help="GitHub repository in owner/repo format (default: compiler-explorer/compiler-explorer)", +) +def find_duplicates_cmd(output_file, threshold, state, min_age, limit, repo): + """Find potential duplicate issues in the compiler-explorer repository. + + OUTPUT_FILE is the path where the markdown report will be saved. + + Examples: + + \b + # Find duplicates in open issues + gh_tool find-duplicates /tmp/duplicates.md + + \b + # High confidence matches only + gh_tool find-duplicates /tmp/report.md --threshold 0.85 + + \b + # Check all issues (including closed) + gh_tool find-duplicates /tmp/all.md --state all + """ + # Fetch issues + click.echo(f"Fetching {state} issues...", err=True) + issues = fetch_issues(state, limit, repo) + + # Find duplicates + click.echo(f"Analyzing {len(issues)} issues with threshold {threshold}...", err=True) + groups = find_duplicates(issues, threshold, min_age) + + # Generate report + generate_report(groups, output_file) + click.echo(f"Found {len(groups)} potential duplicate groups", err=True) + + +if __name__ == "__main__": + main() diff --git a/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py b/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py new file mode 100755 index 000000000..72a5a636c --- /dev/null +++ b/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py @@ -0,0 +1,144 @@ +"""Find potential duplicate issues in the compiler-explorer repository using text similarity.""" + +import json +import subprocess +import sys +from datetime import datetime, timedelta, timezone +from difflib import SequenceMatcher +from typing import Any + +import click + + +def fetch_issues(state: str = "open", limit: int = 1000, repo: str = "compiler-explorer/compiler-explorer") -> list[dict[str, Any]]: + """Fetch issues from GitHub using gh CLI.""" + click.echo(f"Fetching {state} issues from {repo}...", err=True) + + cmd = [ + "gh", "issue", "list", + "--repo", repo, + "--state", state, + "--limit", str(limit), + "--json", "number,title,createdAt,updatedAt,state,labels,comments" + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + issues = json.loads(result.stdout) + click.echo(f"Fetched {len(issues)} issues", err=True) + return issues + except subprocess.CalledProcessError as e: + click.echo(f"Error fetching issues: {e.stderr}", err=True) + raise click.Abort() + except json.JSONDecodeError as e: + click.echo(f"Error parsing JSON: {e}", err=True) + raise click.Abort() + + +def calculate_similarity(title1: str, title2: str) -> float: + """Calculate similarity ratio between two titles using SequenceMatcher.""" + return SequenceMatcher(None, title1.lower(), title2.lower()).ratio() + + +def find_duplicates( + issues: list[dict[str, Any]], threshold: float = 0.6, min_age_days: int = 0 +) -> list[dict[str, Any]]: + """Find potential duplicate issues based on title similarity.""" + # Filter issues by age if requested + if min_age_days > 0: + cutoff_date = datetime.now(timezone.utc) - timedelta(days=min_age_days) + issues = [ + issue for issue in issues + if datetime.fromisoformat(issue["createdAt"].replace("Z", "+00:00")) < cutoff_date + ] + click.echo(f"Filtered to {len(issues)} issues older than {min_age_days} days", err=True) + + # Find similar pairs + duplicates: list[dict[str, Any]] = [] + seen: set[tuple[int, int]] = set() + total_comparisons = len(issues) * (len(issues) - 1) // 2 + + click.echo(f"Comparing {len(issues)} issues ({total_comparisons:,} comparisons)...", err=True) + + with click.progressbar( + length=total_comparisons, label="Finding duplicates", file=sys.stderr + ) as bar: + for i, issue1 in enumerate(issues): + for j, issue2 in enumerate(issues[i + 1 :], start=i + 1): + bar.update(1) + + # Skip if already grouped + pair = tuple(sorted([issue1["number"], issue2["number"]])) + if pair in seen: + continue + + similarity = calculate_similarity(issue1["title"], issue2["title"]) + + if similarity >= threshold: + duplicates.append({"similarity": similarity, "issues": [issue1, issue2]}) + seen.add(pair) + + # Group similar issues together + groups: list[dict[str, Any]] = [] + + for dup in sorted(duplicates, key=lambda x: x["similarity"], reverse=True): + issue1, issue2 = dup["issues"] + num1, num2 = issue1["number"], issue2["number"] + + # Find existing group containing either issue + found_group = None + for group in groups: + if num1 in [i["number"] for i in group["issues"]] or num2 in [i["number"] for i in group["issues"]]: + found_group = group + break + + if found_group: + # Add to existing group if not already there + for issue in [issue1, issue2]: + if issue["number"] not in [i["number"] for i in found_group["issues"]]: + found_group["issues"].append(issue) + found_group["max_similarity"] = max(found_group["max_similarity"], dup["similarity"]) + else: + # Create new group + groups.append({ + "issues": [issue1, issue2], + "max_similarity": dup["similarity"] + }) + + return groups + + +def format_issue(issue: dict[str, Any]) -> str: + """Format issue for display.""" + labels = ", ".join(l["name"] for l in issue["labels"]) if issue["labels"] else "no labels" + created = issue["createdAt"][:10] + state = issue["state"] + comment_count = len(issue.get("comments", [])) + + return f"- #{issue['number']} {issue['title']} ({comment_count} comments, {state}, created {created})" + + +def generate_report(groups: list[dict[str, Any]], output_file: str) -> None: + """Generate markdown report of duplicate groups.""" + output: list[str] = [] + output.append("# Potential Duplicate Issues\n") + + if not groups: + output.append("No potential duplicates found.\n") + else: + output.append(f"Found {len(groups)} potential duplicate groups:\n") + + for idx, group in enumerate(sorted(groups, key=lambda x: x["max_similarity"], reverse=True), 1): + similarity_pct = int(group["max_similarity"] * 100) + output.append(f"## Group {idx} ({similarity_pct}% similar)\n") + + for issue in sorted(group["issues"], key=lambda x: x["createdAt"]): + output.append(format_issue(issue) + "\n") + + output.append("\n") + + report = "\n".join(output) + + with open(output_file, "w") as f: + f.write(report) + click.echo(f"Report saved to {output_file}", err=True) diff --git a/etc/scripts/gh_tool/tests/test_duplicate_finder.py b/etc/scripts/gh_tool/tests/test_duplicate_finder.py new file mode 100644 index 000000000..18086d74a --- /dev/null +++ b/etc/scripts/gh_tool/tests/test_duplicate_finder.py @@ -0,0 +1,192 @@ +# Copyright (c) 2025, Compiler Explorer Authors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import tempfile +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest + +from gh_tool.duplicate_finder import calculate_similarity, find_duplicates, generate_report + + +def make_issue(number, title, created_at=None, comments=None): + """Helper to create test issue data.""" + if created_at is None: + created_at = datetime.now(timezone.utc).isoformat() + if comments is None: + comments = [] + + return { + "number": number, + "title": title, + "createdAt": created_at, + "updatedAt": created_at, + "state": "open", + "labels": [], + "comments": comments, + } + + +class TestCalculateSimilarity: + @pytest.mark.parametrize( + "title1,title2,expected_min,expected_max", + [ + # Identical strings + ("Add GCC 13", "Add GCC 13", 1.0, 1.0), + # Case insensitive + ("Add GCC 13", "add gcc 13", 1.0, 1.0), + # Completely different + ("Add GCC 13", "Python bug", 0.0, 0.3), + # Similar titles with different case + ("[LIB REQUEST] numpy", "[LIB REQUEST] NumPy", 0.9, 1.0), + # Partial similarity + ("Add GCC 13 support", "Add GCC 14 support", 0.7, 1.0), + # Different request types + ("[COMPILER REQUEST] foo", "[LIB REQUEST] foo", 0.5, 0.8), + ], + ) + def test_similarity_calculation(self, title1, title2, expected_min, expected_max): + similarity = calculate_similarity(title1, title2) + assert expected_min <= similarity <= expected_max + + +class TestFindDuplicates: + def test_no_duplicates(self): + issues = [ + make_issue(1, "Add GCC 13"), + make_issue(2, "Fix Python bug"), + make_issue(3, "Update documentation"), + ] + groups = find_duplicates(issues, threshold=0.6) + assert len(groups) == 0 + + def test_simple_duplicate_pair(self): + issues = [ + make_issue(1, "Add NumPy library"), + make_issue(2, "Add numpy library"), + ] + groups = find_duplicates(issues, threshold=0.8) + assert len(groups) == 1 + assert len(groups[0]["issues"]) == 2 + assert groups[0]["issues"][0]["number"] in [1, 2] + assert groups[0]["issues"][1]["number"] in [1, 2] + + def test_multiple_duplicate_groups(self): + issues = [ + make_issue(1, "Add GCC 13"), + make_issue(2, "Add gcc 13"), + make_issue(3, "Add Clang 17"), + make_issue(4, "Add clang 17"), + make_issue(5, "Fix bug"), + ] + groups = find_duplicates(issues, threshold=0.85) + assert len(groups) == 2 + + def test_transitive_grouping(self): + # If A~B and B~C, they should all be in one group + issues = [ + make_issue(1, "Add NumPy"), + make_issue(2, "Add numpy"), + make_issue(3, "Add NumPy library"), + ] + groups = find_duplicates(issues, threshold=0.7) + # Should be grouped together transitively + assert len(groups) >= 1 + # At least one group should have all 3 issues + max_group_size = max(len(g["issues"]) for g in groups) + assert max_group_size >= 2 + + def test_age_filtering(self): + now = datetime.now(timezone.utc) + old_date = (now - timedelta(days=100)).isoformat() + recent_date = (now - timedelta(days=5)).isoformat() + + issues = [ + make_issue(1, "Add NumPy", created_at=old_date), + make_issue(2, "Add numpy", created_at=recent_date), + ] + + # Filter to only old issues (>30 days) + groups = find_duplicates(issues, threshold=0.8, min_age_days=30) + # Should only have one issue in the comparison, so no duplicates found + assert len(groups) == 0 + + # No age filter should find the duplicate + groups = find_duplicates(issues, threshold=0.8, min_age_days=0) + assert len(groups) == 1 + + def test_threshold_sensitivity(self): + issues = [ + make_issue(1, "Add GCC 13 compiler"), + make_issue(2, "Add GCC 14 compiler"), + ] + + # Low threshold should find similarity + groups = find_duplicates(issues, threshold=0.6) + assert len(groups) == 1 + + # Very high threshold should not + groups = find_duplicates(issues, threshold=0.99) + assert len(groups) == 0 + + +class TestGenerateReport: + def test_empty_report(self): + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.md') as f: + output_file = f.name + + try: + generate_report([], output_file) + content = Path(output_file).read_text() + assert "No potential duplicates found" in content + finally: + Path(output_file).unlink() + + def test_report_with_groups(self): + groups = [ + { + "issues": [ + make_issue(1, "Add NumPy", created_at="2020-01-01T00:00:00Z"), + make_issue(2, "Add numpy", created_at="2020-01-02T00:00:00Z"), + ], + "max_similarity": 0.95, + } + ] + + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.md') as f: + output_file = f.name + + try: + generate_report(groups, output_file) + content = Path(output_file).read_text() + + assert "# Potential Duplicate Issues" in content + assert "Found 1 potential duplicate groups" in content + assert "## Group 1 (95% similar)" in content + assert "#1" in content + assert "#2" in content + assert "numpy" in content.lower() + finally: + Path(output_file).unlink() From efab7336b2d4508ae1856cbb422e85169dc7bf96 Mon Sep 17 00:00:00 2001 From: aneshlya Date: Tue, 7 Oct 2025 12:55:38 -0700 Subject: [PATCH 04/11] Add ISPC v1.28.2 (#8167) This PR adds support of recently released ISPC 1.28.2 and updates a default snippet for it. Related infra change: https://github.com/compiler-explorer/infra/pull/1857 --- etc/config/ispc.amazon.properties | 7 +++++-- examples/ispc/default.ispc | 6 +----- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/etc/config/ispc.amazon.properties b/etc/config/ispc.amazon.properties index 714440a47..20c15cfae 100644 --- a/etc/config/ispc.amazon.properties +++ b/etc/config/ispc.amazon.properties @@ -1,10 +1,13 @@ compilers=&ispc -defaultCompiler=ispc1281 +defaultCompiler=ispc1282 objdumper=/opt/compiler-explorer/gcc-14.2.0/bin/objdump -group.ispc.compilers=ispc1281:ispc1280:ispc1270:ispc1260:ispc1253:ispc1250:ispc1240:ispc1230:ispc1220:ispc1210:ispc1200:ispc1190:ispc1180:ispc1170:ispc1161:ispc1160:ispc1150:ispc1141:ispc1140:ispc1130:ispc1120:ispc1110:ispc1100:ispc192:ispc191:ispc-trunk +group.ispc.compilers=ispc1282:ispc1281:ispc1280:ispc1270:ispc1260:ispc1253:ispc1250:ispc1240:ispc1230:ispc1220:ispc1210:ispc1200:ispc1190:ispc1180:ispc1170:ispc1161:ispc1160:ispc1150:ispc1141:ispc1140:ispc1130:ispc1120:ispc1110:ispc1100:ispc192:ispc191:ispc-trunk group.ispc.isSemVer=true group.ispc.baseName=ispc +compiler.ispc1282.exe=/opt/compiler-explorer/ispc-1.28.2/bin/ispc +compiler.ispc1282.semver=1.28.2 +compiler.ispc1282.executableLinker=/opt/compiler-explorer/gcc-14.2.0/bin/gcc compiler.ispc1281.exe=/opt/compiler-explorer/ispc-1.28.1/bin/ispc compiler.ispc1281.semver=1.28.1 compiler.ispc1281.executableLinker=/opt/compiler-explorer/gcc-14.2.0/bin/gcc diff --git a/examples/ispc/default.ispc b/examples/ispc/default.ispc index 8d8ec61ac..cef0c92c6 100644 --- a/examples/ispc/default.ispc +++ b/examples/ispc/default.ispc @@ -1,10 +1,6 @@ // Type your code here, or load an example. varying int square_even(varying int num) { - if (num % 2 == 0) { - return num * num; - } else { - return num; - } + return (num % 2 == 0)? num * num: num; } // Uncomment this if you would like to execute the code From eca351fa49daf253ceae9fbfff375a31e4265c5b Mon Sep 17 00:00:00 2001 From: Matt Godbolt Date: Tue, 7 Oct 2025 15:11:16 -0500 Subject: [PATCH 05/11] Add automated duplicate issue detection (#8171) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Implements automated detection of potential duplicate issues using GitHub Actions. ## Implementation Details - Uses `wow-actions/potential-duplicates@v1` action - Triggers on issue `opened` and `edited` events - Configured with **90% similarity threshold** to minimize false positives - Automatically adds `potential-duplicate` label and comment with links to similar issues ## Rationale for 90% Threshold Based on manual testing with the `gh_tool` CLI: - 85% threshold produced too many false positives from template-based matches - True duplicates typically have 90%+ similarity - Uses Damerau-Levenshtein distance algorithm (same as manual tool) ## Testing - βœ… YAML syntax validated - βœ… Pre-commit hooks passed (lint + ts-check) - βœ… Created `potential-duplicate` label in repository - Manual testing of similar configuration showed good results at 90% threshold ## Dependencies - Depends on #8166 (add-gh-tools-cli branch) being merged first - This PR adds the automation layer on top of the manual tooling πŸ€– Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .github/workflows/duplicate-detection.yml | 36 +++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 .github/workflows/duplicate-detection.yml diff --git a/.github/workflows/duplicate-detection.yml b/.github/workflows/duplicate-detection.yml new file mode 100644 index 000000000..913c363bb --- /dev/null +++ b/.github/workflows/duplicate-detection.yml @@ -0,0 +1,36 @@ +# This workflow automatically detects potential duplicate issues +# using text similarity analysis with Damerau-Levenshtein distance. +# +# For more information, see: https://github.com/wow-actions/potential-duplicates + +name: Duplicate Issue Detection +on: + issues: + types: [opened, edited] + +jobs: + detect-duplicates: + runs-on: ubuntu-latest + # Only run on issues, not pull requests + if: ${{ !github.event.issue.pull_request }} + steps: + - uses: wow-actions/potential-duplicates@v1 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Use 90% similarity threshold to reduce false positives from template matches + # Testing showed that 85% threshold produced too many template-based matches + # True duplicates typically have 90%+ similarity + threshold: 0.90 + # Comment on the issue if duplicates are found + label: potential-duplicate + # Custom comment to link to potentially duplicate issues + comment: | + **Potential duplicate detected** + + This issue appears to be similar to existing issues. Please review them before continuing: + + {{#issues}} + - [#{{number}}]({{html_url}}) ({{accuracy}}% similar) + {{/issues}} + + If this is not a duplicate, please clarify how it differs from the above issues. From 5ca970efcef4dca516001e1bb5633e9f74797984 Mon Sep 17 00:00:00 2001 From: Matt Godbolt Date: Tue, 7 Oct 2025 15:44:15 -0500 Subject: [PATCH 06/11] Extract diagnostic info from Safari CustomEvent rejections (#8173) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #8172 Fixes [COMPILER-EXPLORER-DXM](https://compiler-explorer.sentry.io/issues/COMPILER-EXPLORER-DXM) ## Problem Sentry issue COMPILER-EXPLORER-DXM has accumulated **7,018+ occurrences** with essentially no diagnostic information: - Error: `CustomEvent: Event 'CustomEvent' (type=unhandledrejection) captured as promise rejection` - No stacktrace - Safari-specific (Safari 26.0 on macOS) - No actionable information to debug the issue ## Root Cause Safari sometimes rejects promises with `CustomEvent`/`Event` objects instead of Error objects. Our `unhandledrejection` handler in `static/sentry.ts:110-122` converts non-Error rejections to Error objects using: ```typescript const errorMessage = typeof reason === 'string' ? reason : `Non-Error rejection: ${JSON.stringify(reason)}`; ``` When `JSON.stringify()` is called on Event objects, it returns `{}` because Event properties are **non-enumerable**. This loses all valuable diagnostic information like: - `event.type` - the event type - `event.target` - what triggered the event - `event.detail` - custom data for CustomEvents ## Evidence - [Sentry JavaScript SDK Issue #2210](https://github.com/getsentry/sentry-javascript/issues/2210) - Documents the exact same problem - [WebKit Bug #150358](https://bugs.webkit.org/show_bug.cgi?id=150358) - Promise rejection event handling - Multiple Safari 16.3+ reports of CustomEvent rejections ## Solution Extract meaningful properties from Event/CustomEvent objects **before** stringifying: 1. **Add type guard**: `isEventLike()` to detect Event/CustomEvent objects 2. **Extract properties**: `formatEventRejection()` to get `type`, `target`, `detail` 3. **Cleaner code**: Refactor with ternary chain and modern TypeScript patterns 4. **Better diagnostics**: Use `Object.assign()` for type-safe property addition ### Before ``` Non-Error rejection: {} ``` ### After ``` Event rejection: type="unhandledrejection", target="Window", detail={...} ``` ## Impact This will allow us to: 1. βœ… Identify the actual source of these Safari rejections 2. βœ… Determine if they're from CE code, third-party libraries, or browser extensions 3. βœ… Decide if they need fixing or should be filtered out 4. βœ… Get actionable diagnostic information instead of empty objects ## Test Plan - βœ… TypeScript type checking passes - βœ… Linter passes with auto-formatting - βœ… Related tests pass - βœ… Pre-commit hooks pass - Manual testing: Wait for Safari users to trigger these errors and verify we now get useful diagnostic info in Sentry ## Code Review Notes The fix operates at the **right layer** - transforming Events into meaningful Error messages at the point of rejection, before Sentry sees them. This is different from Sentry's `ExtraErrorData` integration which operates on already-serialized errors. πŸ€– Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- static/sentry.ts | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/static/sentry.ts b/static/sentry.ts index 3f5fdc808..e7bd06777 100644 --- a/static/sentry.ts +++ b/static/sentry.ts @@ -55,6 +55,25 @@ export function setSentryLayout(l: GoldenLayout) { }); } +function isEventLike(value: unknown): value is Event { + return value instanceof Event || value?.constructor?.name === 'Event' || value?.constructor?.name === 'CustomEvent'; +} + +function formatEventRejection(evt: Event): string { + const targetName = evt.target?.constructor?.name ?? 'unknown'; + let message = `Event rejection: type="${evt.type}", target="${targetName}"`; + + if ('detail' in evt && evt.detail !== undefined) { + try { + message += `, detail=${JSON.stringify(evt.detail)}`; + } catch { + message += ', detail=[Unserializable]'; + } + } + + return message; +} + export function SetupSentry() { if (options.statusTrackingEnabled && options.sentryDsn) { Sentry.init({ @@ -108,16 +127,23 @@ export function SetupSentry() { }, }); window.addEventListener('unhandledrejection', event => { - // Convert non-Error rejection reasons to Error objects let reason = event.reason; - if (!(reason instanceof Error)) { - const errorMessage = - typeof reason === 'string' ? reason : `Non-Error rejection: ${JSON.stringify(reason)}`; - reason = new Error(errorMessage); - // Preserve original reason for debugging - (reason as any).originalReason = event.reason; + if (!(reason instanceof Error)) { + // Safari sometimes rejects promises with CustomEvent/Event objects. + // Extract useful properties instead of stringifying to empty object. + // See: https://github.com/compiler-explorer/compiler-explorer/issues/8172 + // Related: https://github.com/getsentry/sentry-javascript/issues/2210 + const errorMessage = + typeof reason === 'string' + ? reason + : isEventLike(reason) + ? formatEventRejection(reason) + : `Non-Error rejection: ${JSON.stringify(reason)}`; + + reason = Object.assign(new Error(errorMessage), {originalReason: event.reason}); } + SentryCapture(reason, 'Unhandled Promise Rejection'); }); } From 70df51df2960058e8d9f9cd65ba1382675b45cbe Mon Sep 17 00:00:00 2001 From: Matt Godbolt Date: Tue, 7 Oct 2025 15:44:56 -0500 Subject: [PATCH 07/11] Improve duplicate issue detection by stripping category tags (#8175) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Fixes the duplicate issue detection algorithm to strip `[TAGS]` from issue titles before calculating similarity. This eliminates massive false-positive groups caused by shared tag prefixes like `[LIB REQUEST]` or `[COMPILER REQUEST]`. ## Problem The previous implementation would create groups of 98+ completely unrelated issues just because they shared common tag prefixes. For example: - `[LIB REQUEST] Add ULib Library` - `[LIB REQUEST] musl vs glibc` - `[REQUEST] Float explorer support` - `[REQUEST] Support logging in` These would all be grouped together despite being completely different requests. ## Solution - Strip `[TAGS]` before calculating text similarity using a compiled regex pattern - Compare only the actual content: "Add ULib Library" vs "musl vs glibc" β†’ low similarity βœ“ ## Additional Changes - Added `ruff` as a project dependency for consistent code quality - Fixed linting issues (unused imports, updated to `datetime.UTC`) - Updated tests to reflect new tag-stripping behavior ## Results Testing on actual CE issues shows dramatic improvement: - **Before**: 83 groups, with Group 1 containing 98 unrelated issues (98% false positives) - **After**: 63 groups, with Group 1 containing 2 legitimate "Forth" duplicates (actual duplicates) Most groups are now legitimate duplicates like: - Three "Problem with [opcode]" bugs - Two TI ARM compiler requests - Multiple MSVC version requests ## Test Plan - [x] All existing tests pass - [x] Tested on real CE issue data showing 20+ group reduction - [x] Code passes ruff linting and formatting πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude --- etc/scripts/gh_tool/pyproject.toml | 1 + etc/scripts/gh_tool/src/gh_tool/cli.py | 2 - .../gh_tool/src/gh_tool/duplicate_finder.py | 51 +++++++++++-------- .../gh_tool/tests/test_duplicate_finder.py | 14 ++--- 4 files changed, 39 insertions(+), 29 deletions(-) diff --git a/etc/scripts/gh_tool/pyproject.toml b/etc/scripts/gh_tool/pyproject.toml index e39054fef..1a0d97542 100644 --- a/etc/scripts/gh_tool/pyproject.toml +++ b/etc/scripts/gh_tool/pyproject.toml @@ -10,6 +10,7 @@ requires-python = ">=3.12" dependencies = [ "click>=8.1.0", "pytest>=8.0.0", + "ruff>=0.8.0", ] [project.scripts] diff --git a/etc/scripts/gh_tool/src/gh_tool/cli.py b/etc/scripts/gh_tool/src/gh_tool/cli.py index 1325f8848..df553b472 100644 --- a/etc/scripts/gh_tool/src/gh_tool/cli.py +++ b/etc/scripts/gh_tool/src/gh_tool/cli.py @@ -1,8 +1,6 @@ #!/usr/bin/env python3 """CLI for GitHub automation tools for Compiler Explorer.""" -import sys - import click from gh_tool.duplicate_finder import fetch_issues, find_duplicates, generate_report diff --git a/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py b/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py index 72a5a636c..9b64889ef 100755 --- a/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py +++ b/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py @@ -1,25 +1,37 @@ """Find potential duplicate issues in the compiler-explorer repository using text similarity.""" import json +import re import subprocess import sys -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta from difflib import SequenceMatcher from typing import Any import click +# Compiled regex to strip [TAGS] from issue titles +TAG_PATTERN = re.compile(r"\[.*?\]\s*") -def fetch_issues(state: str = "open", limit: int = 1000, repo: str = "compiler-explorer/compiler-explorer") -> list[dict[str, Any]]: + +def fetch_issues( + state: str = "open", limit: int = 1000, repo: str = "compiler-explorer/compiler-explorer" +) -> list[dict[str, Any]]: """Fetch issues from GitHub using gh CLI.""" click.echo(f"Fetching {state} issues from {repo}...", err=True) cmd = [ - "gh", "issue", "list", - "--repo", repo, - "--state", state, - "--limit", str(limit), - "--json", "number,title,createdAt,updatedAt,state,labels,comments" + "gh", + "issue", + "list", + "--repo", + repo, + "--state", + state, + "--limit", + str(limit), + "--json", + "number,title,createdAt,updatedAt,state,labels,comments", ] try: @@ -36,8 +48,14 @@ def fetch_issues(state: str = "open", limit: int = 1000, repo: str = "compiler-e def calculate_similarity(title1: str, title2: str) -> float: - """Calculate similarity ratio between two titles using SequenceMatcher.""" - return SequenceMatcher(None, title1.lower(), title2.lower()).ratio() + """Calculate similarity ratio between two titles using SequenceMatcher. + + Strips [TAGS] before comparing to avoid false positives from shared prefixes + like [LIB REQUEST], [COMPILER REQUEST], etc. + """ + clean_title1 = TAG_PATTERN.sub("", title1) + clean_title2 = TAG_PATTERN.sub("", title2) + return SequenceMatcher(None, clean_title1.lower(), clean_title2.lower()).ratio() def find_duplicates( @@ -46,10 +64,9 @@ def find_duplicates( """Find potential duplicate issues based on title similarity.""" # Filter issues by age if requested if min_age_days > 0: - cutoff_date = datetime.now(timezone.utc) - timedelta(days=min_age_days) + cutoff_date = datetime.now(UTC) - timedelta(days=min_age_days) issues = [ - issue for issue in issues - if datetime.fromisoformat(issue["createdAt"].replace("Z", "+00:00")) < cutoff_date + issue for issue in issues if datetime.fromisoformat(issue["createdAt"].replace("Z", "+00:00")) < cutoff_date ] click.echo(f"Filtered to {len(issues)} issues older than {min_age_days} days", err=True) @@ -60,9 +77,7 @@ def find_duplicates( click.echo(f"Comparing {len(issues)} issues ({total_comparisons:,} comparisons)...", err=True) - with click.progressbar( - length=total_comparisons, label="Finding duplicates", file=sys.stderr - ) as bar: + with click.progressbar(length=total_comparisons, label="Finding duplicates", file=sys.stderr) as bar: for i, issue1 in enumerate(issues): for j, issue2 in enumerate(issues[i + 1 :], start=i + 1): bar.update(1) @@ -100,17 +115,13 @@ def find_duplicates( found_group["max_similarity"] = max(found_group["max_similarity"], dup["similarity"]) else: # Create new group - groups.append({ - "issues": [issue1, issue2], - "max_similarity": dup["similarity"] - }) + groups.append({"issues": [issue1, issue2], "max_similarity": dup["similarity"]}) return groups def format_issue(issue: dict[str, Any]) -> str: """Format issue for display.""" - labels = ", ".join(l["name"] for l in issue["labels"]) if issue["labels"] else "no labels" created = issue["createdAt"][:10] state = issue["state"] comment_count = len(issue.get("comments", [])) diff --git a/etc/scripts/gh_tool/tests/test_duplicate_finder.py b/etc/scripts/gh_tool/tests/test_duplicate_finder.py index 18086d74a..e57810eb9 100644 --- a/etc/scripts/gh_tool/tests/test_duplicate_finder.py +++ b/etc/scripts/gh_tool/tests/test_duplicate_finder.py @@ -23,7 +23,7 @@ # POSSIBILITY OF SUCH DAMAGE. import tempfile -from datetime import datetime, timedelta, timezone +from datetime import UTC, datetime, timedelta from pathlib import Path import pytest @@ -34,7 +34,7 @@ from gh_tool.duplicate_finder import calculate_similarity, find_duplicates, gene def make_issue(number, title, created_at=None, comments=None): """Helper to create test issue data.""" if created_at is None: - created_at = datetime.now(timezone.utc).isoformat() + created_at = datetime.now(UTC).isoformat() if comments is None: comments = [] @@ -63,8 +63,8 @@ class TestCalculateSimilarity: ("[LIB REQUEST] numpy", "[LIB REQUEST] NumPy", 0.9, 1.0), # Partial similarity ("Add GCC 13 support", "Add GCC 14 support", 0.7, 1.0), - # Different request types - ("[COMPILER REQUEST] foo", "[LIB REQUEST] foo", 0.5, 0.8), + # Different request types but same content (tags stripped) + ("[COMPILER REQUEST] foo", "[LIB REQUEST] foo", 1.0, 1.0), ], ) def test_similarity_calculation(self, title1, title2, expected_min, expected_max): @@ -119,7 +119,7 @@ class TestFindDuplicates: assert max_group_size >= 2 def test_age_filtering(self): - now = datetime.now(timezone.utc) + now = datetime.now(UTC) old_date = (now - timedelta(days=100)).isoformat() recent_date = (now - timedelta(days=5)).isoformat() @@ -154,7 +154,7 @@ class TestFindDuplicates: class TestGenerateReport: def test_empty_report(self): - with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.md') as f: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".md") as f: output_file = f.name try: @@ -175,7 +175,7 @@ class TestGenerateReport: } ] - with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.md') as f: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".md") as f: output_file = f.name try: From daae03566ca533312050223c71acacbd443496e8 Mon Sep 17 00:00:00 2001 From: Matt Godbolt Date: Tue, 7 Oct 2025 16:28:15 -0500 Subject: [PATCH 08/11] Update compiler installation documentation to reference YAML config (#8177) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "Adding a new compiler to the live site" section was outdated, referencing deprecated bash scripts in update_compilers/ directory. Updated to reference the current YAML-based configuration system: - References ce_install tool instead of old scripts - Points to bin/yaml/*.yaml configuration files - Links to infra repo documentation (ce_install_yaml.md, installing_compilers.md) - Provides concrete installation command examples - Updates terminology (non-free instead of install_nonfree_compilers.sh) Fixes #5937 πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude --- docs/AddingACompiler.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/AddingACompiler.md b/docs/AddingACompiler.md index 2db24ee9b..5688f8ab3 100644 --- a/docs/AddingACompiler.md +++ b/docs/AddingACompiler.md @@ -170,16 +170,19 @@ be able to see the MSVC compiler in the compiler list. ## Adding a new compiler to the live site -On the main CE website, compilers are installed into a `/opt/compiler-explorer/` directory by a set of scripts in the +On the main CE website, compilers are installed into `/opt/compiler-explorer/` using the `ce_install` tool from the sister GitHub repo: https://github.com/compiler-explorer/infra -In the `update_compilers` directory in that repository are a set of scripts that download and install binaries and -compilers. If you wish to test locally, and can create a `/opt/compiler-explorer` directory on your machine which is -readable and writable by your current user, then you can run the scripts directly. The binaries and the free compilers -can be installed - the commercial compilers live in the `install_nonfree_compilers.sh` and won't work. +Compiler definitions are YAML-based configurations in the `bin/yaml/` directory of that repository (e.g., `cpp.yaml`, +`rust.yaml`). For many compilers, adding a new version is as simple as adding the version number to the `targets:` list +in the appropriate YAML file. See the infra repository's documentation at `docs/ce_install_yaml.md` and +`docs/installing_compilers.md` for comprehensive details on the YAML configuration format and installation process. -If your compiler fits nicely into the harness then it should be straightforward to add it there. Anything more complex: -contact the CE authors for more help. +If you wish to test locally, create a `/opt/compiler-explorer` directory readable and writable by your user, then run +`./bin/ce_install install 'compilers/LANG/ARCH/COMPILER VERSION'` from the infra repository. Free compilers install +normally; commercial compilers marked `non-free` in the YAML won't work without proper licensing. + +If your compiler fits the existing patterns it should be straightforward. Anything more complex: contact the CE authors. ## Putting it all together From fd39af7be8ad70a6394a785bf5bd8a4c4e2b0d41 Mon Sep 17 00:00:00 2001 From: Matt Godbolt Date: Tue, 7 Oct 2025 16:29:12 -0500 Subject: [PATCH 09/11] Add AI-powered duplicate detection with strict filtering (#8176) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Adds optional AI-powered duplicate detection using Claude API to eliminate false positives from string similarity matching. The AI analyzes candidate groups with strict rules and only confirms true duplicates. ## Problem The tag-stripping improvement (#8175) reduced false positives significantly, but string similarity still produces noise: - Different assemblers grouped together: "fasm", "YASM", "AsmX" (all different tools) - Unrelated features: "language tooltips" vs "language detection" (different features) - Specific vs general requests: "EWARM" vs "ARM execution" (specific toolchain vs general support) **Before AI filtering:** 63 groups with ~60% false positive rate ## Solution ### Two-phase detection: 1. **Broadphase:** String similarity (fast, high recall) creates candidate groups 2. **AI Refinement:** Claude Sonnet 4 applies strict rules to confirm duplicates ### Strict AI rules: - βœ“ **Duplicates:** Same tool with spelling/version variants ("NumPy" = "numpy", "GCC 13" = "GCC 13.1") - βœ— **NOT duplicates:** Different named tools ("fasm" β‰  "YASM"), related features ("tooltips" β‰  "detection") ### Features: - Optional `--use-ai` flag (requires `ANTHROPIC_API_KEY` in `.env` file) - Adjustable confidence threshold with `--ai-confidence` (default: 0.7) - AI reasoning included in markdown reports for transparency - Graceful fallback if API key not available ## Results Testing on 843 open CE issues: | Phase | Groups | Quality | |-------|--------|---------| | Broadphase (string similarity) | 63 | ~40% accurate | | AI filtering | 5 | **100% accurate** | ### Confirmed duplicates found: 1. Forth language requests (identical) 2. Documentation out-of-date reports (#5937 + #4906) 3. objdump tool requests (#4633 + #3139) 4. Haskell vector library requests 5. Make/webpack build issues (same bug) ### False positives eliminated: - βœ— fasm/YASM/AsmX (different assemblers) - βœ— Language tooltips vs detection (different features) - βœ— ARM vs EWARM execution (general vs specific) - βœ— Lua vs LUAU (related but different languages) - βœ— OpenBLAS vs OpenSSL (different libraries) ## Cost Analysis - 63 groups Γ— ~400-500 tokens/group β‰ˆ 25-30k tokens per run - Cost: **~$0.15 per run** with Sonnet 4 (based on actual usage) - Runs only when `--use-ai` flag is used - Very affordable for occasional duplicate detection ## Configuration Create `.env` file in `etc/scripts/gh_tool/`: ```bash ANTHROPIC_API_KEY=sk-ant-... ``` The `.env` file is gitignored for security. ## Example Usage ```bash # Standard detection (no AI) uv run gh_tool find-duplicates /tmp/report.md # AI-powered detection uv run gh_tool find-duplicates /tmp/report.md --use-ai # Adjust AI confidence threshold uv run gh_tool find-duplicates /tmp/report.md --use-ai --ai-confidence 0.8 ``` ## Dependencies Added - `anthropic>=0.40.0` - Claude API SDK - `python-dotenv>=1.0.0` - Environment variable management ## Test Plan - [x] All existing tests pass - [x] Tested on 843 real CE issues with 100% accuracy - [x] Graceful fallback when API key not available - [x] AI reasoning included in markdown reports - [x] Code passes ruff linting πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude --- etc/scripts/gh_tool/.gitignore | 3 + etc/scripts/gh_tool/pyproject.toml | 2 + .../src/gh_tool/ai_duplicate_analyzer.py | 134 ++++++++++++++++++ etc/scripts/gh_tool/src/gh_tool/cli.py | 20 ++- .../gh_tool/src/gh_tool/duplicate_finder.py | 10 +- 5 files changed, 166 insertions(+), 3 deletions(-) create mode 100644 etc/scripts/gh_tool/src/gh_tool/ai_duplicate_analyzer.py diff --git a/etc/scripts/gh_tool/.gitignore b/etc/scripts/gh_tool/.gitignore index cf707e0ce..d6e22c730 100644 --- a/etc/scripts/gh_tool/.gitignore +++ b/etc/scripts/gh_tool/.gitignore @@ -14,3 +14,6 @@ uv.lock .vscode/ .idea/ *.swp + +# Environment +.env diff --git a/etc/scripts/gh_tool/pyproject.toml b/etc/scripts/gh_tool/pyproject.toml index 1a0d97542..3968cec92 100644 --- a/etc/scripts/gh_tool/pyproject.toml +++ b/etc/scripts/gh_tool/pyproject.toml @@ -8,8 +8,10 @@ version = "0.0.1" description = "GitHub automation tool for Compiler Explorer" requires-python = ">=3.12" dependencies = [ + "anthropic>=0.40.0", "click>=8.1.0", "pytest>=8.0.0", + "python-dotenv>=1.0.0", "ruff>=0.8.0", ] diff --git a/etc/scripts/gh_tool/src/gh_tool/ai_duplicate_analyzer.py b/etc/scripts/gh_tool/src/gh_tool/ai_duplicate_analyzer.py new file mode 100644 index 000000000..85b1c0c29 --- /dev/null +++ b/etc/scripts/gh_tool/src/gh_tool/ai_duplicate_analyzer.py @@ -0,0 +1,134 @@ +"""AI-powered duplicate issue detection using Claude.""" + +import os +from typing import Any + +import click +from anthropic import Anthropic +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + + +def get_anthropic_client() -> Anthropic | None: + """Get Anthropic client if API key is available.""" + api_key = os.getenv("ANTHROPIC_API_KEY") + if not api_key: + return None + return Anthropic(api_key=api_key) + + +def analyze_duplicate_group(issues: list[dict[str, Any]], client: Anthropic) -> dict[str, Any]: + """Use AI to determine if a group of issues are truly duplicates. + + Args: + issues: List of issue dictionaries with at least 'number' and 'title' fields + client: Anthropic client instance + + Returns: + dict with: + - is_duplicate: bool - whether issues are duplicates + - confidence: float - confidence score 0-1 + - reasoning: str - explanation of the decision + """ + # Format issues for the prompt + issue_list = "\n".join(f"- Issue #{issue['number']}: {issue['title']}" for issue in issues) + + prompt = f"""You are analyzing GitHub issues to determine if they are EXACT duplicates. + +Issues to analyze: +{issue_list} + +STRICT RULES for duplicates: +1. Different named tools/libraries are DIFFERENT: "fasm" β‰  "YASM" β‰  "AsmX" (even if all assemblers) +2. Similar categories are NOT duplicates: requesting different compilers/libraries/languages is NOT a duplicate +3. Related features are NOT duplicates: "language tooltips" β‰  "language detection" (different features) +4. Only spelling/capitalization variants are duplicates: "NumPy" = "numpy", "Forth" = "FORTH" + +EXAMPLES: +βœ“ DUPLICATE: "Add NumPy" + "Add numpy" (same library, different case) +βœ“ DUPLICATE: "GCC 13" + "GCC 13.1" (same compiler, version variants) +βœ— NOT DUPLICATE: "fasm" + "YASM" (different assemblers, even though both are assemblers) +βœ— NOT DUPLICATE: "OpenBLAS" + "OpenSSL" (different libraries starting with "Open") +βœ— NOT DUPLICATE: "ARM execution" + "EWARM execution" (EWARM is specific toolchain, not general ARM) +βœ— NOT DUPLICATE: "language tooltips" + "language detection" (different features in same domain) + +Be VERY strict. Only mark as duplicate if they request the EXACT SAME thing with minor spelling/version variations. + +Respond in JSON format: +{{ + "is_duplicate": true/false, + "confidence": 0.0-1.0, + "reasoning": "brief explanation" +}}""" + + try: + response = client.messages.create( + model="claude-sonnet-4-20250514", + max_tokens=500, + messages=[{"role": "user", "content": prompt}], + ) + + # Parse the response + content = response.content[0].text.strip() + + # Try to extract JSON from the response + import json + + # Find JSON block if wrapped in markdown + if "```json" in content: + content = content.split("```json")[1].split("```")[0].strip() + elif "```" in content: + content = content.split("```")[1].split("```")[0].strip() + + result = json.loads(content) + return { + "is_duplicate": result.get("is_duplicate", False), + "confidence": result.get("confidence", 0.0), + "reasoning": result.get("reasoning", ""), + } + + except Exception as e: + click.echo(f"Warning: AI analysis failed: {e}", err=True) + # On error, assume it's not a duplicate to avoid false positives + return {"is_duplicate": False, "confidence": 0.0, "reasoning": f"Error: {e}"} + + +def filter_groups_with_ai(groups: list[dict[str, Any]], min_confidence: float = 0.7) -> list[dict[str, Any]]: + """Filter duplicate groups using AI analysis. + + Args: + groups: List of duplicate groups from broadphase detection + min_confidence: Minimum confidence score to keep a group (default 0.7) + + Returns: + Filtered list of groups that AI confirms are duplicates + """ + client = get_anthropic_client() + if not client: + click.echo("Warning: ANTHROPIC_API_KEY not found in environment or .env file", err=True) + click.echo("Skipping AI analysis, returning all groups", err=True) + return groups + + click.echo(f"Analyzing {len(groups)} groups with AI...", err=True) + + filtered_groups = [] + for idx, group in enumerate(groups, 1): + click.echo(f" Analyzing group {idx}/{len(groups)}...", err=True) + + result = analyze_duplicate_group(group["issues"], client) + + if result["is_duplicate"] and result["confidence"] >= min_confidence: + # Add AI metadata to the group + group["ai_analysis"] = result + filtered_groups.append(group) + click.echo(f" βœ“ Duplicate (confidence: {result['confidence']:.2f})", err=True) + else: + click.echo( + f" βœ— Not duplicate (confidence: {result['confidence']:.2f}): {result['reasoning']}", + err=True, + ) + + click.echo(f"AI filtering: {len(groups)} β†’ {len(filtered_groups)} groups", err=True) + return filtered_groups diff --git a/etc/scripts/gh_tool/src/gh_tool/cli.py b/etc/scripts/gh_tool/src/gh_tool/cli.py index df553b472..188632d75 100644 --- a/etc/scripts/gh_tool/src/gh_tool/cli.py +++ b/etc/scripts/gh_tool/src/gh_tool/cli.py @@ -3,6 +3,7 @@ import click +from gh_tool.ai_duplicate_analyzer import filter_groups_with_ai from gh_tool.duplicate_finder import fetch_issues, find_duplicates, generate_report @@ -44,7 +45,18 @@ def main(): type=str, help="GitHub repository in owner/repo format (default: compiler-explorer/compiler-explorer)", ) -def find_duplicates_cmd(output_file, threshold, state, min_age, limit, repo): +@click.option( + "--use-ai", + is_flag=True, + help="Use AI to refine duplicate detection (requires ANTHROPIC_API_KEY in .env)", +) +@click.option( + "--ai-confidence", + default=0.7, + type=click.FloatRange(0, 1), + help="Minimum AI confidence score to keep a group (default: 0.7)", +) +def find_duplicates_cmd(output_file, threshold, state, min_age, limit, repo, use_ai, ai_confidence): """Find potential duplicate issues in the compiler-explorer repository. OUTPUT_FILE is the path where the markdown report will be saved. @@ -67,10 +79,14 @@ def find_duplicates_cmd(output_file, threshold, state, min_age, limit, repo): click.echo(f"Fetching {state} issues...", err=True) issues = fetch_issues(state, limit, repo) - # Find duplicates + # Find duplicates (broadphase) click.echo(f"Analyzing {len(issues)} issues with threshold {threshold}...", err=True) groups = find_duplicates(issues, threshold, min_age) + # Refine with AI if requested + if use_ai: + groups = filter_groups_with_ai(groups, ai_confidence) + # Generate report generate_report(groups, output_file) click.echo(f"Found {len(groups)} potential duplicate groups", err=True) diff --git a/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py b/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py index 9b64889ef..84ed23260 100755 --- a/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py +++ b/etc/scripts/gh_tool/src/gh_tool/duplicate_finder.py @@ -141,7 +141,15 @@ def generate_report(groups: list[dict[str, Any]], output_file: str) -> None: for idx, group in enumerate(sorted(groups, key=lambda x: x["max_similarity"], reverse=True), 1): similarity_pct = int(group["max_similarity"] * 100) - output.append(f"## Group {idx} ({similarity_pct}% similar)\n") + + # Add AI analysis if available + if "ai_analysis" in group: + ai = group["ai_analysis"] + confidence_pct = int(ai["confidence"] * 100) + output.append(f"## Group {idx} ({similarity_pct}% similar) - AI Confidence: {confidence_pct}%\n") + output.append(f"\n**AI Analysis:** {ai['reasoning']}\n") + else: + output.append(f"## Group {idx} ({similarity_pct}% similar)\n") for issue in sorted(group["issues"], key=lambda x: x["createdAt"]): output.append(format_issue(issue) + "\n") From 3fc36bb3225dadf63c2fdf3baaad5f423135b2cf Mon Sep 17 00:00:00 2001 From: Matt Godbolt Date: Tue, 7 Oct 2025 16:50:14 -0500 Subject: [PATCH 10/11] Tweaks --- .../src/gh_tool/ai_duplicate_analyzer.py | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/etc/scripts/gh_tool/src/gh_tool/ai_duplicate_analyzer.py b/etc/scripts/gh_tool/src/gh_tool/ai_duplicate_analyzer.py index 85b1c0c29..ad56339ac 100644 --- a/etc/scripts/gh_tool/src/gh_tool/ai_duplicate_analyzer.py +++ b/etc/scripts/gh_tool/src/gh_tool/ai_duplicate_analyzer.py @@ -66,13 +66,18 @@ Respond in JSON format: try: response = client.messages.create( model="claude-sonnet-4-20250514", - max_tokens=500, + max_tokens=2000, messages=[{"role": "user", "content": prompt}], ) # Parse the response content = response.content[0].text.strip() + # Debug logging for empty responses + if not content: + click.echo(f" Warning: Empty response from AI for group with {len(issues)} issues", err=True) + return {"is_duplicate": False, "confidence": 0.0, "reasoning": "Empty AI response"} + # Try to extract JSON from the response import json @@ -89,8 +94,12 @@ Respond in JSON format: "reasoning": result.get("reasoning", ""), } + except json.JSONDecodeError as e: + click.echo(f" Warning: Invalid JSON from AI (group size: {len(issues)})", err=True) + click.echo(f" First 200 chars of response: {content[:200] if content else '(empty)'}...", err=True) + return {"is_duplicate": False, "confidence": 0.0, "reasoning": f"JSON parse error: {e}"} except Exception as e: - click.echo(f"Warning: AI analysis failed: {e}", err=True) + click.echo(f" Warning: AI analysis failed: {e}", err=True) # On error, assume it's not a duplicate to avoid false positives return {"is_duplicate": False, "confidence": 0.0, "reasoning": f"Error: {e}"} @@ -115,7 +124,12 @@ def filter_groups_with_ai(groups: list[dict[str, Any]], min_confidence: float = filtered_groups = [] for idx, group in enumerate(groups, 1): - click.echo(f" Analyzing group {idx}/{len(groups)}...", err=True) + num_issues = len(group["issues"]) + click.echo(f" Analyzing group {idx}/{len(groups)} ({num_issues} issues)...", err=True) + + # Warn about very large groups + if num_issues > 20: + click.echo(f" ⚠ Large group ({num_issues} issues) - this may be expensive", err=True) result = analyze_duplicate_group(group["issues"], client) From 98a417aa2ccc4bcc8c7a8fae8022f4b3c9d9381b Mon Sep 17 00:00:00 2001 From: narpfel Date: Wed, 8 Oct 2025 21:56:53 +0200 Subject: [PATCH 11/11] Fix comment syntax highlighting for Haskell (#8135) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This adds syntax highlighting for block comments `{- ... -}` and configuration to support the β€œadd comment” and β€œremove comment” keyboard shortcuts. --- static/modes/haskell-mode.ts | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/static/modes/haskell-mode.ts b/static/modes/haskell-mode.ts index 6d9fa96cd..c2f42e7bb 100644 --- a/static/modes/haskell-mode.ts +++ b/static/modes/haskell-mode.ts @@ -77,20 +77,30 @@ function definition(): monaco.languages.IMonarchLanguage { ], comment: [ - [/[^/*]+/, 'comment'], - [/\*\//, 'comment', '@pop'], - [/[/*]/, 'comment'], + [/[^{-]+/, 'comment'], + [/{-/, 'comment', '@push'], + [/-}/, 'comment', '@pop'], + [/[{-]/, 'comment'], ], whitespace: [ [/[ \t\r\n]+/, 'white'], - [/\/\*/, 'comment', '@comment'], - [/\/\/.*$/, 'comment'], + [/{-/, 'comment', '@comment'], [/--.*$/, 'comment'], ], }, }; } +function configuration(): monaco.languages.LanguageConfiguration { + return { + comments: { + lineComment: '--', + blockComment: ['{-', '-}'], + }, + }; +} + monaco.languages.register({id: 'haskell'}); monaco.languages.setMonarchTokensProvider('haskell', definition()); +monaco.languages.setLanguageConfiguration('haskell', configuration());