mirror of
https://github.com/microsoft/PowerToys.git
synced 2026-07-01 07:59:36 +02:00
Compare commits
1 Commits
powerscrip
...
issue/3268
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db10cf2d83 |
@@ -1 +0,0 @@
|
||||
../.github/copilot-instructions.md
|
||||
@@ -1 +0,0 @@
|
||||
../.github/agents
|
||||
@@ -1 +0,0 @@
|
||||
../.github/prompts
|
||||
@@ -1 +0,0 @@
|
||||
../.github/instructions
|
||||
@@ -1 +0,0 @@
|
||||
../.github/skills
|
||||
@@ -1,5 +1,5 @@
|
||||
# yaml-language-server: $schema=https://aka.ms/configuration-dsc-schema/0.2
|
||||
# Reference: https://github.com/microsoft/PowerToys/blob/main/doc/devdocs/readme.md#getting-started
|
||||
# Reference: https://github.com/microsoft/PowerToys/blob/main/doc/devdocs/readme.md#compiling-powertoys
|
||||
properties:
|
||||
resources:
|
||||
- resource: Microsoft.Windows.Settings/WindowsSettings
|
||||
@@ -13,11 +13,11 @@ properties:
|
||||
- resource: Microsoft.WinGet.DSC/WinGetPackage
|
||||
id: vsPackage
|
||||
directives:
|
||||
description: Install Visual Studio 2026 Enterprise (Any edition will work)
|
||||
description: Install Visual Studio 2022 Enterprise (Any edition will work)
|
||||
# Requires elevation for the set operation
|
||||
securityContext: elevated
|
||||
settings:
|
||||
id: Microsoft.VisualStudio.Enterprise
|
||||
id: Microsoft.VisualStudio.2022.Enterprise
|
||||
source: winget
|
||||
- resource: Microsoft.VisualStudio.DSC/VSComponents
|
||||
dependsOn:
|
||||
@@ -29,7 +29,7 @@ properties:
|
||||
securityContext: elevated
|
||||
settings:
|
||||
productId: Microsoft.VisualStudio.Product.Enterprise
|
||||
channelId: VisualStudio.18.Release
|
||||
channelId: VisualStudio.17.Release
|
||||
vsConfigFile: '${WinGetConfigRoot}\..\.vsconfig'
|
||||
configurationVersion: 0.2.0
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# yaml-language-server: $schema=https://aka.ms/configuration-dsc-schema/0.2
|
||||
# Reference: https://github.com/microsoft/PowerToys/blob/main/doc/devdocs/readme.md#getting-started
|
||||
# Reference: https://github.com/microsoft/PowerToys/blob/main/doc/devdocs/readme.md#compiling-powertoys
|
||||
properties:
|
||||
resources:
|
||||
- resource: Microsoft.Windows.Settings/WindowsSettings
|
||||
@@ -13,11 +13,11 @@ properties:
|
||||
- resource: Microsoft.WinGet.DSC/WinGetPackage
|
||||
id: vsPackage
|
||||
directives:
|
||||
description: Install Visual Studio 2026 Professional (Any edition will work)
|
||||
description: Install Visual Studio 2022 Professional (Any edition will work)
|
||||
# Requires elevation for the set operation
|
||||
securityContext: elevated
|
||||
settings:
|
||||
id: Microsoft.VisualStudio.Professional
|
||||
id: Microsoft.VisualStudio.2022.Professional
|
||||
source: winget
|
||||
- resource: Microsoft.VisualStudio.DSC/VSComponents
|
||||
dependsOn:
|
||||
@@ -29,7 +29,7 @@ properties:
|
||||
securityContext: elevated
|
||||
settings:
|
||||
productId: Microsoft.VisualStudio.Product.Professional
|
||||
channelId: VisualStudio.18.Release
|
||||
channelId: VisualStudio.17.Release
|
||||
vsConfigFile: '${WinGetConfigRoot}\..\.vsconfig'
|
||||
configurationVersion: 0.2.0
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# yaml-language-server: $schema=https://aka.ms/configuration-dsc-schema/0.2
|
||||
# Reference: https://github.com/microsoft/PowerToys/blob/main/doc/devdocs/readme.md#getting-started
|
||||
# Reference: https://github.com/microsoft/PowerToys/blob/main/doc/devdocs/readme.md#compiling-powertoys
|
||||
properties:
|
||||
resources:
|
||||
- resource: Microsoft.Windows.Settings/WindowsSettings
|
||||
@@ -13,11 +13,11 @@ properties:
|
||||
- resource: Microsoft.WinGet.DSC/WinGetPackage
|
||||
id: vsPackage
|
||||
directives:
|
||||
description: Install Visual Studio 2026 Community (Any edition will work)
|
||||
description: Install Visual Studio 2022 Community (Any edition will work)
|
||||
# Requires elevation for the set operation
|
||||
securityContext: elevated
|
||||
settings:
|
||||
id: Microsoft.VisualStudio.Community
|
||||
id: Microsoft.VisualStudio.2022.Community
|
||||
source: winget
|
||||
- resource: Microsoft.VisualStudio.DSC/VSComponents
|
||||
dependsOn:
|
||||
@@ -29,7 +29,7 @@ properties:
|
||||
securityContext: elevated
|
||||
settings:
|
||||
productId: Microsoft.VisualStudio.Product.Community
|
||||
channelId: VisualStudio.18.Release
|
||||
channelId: VisualStudio.17.Release
|
||||
vsConfigFile: '${WinGetConfigRoot}\..\.vsconfig'
|
||||
configurationVersion: 0.2.0
|
||||
|
||||
|
||||
11
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
11
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -40,6 +40,7 @@ body:
|
||||
- Other (please specify in "Steps to Reproduce")
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Area(s) with issue?
|
||||
@@ -57,7 +58,6 @@ body:
|
||||
- Environment Variables
|
||||
- FancyZones
|
||||
- FancyZones Editor
|
||||
- Grab And Move
|
||||
- File Locksmith
|
||||
- "File Explorer: Preview Pane"
|
||||
- "File Explorer: Thumbnail preview"
|
||||
@@ -70,7 +70,6 @@ body:
|
||||
- Mouse Without Borders
|
||||
- New+
|
||||
- Peek
|
||||
- Power Display
|
||||
- PowerRename
|
||||
- PowerToys Run
|
||||
- Quick Accent
|
||||
@@ -107,13 +106,7 @@ body:
|
||||
placeholder: What happened instead?
|
||||
validations:
|
||||
required: false
|
||||
- type: upload
|
||||
id: bugreportfile
|
||||
attributes:
|
||||
label: Upload Bug Report ZIP-file
|
||||
description: Right-clicking the PowerToys tray icon in the taskbar and selecting “Report bug” generates a ZIP file containing diagnostic information about your setup and PowerToys logs, helping us better understand and troubleshoot the issue.
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- id: additionalInfo
|
||||
type: textarea
|
||||
attributes:
|
||||
|
||||
97
.github/actions/spell-check/allow/code.txt
vendored
97
.github/actions/spell-check/allow/code.txt
vendored
@@ -1,7 +1,6 @@
|
||||
# COLORS
|
||||
|
||||
argb
|
||||
Bgr
|
||||
bgra
|
||||
BLACKONWHITE
|
||||
BLUEGRAY
|
||||
@@ -17,9 +16,8 @@ LIGHTTURQUOISE
|
||||
NCol
|
||||
OLIVEGREEN
|
||||
PALEBLUE
|
||||
pargb
|
||||
pbgra
|
||||
SRGBTo
|
||||
PArgb
|
||||
Pbgra
|
||||
WHITEONBLACK
|
||||
|
||||
|
||||
@@ -30,7 +28,6 @@ RUS
|
||||
|
||||
AYUV
|
||||
bak
|
||||
HDP
|
||||
Bcl
|
||||
bgcode
|
||||
Deflatealgorithm
|
||||
@@ -41,7 +38,6 @@ Gbps
|
||||
gcode
|
||||
Heatshrink
|
||||
Mbits
|
||||
Kbits
|
||||
MBs
|
||||
mkv
|
||||
msix
|
||||
@@ -51,7 +47,6 @@ resw
|
||||
resx
|
||||
srt
|
||||
Stereolithography
|
||||
taskmgr
|
||||
terabyte
|
||||
UYVY
|
||||
xbf
|
||||
@@ -102,7 +97,6 @@ Yubico
|
||||
Perplexity
|
||||
Groq
|
||||
svgl
|
||||
devhome
|
||||
|
||||
# KEYS
|
||||
|
||||
@@ -128,7 +122,6 @@ HOLDSPACE
|
||||
HOLDBACKSPACE
|
||||
IDIGNORE
|
||||
KBDLLHOOKSTRUCT
|
||||
keydowns
|
||||
keyevent
|
||||
LAlt
|
||||
LBUTTON
|
||||
@@ -187,12 +180,6 @@ xmlutil
|
||||
# Prefix
|
||||
pcs
|
||||
|
||||
# EXPRTK / C++ MATH
|
||||
|
||||
ifunction
|
||||
isinf
|
||||
isnan
|
||||
|
||||
# User32.SYSTEM_METRICS_INDEX.cs
|
||||
|
||||
CLEANBOOT
|
||||
@@ -308,8 +295,6 @@ pwa
|
||||
|
||||
AOT
|
||||
Aot
|
||||
ify
|
||||
TFM
|
||||
|
||||
# YML
|
||||
onefuzz
|
||||
@@ -317,7 +302,6 @@ onefuzz
|
||||
# NameInCode
|
||||
leilzh
|
||||
mengyuanchen
|
||||
contoso
|
||||
|
||||
# DllName
|
||||
testhost
|
||||
@@ -329,7 +313,6 @@ xef
|
||||
xes
|
||||
PACKAGEVERSIONNUMBER
|
||||
APPXMANIFESTVERSION
|
||||
PROGMAN
|
||||
|
||||
# MRU lists
|
||||
CACHEWRITE
|
||||
@@ -337,61 +320,8 @@ MRUCMPPROC
|
||||
MRUINFO
|
||||
REGSTR
|
||||
|
||||
#Xaml
|
||||
NVI
|
||||
Storyboards
|
||||
|
||||
# Misc Win32 APIs and PInvokes
|
||||
DEFAULTTONEAREST
|
||||
INVOKEIDLIST
|
||||
LCMAP
|
||||
MEMORYSTATUSEX
|
||||
ABE
|
||||
Mdt
|
||||
HTCAPTION
|
||||
POSCHANGED
|
||||
QPC
|
||||
QUERYPOS
|
||||
SETAUTOHIDEBAR
|
||||
ULW
|
||||
WINDOWPOS
|
||||
WINEVENTPROC
|
||||
WORKERW
|
||||
FULLSCREENAPP
|
||||
ACLO
|
||||
CACLI
|
||||
DOENVSUBST
|
||||
FILESYSONLY
|
||||
URLIS
|
||||
WAITTIMEOUT
|
||||
DEFAULTTONEAREST
|
||||
DWRITE
|
||||
LWIN
|
||||
VCENTER
|
||||
VREDRAW
|
||||
|
||||
# COM/WinRT interface prefixes and type fragments
|
||||
BAlt
|
||||
BShift
|
||||
Cmanifest
|
||||
Cmodule
|
||||
Cuuid
|
||||
Dng
|
||||
IApplication
|
||||
IDisposable
|
||||
IEnum
|
||||
IFolder
|
||||
IInitialize
|
||||
IMemory
|
||||
IOle
|
||||
ipreview
|
||||
IProperty
|
||||
IShell
|
||||
ithumbnail
|
||||
IVirtual
|
||||
|
||||
# Test frameworks
|
||||
MSTEST
|
||||
|
||||
# PowerRename metadata pattern abbreviations (used in tests and regex patterns)
|
||||
DDDD
|
||||
@@ -403,12 +333,6 @@ YYY
|
||||
# Unicode
|
||||
precomposed
|
||||
|
||||
# names of characters
|
||||
zwsp
|
||||
|
||||
# mermaid
|
||||
autonumber
|
||||
|
||||
# GitHub issue/PR commands
|
||||
azp
|
||||
feedbackhub
|
||||
@@ -418,20 +342,3 @@ reportbug
|
||||
#ffmpeg
|
||||
crf
|
||||
nostdin
|
||||
|
||||
# Performance counter keys
|
||||
engtype
|
||||
Nonpaged
|
||||
|
||||
# XAML
|
||||
Untargeted
|
||||
|
||||
# Program names
|
||||
SEARCHHOST
|
||||
SHELLEXPERIENCEHOST
|
||||
SHELLHOST
|
||||
STARTMENUEXPERIENCEHOST
|
||||
WIDGETBOARD
|
||||
|
||||
# URIs
|
||||
actioncenter
|
||||
|
||||
8
.github/actions/spell-check/allow/names.txt
vendored
8
.github/actions/spell-check/allow/names.txt
vendored
@@ -178,9 +178,7 @@ Taras
|
||||
TBM
|
||||
Teutsch
|
||||
tilovell
|
||||
traies
|
||||
Triet
|
||||
udit
|
||||
urnotdfs
|
||||
vednig
|
||||
waaverecords
|
||||
@@ -194,7 +192,6 @@ ycv
|
||||
yeelam
|
||||
Yuniardi
|
||||
yuyoyuppe
|
||||
zadjii
|
||||
Zeol
|
||||
Zhao
|
||||
Zhaopeng
|
||||
@@ -209,8 +206,6 @@ Bilibili
|
||||
BVID
|
||||
capturevideosample
|
||||
cmdow
|
||||
contoso
|
||||
Contoso
|
||||
Controlz
|
||||
cortana
|
||||
devhints
|
||||
@@ -226,7 +221,6 @@ Moq
|
||||
mozilla
|
||||
mspaint
|
||||
Newtonsoft
|
||||
NVIDIA
|
||||
onenote
|
||||
openai
|
||||
Quickime
|
||||
@@ -234,7 +228,6 @@ regedit
|
||||
roslyn
|
||||
Skia
|
||||
Spotify
|
||||
taskmgr
|
||||
tldr
|
||||
Vanara
|
||||
wangyi
|
||||
@@ -250,3 +243,4 @@ xamlstyler
|
||||
Xavalon
|
||||
Xbox
|
||||
Youdao
|
||||
zadjii
|
||||
|
||||
422
.github/actions/spell-check/allow/zoomit.txt
vendored
422
.github/actions/spell-check/allow/zoomit.txt
vendored
@@ -1,422 +0,0 @@
|
||||
accelscroll
|
||||
acq
|
||||
ADDTO
|
||||
ADDTOOL
|
||||
adr
|
||||
Adr
|
||||
ALWAYSTIP
|
||||
APPLYTOSUBMENUS
|
||||
ARCHMASK
|
||||
archs
|
||||
AUDCLNT
|
||||
autocorr
|
||||
avx
|
||||
axisdefer
|
||||
axisflip
|
||||
axisstart
|
||||
backlight
|
||||
BEOS
|
||||
bfi
|
||||
BFIN
|
||||
bfly
|
||||
BGRX
|
||||
bitmaps
|
||||
bitrev
|
||||
blits
|
||||
Borgerding
|
||||
Borland
|
||||
breakc
|
||||
BREAKSCR
|
||||
BUFFERFLAGS
|
||||
bugzilla
|
||||
Cands
|
||||
capturepath
|
||||
cbs
|
||||
centiseconds
|
||||
cexp
|
||||
cfx
|
||||
cfy
|
||||
cgem
|
||||
cifx
|
||||
cify
|
||||
CLASSW
|
||||
coeffs
|
||||
colblocks
|
||||
constantbuffer
|
||||
coprime
|
||||
cpuid
|
||||
cpx
|
||||
CREATEDIBSECTION
|
||||
CREATESTRUCTW
|
||||
crossfades
|
||||
Ctl
|
||||
CTLCOLOR
|
||||
CTLCOLORBTN
|
||||
CTLCOLORDLG
|
||||
CTLCOLOREDIT
|
||||
CTLCOLORLISTBOX
|
||||
CTrim
|
||||
CVTEPI
|
||||
DBuffer
|
||||
dcl
|
||||
dct
|
||||
ddx
|
||||
ddy
|
||||
Deinterleave
|
||||
denoise
|
||||
denoised
|
||||
DEVSOURCE
|
||||
DFCS
|
||||
DIVSCALAR
|
||||
DJGPP
|
||||
dlg
|
||||
dlu
|
||||
dnn
|
||||
DONTCARE
|
||||
downsample
|
||||
DRAWITEM
|
||||
DRAWITEMSTRUCT
|
||||
droppedband
|
||||
Droppedband
|
||||
DSPs
|
||||
dsum
|
||||
dupburst
|
||||
dupsegments
|
||||
DWLP
|
||||
eband
|
||||
ebx
|
||||
ECX
|
||||
EDITCONTROL
|
||||
EDSP
|
||||
emmintrin
|
||||
EMX
|
||||
ENABLEHOOK
|
||||
endloop
|
||||
ENDOFSTREAM
|
||||
ener
|
||||
enh
|
||||
ettings
|
||||
expectedlock
|
||||
expf
|
||||
fabs
|
||||
fabsf
|
||||
facbuf
|
||||
fastscroll
|
||||
FDE
|
||||
ffast
|
||||
FIXDIV
|
||||
floorf
|
||||
fmadd
|
||||
fout
|
||||
fstride
|
||||
fxc
|
||||
GETCHANNELRECT
|
||||
GETCHECK
|
||||
GETCOUNT
|
||||
GETDISPINFO
|
||||
GETSCREENSAVEACTIVE
|
||||
GETSCREENSAVETIMEOUT
|
||||
GETTHUMBRECT
|
||||
GIFs
|
||||
glu
|
||||
groupshared
|
||||
gru
|
||||
hcfdark
|
||||
hcfwhitespace
|
||||
hlsl
|
||||
Hsieh
|
||||
hstride
|
||||
HTBOTTOMRIGHT
|
||||
HTHEME
|
||||
htol
|
||||
ICONINFORMATION
|
||||
ICONWARNING
|
||||
idct
|
||||
IDIn
|
||||
IDISHWND
|
||||
ifft
|
||||
igc
|
||||
ilog
|
||||
imad
|
||||
imax
|
||||
imin
|
||||
immintrin
|
||||
Inj
|
||||
interp
|
||||
inttypes
|
||||
ishl
|
||||
itof
|
||||
jumprecover
|
||||
kfft
|
||||
kheight
|
||||
kissfft
|
||||
KSDATAFORMAT
|
||||
ksize
|
||||
ktime
|
||||
lastg
|
||||
latestcapture
|
||||
ldx
|
||||
LEFTNOWORDWRAP
|
||||
legitjumps
|
||||
lenmem
|
||||
letterbox
|
||||
lld
|
||||
lldx
|
||||
llu
|
||||
llums
|
||||
logfont
|
||||
lookback
|
||||
lpc
|
||||
lpcnet
|
||||
LPNMHDR
|
||||
LPNMTTDISPINFO
|
||||
lround
|
||||
lte
|
||||
luma
|
||||
Luma
|
||||
maj
|
||||
manualdrop
|
||||
maskcache
|
||||
maxabs
|
||||
maxcorr
|
||||
MAXFACTORS
|
||||
maxperiod
|
||||
maxstep
|
||||
memalign
|
||||
memid
|
||||
memneeded
|
||||
MENUINFO
|
||||
MFSTARTUP
|
||||
mfxhw
|
||||
mic
|
||||
middledrop
|
||||
minperiod
|
||||
MIPSr
|
||||
MJPEG
|
||||
MMRESULT
|
||||
momentumreversal
|
||||
movc
|
||||
mrate
|
||||
mrt
|
||||
MULBYSCALAR
|
||||
MULC
|
||||
MWERKS
|
||||
mycfg
|
||||
narrowstrip
|
||||
nbak
|
||||
nbytes
|
||||
ncapture
|
||||
nchw
|
||||
ncm
|
||||
nduplicates
|
||||
nfft
|
||||
NHWC
|
||||
niterations
|
||||
nmonitor
|
||||
nnet
|
||||
NONCLIENTMETRICS
|
||||
NONOTIFY
|
||||
nonvle
|
||||
normf
|
||||
nredraw
|
||||
nstop
|
||||
nsubpixel
|
||||
ntorn
|
||||
numthreads
|
||||
nvw
|
||||
Octasic
|
||||
osc
|
||||
OSCE
|
||||
ovflw
|
||||
OWNERDRAW
|
||||
PBGRA
|
||||
periodictrap
|
||||
pfdc
|
||||
pillarbox
|
||||
playhead
|
||||
pnmh
|
||||
pointerreuse
|
||||
PPW
|
||||
prereq
|
||||
PSHR
|
||||
pstdint
|
||||
PSWA
|
||||
pwfx
|
||||
QCONST
|
||||
qpc
|
||||
Qpc
|
||||
quantums
|
||||
qweight
|
||||
RCSEGMODEL
|
||||
RCZOOMITSCR
|
||||
readback
|
||||
READERF
|
||||
realcapture
|
||||
REFKNOWNFOLDERID
|
||||
relu
|
||||
reposted
|
||||
RETURNCMD
|
||||
rnn
|
||||
rnnoise
|
||||
rotateleft
|
||||
rsqrt
|
||||
rtcd
|
||||
RTEXT
|
||||
RTH
|
||||
rtvs
|
||||
SCALEIN
|
||||
SCALEOUT
|
||||
SCREENSAVE
|
||||
SCRNSAVE
|
||||
SCRNSAVECONFIGURE
|
||||
scrnsavw
|
||||
Scrnsavw
|
||||
scrollramp
|
||||
SCROLLSIZEGRIP
|
||||
selfie
|
||||
selftest
|
||||
SETBARCOLOR
|
||||
SETBKCOLOR
|
||||
SETDEFID
|
||||
SETRECT
|
||||
SETSCREENSAVETIMEOUT
|
||||
SETTIPSIDE
|
||||
sgem
|
||||
sgemv
|
||||
sgv
|
||||
SHAREMODE
|
||||
SHAREVIOLATION
|
||||
shortlist
|
||||
simde
|
||||
siv
|
||||
slowthenfast
|
||||
smallstart
|
||||
SNIPOCR
|
||||
softmax
|
||||
sqrtf
|
||||
SROUND
|
||||
srvs
|
||||
ssi
|
||||
startuprecovery
|
||||
stdint
|
||||
stf
|
||||
stopafter
|
||||
STREAMFLAGS
|
||||
SUBFROM
|
||||
subias
|
||||
submix
|
||||
sxx
|
||||
sxy
|
||||
symbian
|
||||
synthesising
|
||||
syy
|
||||
tallportal
|
||||
TBTS
|
||||
tci
|
||||
tcsicmp
|
||||
TEXTCALLBACK
|
||||
TEXTMETRIC
|
||||
tgsm
|
||||
THIRDPARTY
|
||||
tinystep
|
||||
tme
|
||||
toolbars
|
||||
TOOLINFO
|
||||
TRACKMOUSEEVENT
|
||||
TRIANGLELIST
|
||||
TTM
|
||||
TTN
|
||||
TWID
|
||||
UADD
|
||||
uav
|
||||
uavs
|
||||
uge
|
||||
Unadvise
|
||||
upscaled
|
||||
upscales
|
||||
USUB
|
||||
utof
|
||||
vad
|
||||
vaddq
|
||||
vaddvq
|
||||
valgrind
|
||||
Valin
|
||||
vandq
|
||||
vblank
|
||||
vcgeq
|
||||
vdup
|
||||
vectorizer
|
||||
VERTID
|
||||
VIDCAP
|
||||
vld
|
||||
vle
|
||||
Vle
|
||||
VLE
|
||||
vminq
|
||||
vmlal
|
||||
vmull
|
||||
vqaddq
|
||||
VSHR
|
||||
vshrn
|
||||
vsntprintf
|
||||
vsnwprintf
|
||||
vsync
|
||||
WASAPI
|
||||
WAVEFORMATEX
|
||||
WAVEFORMATEXTENSIBLE
|
||||
webcam
|
||||
Webcam
|
||||
webcams
|
||||
Wextra
|
||||
wfopen
|
||||
WGC
|
||||
wideportal
|
||||
wil
|
||||
WMU
|
||||
wrapjump
|
||||
wtol
|
||||
WTSSESSION
|
||||
WTSUn
|
||||
wxyz
|
||||
xchg
|
||||
xcorr
|
||||
XEnd
|
||||
Xfl
|
||||
Xiang
|
||||
Xiph
|
||||
xmmintrin
|
||||
xptr
|
||||
xshift
|
||||
XStart
|
||||
XStep
|
||||
xxxy
|
||||
xxyx
|
||||
xxyz
|
||||
xyw
|
||||
xywx
|
||||
xyxx
|
||||
xyxz
|
||||
xyzw
|
||||
xyzx
|
||||
xzwx
|
||||
xzxx
|
||||
Yfl
|
||||
YInternal
|
||||
yshift
|
||||
YUV
|
||||
yyyx
|
||||
yyzw
|
||||
yzw
|
||||
yzwy
|
||||
yzyy
|
||||
Zhou
|
||||
Zhu
|
||||
ZMBS
|
||||
zncc
|
||||
Zncc
|
||||
ZNCC
|
||||
zrh
|
||||
zwzz
|
||||
zyzw
|
||||
zzwz
|
||||
zzzw
|
||||
73
.github/actions/spell-check/candidate.patterns
vendored
73
.github/actions/spell-check/candidate.patterns
vendored
@@ -1,3 +1,6 @@
|
||||
# D2D
|
||||
#D?2D
|
||||
|
||||
# Repeated letters
|
||||
\b([a-z])\g{-1}{2,}\b
|
||||
|
||||
@@ -11,7 +14,7 @@
|
||||
^.*\b[Cc][Ss][Pp][Ee][Ll]{2}:\s*[Dd][Ii][Ss][Aa][Bb][Ll][Ee]-[Ll][Ii][Nn][Ee]\b
|
||||
|
||||
# copyright
|
||||
Copyright (?:\([Cc]\)|©|)(?:[-\d, ]|and)+(?: [A-Z][a-z]+ [A-Z][a-z]+,?)+
|
||||
Copyright (?:\([Cc]\)|)(?:[-\d, ]|and)+(?: [A-Z][a-z]+ [A-Z][a-z]+,?)+
|
||||
|
||||
# patch hunk comments
|
||||
^@@ -\d+(?:,\d+|) \+\d+(?:,\d+|) @@ .*
|
||||
@@ -19,10 +22,10 @@ Copyright (?:\([Cc]\)|©|)(?:[-\d, ]|and)+(?: [A-Z][a-z]+ [A-Z][a-z]+,?)+
|
||||
index (?:[0-9a-z]{7,40},|)[0-9a-z]{7,40}\.\.[0-9a-z]{7,40}
|
||||
|
||||
# file permissions
|
||||
(?:^|['"`\s])(?!-+\s)[-bcdLlpsw](?:[-r][-w][-Ssx]){2}[-r][-w][-SsTtx]\+?['"`\s]
|
||||
['"`\s][-bcdLlpsw](?:[-r][-w][-Ssx]){2}[-r][-w][-SsTtx]\+?['"`\s]
|
||||
|
||||
# css fonts
|
||||
\bfont(?:-family(?:[-\w+]*)|):[^;}]+
|
||||
\bfont(?:-family|):[^;}]+
|
||||
|
||||
# css url wrappings
|
||||
\burl\([^)]+\)
|
||||
@@ -87,9 +90,6 @@ arn:aws:[-/:\w]+
|
||||
# AWS VPC
|
||||
vpc-\w+
|
||||
|
||||
# Azure AD
|
||||
\baad\.\w{48}\b
|
||||
|
||||
# While you could try to match `http://` and `https://` by using `s?` in `https?://`, sometimes there
|
||||
# YouTube url
|
||||
\b(?:(?:www\.|)youtube\.com|youtu.be)/(?:channel/|embed/|user/|playlist\?list=|watch\?v=|v/|)[-a-zA-Z0-9?&=_%]*
|
||||
@@ -171,7 +171,7 @@ themes\.googleusercontent\.com/static/fonts/[^/\s"]+/v\d+/[^.]+.
|
||||
GHSA(?:-[0-9a-z]{4}){3}
|
||||
|
||||
# GitHub actions
|
||||
\buses:\s+(['"]?)[-\w.]+/[-\w./]+@[-\w.]+\g{-1}
|
||||
\buses:\s+[-\w.]+/[-\w./]+@[-\w.]+
|
||||
|
||||
# GitLab commit
|
||||
\bgitlab\.[^/\s"]*/\S+/\S+/commit/[0-9a-f]{7,16}#[0-9a-f]{40}\b
|
||||
@@ -240,7 +240,7 @@ accounts\.binance\.com/[a-z/]*oauth/authorize\?[-0-9a-zA-Z&%]*
|
||||
\bmedium\.com/@?[^/\s"]+/[-\w]+
|
||||
|
||||
# microsoft
|
||||
\b(?:https?://|)(?:(?:(?:blogs|download\.visualstudio|docs|msdn2?|research)\.|)microsoft|blogs\.msdn)\.co(?:m|\.\w\w)/[-_a-zA-Z0-9()=./%?#]*
|
||||
\b(?:https?://|)(?:(?:(?:blogs|download\.visualstudio|docs|msdn2?|research)\.|)microsoft|blogs\.msdn)\.co(?:m|\.\w\w)/[-_a-zA-Z0-9()=./%]*
|
||||
# powerbi
|
||||
\bapp\.powerbi\.com/reportEmbed/[^"' ]*
|
||||
# vs devops
|
||||
@@ -414,7 +414,7 @@ ipfs://[0-9a-zA-Z]{3,}
|
||||
\bgetopts\s+(?:"[^"]+"|'[^']+')
|
||||
|
||||
# ANSI color codes
|
||||
(?:\\(?:u00|x)1[Bb]|\\03[1-7]|\x1b|\\u\{1[Bb]\})\[(?:\d+(?:;\d+)*|)m
|
||||
(?:\\(?:u00|x)1[Bb]|\\03[1-7]|\x1b|\\u\{1[Bb]\})\[\d+(?:;\d+)*m
|
||||
|
||||
# URL escaped characters
|
||||
%[0-9A-F][A-F](?=[A-Za-z])
|
||||
@@ -431,7 +431,7 @@ sha\d+:[0-9a-f]*?[a-f]{3,}[0-9a-f]*
|
||||
# sha-... -- uses a fancy capture
|
||||
(\\?['"]|")[0-9a-f]{40,}\g{-1}
|
||||
# hex runs
|
||||
\b(?=(?:[a-fA-F]{0,2}\d)*[a-fA-F]{3})[0-9a-fA-F]{16,}\b
|
||||
\b[0-9a-fA-F]{16,}\b
|
||||
# hex in url queries
|
||||
=[0-9a-fA-F]*?(?:[A-F]{3,}|[a-f]{3,})[0-9a-fA-F]*?&
|
||||
# ssh
|
||||
@@ -455,11 +455,7 @@ LS0tLS1CRUdJT.*
|
||||
|
||||
# uuid:
|
||||
\b[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}\b
|
||||
|
||||
# unicode escaped characters (4)
|
||||
\\u[0-9a-fA-F]{4}
|
||||
|
||||
# hex digits including css/html color classes
|
||||
# hex digits including css/html color classes:
|
||||
(?:[\\0][xX]|\\u\{?|[uU]\+|#x?|%23|&H)[0-9_a-fA-FgGrR]*?[a-fA-FgGrR]{2,}[0-9_a-fA-FgGrR]*(?:[uUlL]{0,3}|[iu]\d+)\b
|
||||
|
||||
# integrity
|
||||
@@ -482,7 +478,7 @@ Name\[[^\]]+\]=.*
|
||||
(?:(?:\b|_|(?<=[a-z]))I|(?:\b|_)(?:nsI|isA))(?=(?:[A-Z][a-z]{2,})+(?:[A-Z\d]|\b))
|
||||
|
||||
# python
|
||||
#\b(?i)py(?!gment|gmy|lon|ramid|ro|th)(?=[a-z]{2,})
|
||||
#\b(?i)py(?!gments|gmy|lon|ramid|ro|th)(?=[a-z]{2,})
|
||||
|
||||
# crypt
|
||||
(['"])\$2[ayb]\$.{56}\g{-1}
|
||||
@@ -502,21 +498,12 @@ Name\[[^\]]+\]=.*
|
||||
# go.sum
|
||||
\bh1:\S+
|
||||
|
||||
# golang print-f-style functions
|
||||
#(?i)(?<=append|comma|debug|equal|err|error|exit|fatal|format|info|log|name|panic|print|skip|scan|string|trace|true|warn|warning|wrap|write)(?:f|ln)(?:[ (]|$)
|
||||
|
||||
# golang regular expression
|
||||
(?<!")\br".+?"
|
||||
|
||||
# imports
|
||||
^import\s+(?:(?:static|type)\s+|)(?:[\w.]|\{\s*\w*?(?:,\s*(?:\w*|\*))+\s*\})+(?:\s+from (['"]).*?\g{-1}|)
|
||||
^import\s+(?:(?:static|type)\s+|)(?:[\w.]|\{\s*\w*?(?:,\s*(?:\w*|\*))+\s*\})+
|
||||
|
||||
# scala modules
|
||||
#("[^"]+"\s*%%?\s*){2,3}"[^"]+"
|
||||
|
||||
# Dataframes / NumPy
|
||||
#\b(?:df|np)\.\w{3,}
|
||||
|
||||
# container images
|
||||
image: [-\w./:@]+
|
||||
|
||||
@@ -546,18 +533,12 @@ content: (['"])[-a-zA-Z=;:/0-9+]*=\g{-1}
|
||||
# Note that there's a high false positive rate, remove the `?=` and search for the regex to see if the matches seem like reasonable strings
|
||||
(?<!['"])\b(?:B|BR|Br|F|FR|Fr|R|RB|RF|Rb|Rf|U|UR|Ur|b|bR|br|f|fR|fr|r|rB|rF|rb|rf|u|uR|ur)['"](?=[A-Z]{3,}|[A-Z][a-z]{2,}|[a-z]{3,})
|
||||
|
||||
# Regular expression for word breaks
|
||||
#\\b(?=[a-z]{2})
|
||||
|
||||
# Regular expressions for (P|p)assword
|
||||
\([A-Z]\|[a-z]\)[a-z]+
|
||||
|
||||
# Java regular expressions
|
||||
Pattern\.(?:compile|matches)\(".*"
|
||||
|
||||
# JavaScript regular expressions
|
||||
# javascript exec/test regex
|
||||
/.{3,}?/[gim]*\.(?:exec|test)\(
|
||||
# javascript test regex
|
||||
/.{3,}/[gim]*\.test\(
|
||||
# javascript match regex
|
||||
\.match\(/[^/\s"]{3,}/[gim]*\s*
|
||||
# javascript match regex
|
||||
@@ -584,7 +565,7 @@ perl(?:\s+-[a-zA-Z]\w*)+
|
||||
regexp?\.MustCompile\((?:`[^`]*`|".*"|'.*')\)
|
||||
|
||||
# regex choice
|
||||
#\((?:\?:|)[^)|]+(?<! )\|(?!(?:jq|xargs)\b)[^)| ][^)]*\)
|
||||
# \(\?:[^)]+\|[^)]+\)
|
||||
|
||||
# proto
|
||||
^\s*(\w+)\s\g{-1} =
|
||||
@@ -607,9 +588,6 @@ urn:shemas-jetbrains-com
|
||||
# Debian changelog severity
|
||||
[-\w]+ \(.*\) (?:\w+|baseline|unstable|experimental); urgency=(?:low|medium|high|emergency|critical)\b
|
||||
|
||||
# Red Hat Package management spec file dependencies
|
||||
^(?:Build|)Requires: [-.\w]+
|
||||
|
||||
# kubernetes pod status lists
|
||||
# https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase
|
||||
\w+(?:-\w+)+\s+\d+/\d+\s+(?:Running|Pending|Succeeded|Failed|Unknown)\s+
|
||||
@@ -664,8 +642,6 @@ PrependWithABINamepsace
|
||||
>[-a-zA-Z=;:/0-9+]{3,}=</
|
||||
# base64 encoded content, possibly wrapped in mime
|
||||
#(?:^|[\s=;:?])[-a-zA-Z=;:/0-9+]{50,}(?:[\s=;:?]|$)
|
||||
# jwt
|
||||
(?:\be[wy][-a-zA-Z=;:/0-9+]+\.){2}[-_\w]+
|
||||
# base64 encoded json
|
||||
\beyJ[-a-zA-Z=;:/0-9+]+
|
||||
# base64 encoded pkcs
|
||||
@@ -703,9 +679,9 @@ systemd.*?running in system mode \([-+].*\)$
|
||||
|
||||
# Non-English
|
||||
# Even repositories expecting pure English content can unintentionally have Non-English content... People will occasionally mistakenly enter [homoglyphs](https://en.wikipedia.org/wiki/Homoglyph) which are essentially typos, and using this pattern will mean check-spelling will not complain about them.
|
||||
# .
|
||||
#
|
||||
# If the content to be checked should be written in English and the only Non-English items will be people's names, then you can consider adding this.
|
||||
# .
|
||||
#
|
||||
# Alternatively, if you're using check-spelling v0.0.25+, and you would like to _check_ the Non-English content for spelling errors, you can. For information on how to do so, see:
|
||||
# https://docs.check-spelling.dev/Feature:-Configurable-word-characters.html#unicode
|
||||
[a-zA-Z]*[ÀÁÂÃÄÅÆČÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæčçèéêëìíîïðñòóôõöøùúûüýÿĀāŁłŃńŅņŒœŚśŠšŜŝŸŽžź][a-zA-Z]{3}[a-zA-ZÀÁÂÃÄÅÆČÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæčçèéêëìíîïðñòóôõöøùúûüýÿĀāŁłŃńŅņŒœŚśŠšŜŝŸŽžź]*|[a-zA-Z]{3,}[ÀÁÂÃÄÅÆČÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæčçèéêëìíîïðñòóôõöøùúûüýÿĀāŁłŃńŅņŒœŚśŠšŜŝŸŽžź]|[ÀÁÂÃÄÅÆČÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæčçèéêëìíîïðñòóôõöøùúûüýÿĀāŁłŃńŅņŒœŚśŠšŜŝŸŽžź][a-zA-Z]{3,}
|
||||
@@ -717,7 +693,7 @@ systemd.*?running in system mode \([-+].*\)$
|
||||
# This corpus only had capital letters, but you probably want lowercase ones as well.
|
||||
\b[LN]'+[a-z]{2,}\b
|
||||
|
||||
# LaTeX
|
||||
# latex (check-spelling >= 0.0.22)
|
||||
\\\w{2,}\{
|
||||
|
||||
# American Mathematical Society (AMS) / Doxygen
|
||||
@@ -744,6 +720,7 @@ nolint:\s*[\w,]+
|
||||
# cygwin paths
|
||||
/cygdrive/[a-zA-Z]/(?:Program Files(?: \(.*?\)| ?)(?:/[-+.~\\/()\w ]+)*|[-+.~\\/()\w])+
|
||||
|
||||
# in check-spelling@v0.0.22+, printf markers aren't automatically consumed
|
||||
# printf markers
|
||||
#(?<!\\)\\[nrt](?=[a-z]{2,})
|
||||
# alternate printf markers if you run into latex and friends
|
||||
@@ -772,12 +749,12 @@ W/"[^"]+"
|
||||
|
||||
# Compiler flags (Unix, Java/Scala)
|
||||
# Use if you have things like `-Pdocker` and want to treat them as `docker`
|
||||
#(?:^|[\t ,>"'`=\[(#])-(?:(?:J-|)[DPWXY]|[Llf])(?=[A-Z]{2,}|[A-Z][a-z]|[a-z]{2,})
|
||||
#(?:^|[\t ,>"'`=(#])-(?:(?:J-|)[DPWXY]|[Llf])(?=[A-Z]{2,}|[A-Z][a-z]|[a-z]{2,})
|
||||
|
||||
# Compiler flags (Windows / PowerShell)
|
||||
# This is a subset of the more general compiler flags pattern.
|
||||
# It avoids matching `-Path` to prevent it from being treated as `ath`
|
||||
#(?:^|[\t ,"'`=\[(#])-(?:[DPL](?=[A-Z]{2,})|[WXYlf](?=[A-Z]{2,}|[A-Z][a-z]|[a-z]{2,}))
|
||||
#(?:^|[\t ,"'`=(#])-(?:[DPL](?=[A-Z]{2,})|[WXYlf](?=[A-Z]{2,}|[A-Z][a-z]|[a-z]{2,}))
|
||||
|
||||
# Compiler flags (linker)
|
||||
,-B
|
||||
@@ -785,7 +762,7 @@ W/"[^"]+"
|
||||
# Library prefix
|
||||
# e.g., `lib`+`archive`, `lib`+`raw`, `lib`+`unwind`
|
||||
# (ignores some words that happen to start with `lib`)
|
||||
(?:\b|_)[Ll]ib(?!era[lt])(?:re(?=office)|era|)(?!ero|erty|rar(?:i(?:an|es)|y))(?=[a-z])
|
||||
(?:\b|_)[Ll]ib(?:re(?=office)|)(?!era[lt]|ero|erty|rar(?:i(?:an|es)|y))(?=[a-z])
|
||||
|
||||
# iSCSI iqn (approximate regex)
|
||||
\biqn\.[0-9]{4}-[0-9]{2}(?:[\.-][a-z][a-z0-9]*)*\b
|
||||
@@ -796,9 +773,9 @@ W/"[^"]+"
|
||||
# curl arguments
|
||||
\b(?:\\n|)curl(?:\.exe|)(?:\s+-[a-zA-Z]{1,2}\b)*(?:\s+-[a-zA-Z]{3,})(?:\s+-[a-zA-Z]+)*
|
||||
# set arguments
|
||||
\b(?:bash|(?<!\.)sh|set)(?:\s+[-+][abefimouxE]{1,2})*\s+[-+][abefimouxE]{3,}(?:\s+[-+][abefimouxE]+)*
|
||||
\b(?:bash|sh|set)(?:\s+[-+][abefimouxE]{1,2})*\s+[-+][abefimouxE]{3,}(?:\s+[-+][abefimouxE]+)*
|
||||
# tar arguments
|
||||
\b(?:\\n|)g?tar(?:\.exe|)(?:\s-C \S+|(?:\s+--[-a-zA-Z]+|\s+-[a-zA-Z]+|\s[ABGJMOPRSUWZacdfh-pr-xz]+\b)(?:=[^ ]*|))+
|
||||
\b(?:\\n|)g?tar(?:\.exe|)(?:(?:\s+--[-a-zA-Z]+|\s+-[a-zA-Z]+|\s[ABGJMOPRSUWZacdfh-pr-xz]+\b)(?:=[^ ]*|))+
|
||||
# tput arguments -- https://man7.org/linux/man-pages/man5/terminfo.5.html -- technically they can be more than 5 chars long...
|
||||
\btput\s+(?:(?:-[SV]|-T\s*\w+)\s+)*\w{3,5}\b
|
||||
# macOS temp folders
|
||||
|
||||
11
.github/actions/spell-check/excludes.txt
vendored
11
.github/actions/spell-check/excludes.txt
vendored
@@ -101,7 +101,6 @@
|
||||
^doc/devdocs/akaLinks\.md$
|
||||
^NOTICE\.md$
|
||||
^src/common/CalculatorEngineCommon/exprtk\.hpp$
|
||||
^src/common/UnitTests-CommonUtils/
|
||||
^src/common/ManagedCommon/ColorFormatHelper\.cs$
|
||||
^src/common/notifications/BackgroundActivatorDLL/cpp\.hint$
|
||||
^src/common/sysinternals/Eula/
|
||||
@@ -110,8 +109,7 @@
|
||||
^src/modules/cmdpal/doc/initial-sdk-spec/list-elements-mock-002\.pdn$
|
||||
^src/modules/cmdpal/ext/SamplePagesExtension/Pages/SampleMarkdownImagesPage\.cs$
|
||||
^src/modules/cmdpal/Microsoft\.CmdPal\.UI/Settings/InternalPage\.SampleData\.cs$
|
||||
^src/modules/cmdpal/Tests/Microsoft\.CmdPal\.Common\.UnitTests/.*\.TestData\.cs$
|
||||
^src/modules/cmdpal/Tests/Microsoft\.CmdPal\.Common\.UnitTests/Text/.*\.cs$
|
||||
^src/modules/cmdpal/Tests/Microsoft\.CmdPal\.Core\.Common\.UnitTests/.*\.TestData\.cs$
|
||||
^src/modules/colorPicker/ColorPickerUI/Shaders/GridShader\.cso$
|
||||
^src/modules/launcher/Plugins/Microsoft\.PowerToys\.Run\.Plugin\.TimeDate/Properties/
|
||||
^src/modules/MouseUtils/MouseJumpUI/MainForm\.resx$
|
||||
@@ -135,14 +133,11 @@
|
||||
^src/modules/previewpane/SvgPreviewHandler/SvgHTMLPreviewGenerator\.cs$
|
||||
^src/modules/previewpane/UnitTests-MarkdownPreviewHandler/HelperFiles/MarkdownWithHTMLImageTag\.txt$
|
||||
^src/modules/registrypreview/RegistryPreviewUILib/Controls/HexBox/.*$
|
||||
^src/modules/ZoomIt/ZoomIt/rnnoise/
|
||||
^src/modules/ZoomIt/ZoomIt/selfie_segmentation\.onnx$
|
||||
^src/modules/ZoomIt/ZoomIt/ZoomIt\.idc$
|
||||
^src/Monaco/
|
||||
^tools/project_template/ModuleTemplate/resource\.h$
|
||||
^tools/Verification scripts/Check preview handler registration\.ps1$
|
||||
ignore$
|
||||
^src/modules/registrypreview/RegistryPreviewUILib/Controls/HexBox/.*$
|
||||
^src/common/CalculatorEngineCommon/exprtk\.hpp$
|
||||
src/modules/cmdpal/ext/SamplePagesExtension/Pages/SampleMarkdownImagesPage.cs
|
||||
^src/modules/powerrename/unittests/testdata/avif_test\.avif$
|
||||
^src/modules/powerrename/unittests/testdata/heif_test\.heic$
|
||||
^deps/spdlog-msvc-fix/
|
||||
|
||||
368
.github/actions/spell-check/expect.txt
vendored
368
.github/actions/spell-check/expect.txt
vendored
File diff suppressed because it is too large
Load Diff
495
.github/actions/spell-check/line_forbidden.patterns
vendored
495
.github/actions/spell-check/line_forbidden.patterns
vendored
File diff suppressed because one or more lines are too long
72
.github/actions/spell-check/patterns.txt
vendored
72
.github/actions/spell-check/patterns.txt
vendored
@@ -1,30 +1,10 @@
|
||||
# See https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples:-patterns
|
||||
|
||||
Inno Setup
|
||||
|
||||
FFmpeg
|
||||
|
||||
# https://github.com/MicrosoftEdge/edge-launcher
|
||||
MIcrosoftEdgeLauncherCsharp
|
||||
|
||||
# x64
|
||||
(?:(?<=[a-df-z])x|(?<=[A-Z]X))64
|
||||
|
||||
# reversed irreversible binomials
|
||||
\b(?:mouse down and up|low and high)\b
|
||||
|
||||
# marker to ignore all code on line
|
||||
^.*/\* #no-spell-check-line \*/.*$
|
||||
# marker for ignoring a comment to the end of the line
|
||||
// #no-spell-check.*$
|
||||
|
||||
# JavaScript regex literals that start with \b can be reported as "b..." words.
|
||||
# Example: /\bclass\s+.../
|
||||
^\s*/\\[b].{3,}?/[gim]*\s*(?:\)(?:;|$)|,$)
|
||||
|
||||
# GitHub API header token used in code (not natural language).
|
||||
\bx-ratelimit-reset\b
|
||||
|
||||
# Gaelic
|
||||
Gàidhlig
|
||||
|
||||
@@ -91,14 +71,11 @@ StringComparer.OrdinalIgnoreCase\) \{.*\}
|
||||
# the last line of mimetype="application/x-microsoft.net.object.bytearray.base64" things in .resx files
|
||||
^\s*[-a-zA-Z=;:/0-9+]*[-a-zA-Z;:/0-9+][-a-zA-Z=;:/0-9+]*=$
|
||||
|
||||
# DateTime Formats
|
||||
Get-Date -Format \w+|DateTime\.Now(?::|\.ToString\(")\w+
|
||||
|
||||
# Automatically suggested patterns
|
||||
|
||||
# hit-count: 5402 file-count: 1339
|
||||
# IServiceProvider / isAThing
|
||||
(?:(?:\b|_|(?<=[a-z]))[A-Z]|(?:\b|_)(?:nsI|isA))(?=(?:[A-Z][a-z]{2,})+(?:[A-Z\d]|\b))
|
||||
(?:(?:\b|_|(?<=[a-z]))[IT]|(?:\b|_)(?:nsI|isA))(?=(?:[A-Z][a-z]{2,})+(?:[A-Z\d]|\b))
|
||||
|
||||
# hit-count: 2073 file-count: 842
|
||||
# #includes
|
||||
@@ -182,10 +159,6 @@ aka\.ms/[a-zA-Z0-9]+
|
||||
# kubernetes crd patterns
|
||||
^\s*pattern: .*$
|
||||
|
||||
# hit-count: 7 file-count: 3
|
||||
# unicode escaped characters (4)
|
||||
\\u[0-9a-fA-F]{4}
|
||||
|
||||
# hit-count: 5 file-count: 3
|
||||
# URL escaped characters
|
||||
%[0-9A-F][A-F](?=[A-Za-z])
|
||||
@@ -198,10 +171,6 @@ aka\.ms/[a-zA-Z0-9]+
|
||||
# medium
|
||||
\bmedium\.com/@?[^/\s"]+/[-\w:/*.]+
|
||||
|
||||
# hit-count: 2 file-count: 2
|
||||
# tar arguments
|
||||
\b(?:\\n|)g?tar(?:\.exe|)(?:\s-C \S+|(?:\s+--[-a-zA-Z]+|\s+-[a-zA-Z]+|\s[ABGJMOPRSUWZacdfh-pr-xz]+\b)(?:=[^ ]*|))+
|
||||
|
||||
# hit-count: 2 file-count: 1
|
||||
# While you could try to match `http://` and `https://` by using `s?` in `https?://`, sometimes there
|
||||
# YouTube url
|
||||
@@ -215,9 +184,22 @@ aka\.ms/[a-zA-Z0-9]+
|
||||
# curl arguments
|
||||
\b(?:\\n|)curl(?:\.exe|)(?:\s+-[a-zA-Z]{1,2}\b)*(?:\s+-[a-zA-Z]{3,})(?:\s+-[a-zA-Z]+)*
|
||||
|
||||
# hit-count: 1 file-count: 1
|
||||
# tar arguments
|
||||
\b(?:\\n|)g?tar(?:\.exe|)(?:(?:\s+--[-a-zA-Z]+|\s+-[a-zA-Z]+|\s[ABGJMOPRSUWZacdfh-pr-xz]+\b)(?:=[^ ]*|))+
|
||||
|
||||
# #pragma lib
|
||||
^\s*#pragma comment\(lib, ".*?"\)
|
||||
|
||||
# UnitTests
|
||||
\[DataRow\(.*\)\]
|
||||
|
||||
# AdditionalDependencies
|
||||
<AdditionalDependencies>.*<
|
||||
|
||||
# the last line of mimetype="application/x-microsoft.net.object.bytearray.base64" things in .resx files
|
||||
^\s*[-a-zA-Z=;:/0-9+]*[-a-zA-Z;:/0-9+][-a-zA-Z=;:/0-9+]*=$
|
||||
|
||||
RegExp\(@?([`'"]).*?\g{-1}\)|(?:escapes|regEx):\s*(?:/.*/|([`'"]).*?\g{-1})|return/.*?/
|
||||
|
||||
# Questionably acceptable forms of `in to`
|
||||
@@ -237,15 +219,13 @@ RegExp\(@?([`'"]).*?\g{-1}\)|(?:escapes|regEx):\s*(?:/.*/|([`'"]).*?\g{-1})|retu
|
||||
# mount
|
||||
\bmount\s+-t\s+(\w+)\s+\g{-1}\b
|
||||
# C types and repeated CSS values
|
||||
\s(auto|await|buffalo|center|div|inherit|long|LONG|none|normal|solid|thin|transparent|very)(?:\s\g{-1})+\s
|
||||
\s(auto|buffalo|center|div|inherit|long|LONG|none|normal|solid|thin|transparent|very)(?:\s\g{-1})+\s
|
||||
# C enum and struct
|
||||
\b(?:enum|struct)\s+(\w+)\s+\g{-1}\b
|
||||
# go templates
|
||||
\s(\w+)\s+\g{-1}\s+\`(?:graphql|inject|json|yaml):
|
||||
# doxygen / javadoc / .net
|
||||
(?:[\\@](?:brief|defgroup|groupname|link|t?param|return|retval)|(?:public|private|\[Parameter(?:\(.+\)|)\])(?:\s+(?:static|override|readonly|required|virtual))*)(?:\s+\{\w+\}|)\s+(\w+)\s+\g{-1}\s
|
||||
# C# getter/setter
|
||||
\s(\w+)\s+\g{-1}\s*\{\s*[gs]et;
|
||||
|
||||
# macOS file path
|
||||
(?:Contents\W+|(?!iOS)/)MacOS\b
|
||||
@@ -294,27 +274,5 @@ St&yle
|
||||
# 0x6f677548 is user name but user folder causes a flag
|
||||
\bx6f677548\b
|
||||
|
||||
# Windows API constants and hardware interface terms
|
||||
\bCOINIT[_A-Z]*\b
|
||||
\bEOAC[_A-Z]*\b
|
||||
\b(?:RPC_C_AUTHN_)?WINNT\b
|
||||
\bUPDATEREGISTRY\b
|
||||
\b(?:CDS_)?UPDATEREGISTRY\b
|
||||
|
||||
# Display interface terms (HDMI, DVI, DisplayPort)
|
||||
\b(?:HDMI|DVI|DisplayPort)(?:-\d+)?\b
|
||||
|
||||
# 2D Region struct names
|
||||
\bDisplayConfig2?D?Region\b
|
||||
|
||||
# Microsoft Store URLs and product IDs
|
||||
ms-windows-store://\S+
|
||||
|
||||
# ANSI color codes
|
||||
(?:\\(?:u00|x)1[Bb]|\\03[1-7]|\x1b|\\u\{1[Bb]\})\[\d+(?:;\d+)*m
|
||||
|
||||
# Special licenses text from RNNoise (BSD-style disclaimer: ``AS IS'')
|
||||
``AS IS''
|
||||
|
||||
# Old school moniker for macOS from RNNoise
|
||||
MacOS
|
||||
|
||||
47
.github/actions/spell-check/reject.txt
vendored
47
.github/actions/spell-check/reject.txt
vendored
@@ -1,30 +1,23 @@
|
||||
attache
|
||||
aroynt.*
|
||||
bellows?
|
||||
^attache$
|
||||
^bellows?$
|
||||
benefitting
|
||||
occurences?
|
||||
.*dnt
|
||||
dependan.*
|
||||
developement
|
||||
developp?e
|
||||
Devers?
|
||||
devex.*
|
||||
devide
|
||||
Devinn?[ae]
|
||||
devisals?
|
||||
devisors?
|
||||
diables?
|
||||
hasta?
|
||||
hastat.*
|
||||
immediatly
|
||||
inisle
|
||||
inital
|
||||
linge
|
||||
oer
|
||||
^dependan.*
|
||||
^develope$
|
||||
^developement$
|
||||
^developpe
|
||||
^Devers?$
|
||||
^devex
|
||||
^devide
|
||||
^Devinn?[ae]
|
||||
^devisal
|
||||
^devisor
|
||||
^diables?$
|
||||
^oer$
|
||||
Sorce
|
||||
[Ss]pae.*
|
||||
Teh
|
||||
untill
|
||||
untilling
|
||||
venders?
|
||||
wether.*
|
||||
^[Ss]pae.*
|
||||
^Teh$
|
||||
^untill$
|
||||
^untilling$
|
||||
^venders?$
|
||||
^wether.*
|
||||
|
||||
2
.github/copilot-instructions.md
vendored
2
.github/copilot-instructions.md
vendored
@@ -33,4 +33,4 @@ These are auto-applied based on file location:
|
||||
## Detailed Documentation
|
||||
|
||||
- [Architecture](../doc/devdocs/core/architecture.md)
|
||||
- [Coding Style](../doc/devdocs/development/style.md)
|
||||
- [Coding Style](../doc/devdocs/development/style.md)
|
||||
|
||||
37
.github/policies/resourceManagement.yml
vendored
37
.github/policies/resourceManagement.yml
vendored
@@ -163,7 +163,7 @@ configuration:
|
||||
association: Collaborator
|
||||
then:
|
||||
- addReply:
|
||||
reply: We've identified this issue as a duplicate of an existing one and are closing this thread so discussion stays in one place.<br/><br/>Please see the comment above for the link to the original tracking issue, and feel free to subscribe there for updates.
|
||||
reply: Hi! We've identified this issue as a duplicate of another one that already exists on this Issue Tracker. This specific instance is being closed in favor of tracking the concern over on the referenced thread. Thanks for your report!
|
||||
- closeIssue
|
||||
- removeLabel:
|
||||
label: Needs-Triage
|
||||
@@ -233,30 +233,6 @@ configuration:
|
||||
- addReply:
|
||||
reply: Hi! Thanks for making us aware of the problem. We raised the issue with our internal localization team. This issue should be fixed hopefully in the next version of PowerToys.
|
||||
description:
|
||||
- if:
|
||||
- payloadType: Issue_Comment
|
||||
- commentContains:
|
||||
pattern: '\/need-monitor-info'
|
||||
isRegex: True
|
||||
- hasLabel:
|
||||
label: Product-Cursor Wrap
|
||||
- or:
|
||||
- activitySenderHasAssociation:
|
||||
association: Owner
|
||||
- activitySenderHasAssociation:
|
||||
association: Member
|
||||
- activitySenderHasAssociation:
|
||||
association: Collaborator
|
||||
then:
|
||||
- removeLabel:
|
||||
label: Needs-Triage
|
||||
- removeLabel:
|
||||
label: Needs-Team-Response
|
||||
- addLabel:
|
||||
label: Needs-Author-Feedback
|
||||
- addReply:
|
||||
reply: "To help debug your layout, please run [this script](https://github.com/microsoft/PowerToys/blob/main/src/modules/MouseUtils/CursorWrap/CursorWrapTests/Capture-MonitorLayout.ps1) and attach the generated JSON output to this thread.\n\nThis allows us to better understand the issue and investigate potential fixes."
|
||||
description:
|
||||
- if:
|
||||
- payloadType: Issue_Comment
|
||||
- commentContains:
|
||||
@@ -266,5 +242,16 @@ configuration:
|
||||
- addReply:
|
||||
reply: Hi! Your last comment indicates to our system, that you might want to contribute to this feature/fix this bug. Thank you! Please make us aware on our ["Would you like to contribute to PowerToys?" thread](https://github.com/microsoft/PowerToys/issues/28769), as we don't see all the comments. <br /><br />_I'm a bot (beep!) so please excuse any mistakes I may make_
|
||||
description:
|
||||
- if:
|
||||
- payloadType: Issues
|
||||
- isAction:
|
||||
action: Opened
|
||||
- bodyContains:
|
||||
pattern: 'Area\(s\) with issue\?\s*\nWorkspaces'
|
||||
isRegex: True
|
||||
then:
|
||||
- addLabel:
|
||||
label: Product-Workspaces
|
||||
description:
|
||||
onFailure:
|
||||
onSuccess:
|
||||
|
||||
377
.github/scripts/telemetry-pr-check.js
vendored
377
.github/scripts/telemetry-pr-check.js
vendored
@@ -1,377 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Detects telemetry-event additions/modifications in a pull request and
|
||||
* posts (or updates) a PR comment when telemetry-related changes are found.
|
||||
*
|
||||
* This script is executed by .github/workflows/telemetry-pr-check.yml.
|
||||
* Keep both files aligned when changing trigger behavior, env usage, or messaging.
|
||||
*/
|
||||
|
||||
const fs = require('node:fs');
|
||||
const REVIEWER_LOGIN = 'chatasweetie';
|
||||
const REVIEWER_MENTION = `@${REVIEWER_LOGIN}`;
|
||||
|
||||
const COMMENT_MARKER = '<!-- telemetry-event-check -->';
|
||||
const COMMENT_BODY_WITH_PRIVACY_UPDATE = `${COMMENT_MARKER}
|
||||
Thank you for contributing to PowerToys. We've detected that this PR might include a new or modified telemetry event. After this PR is merged, please follow these next steps:
|
||||
|
||||
- [ ] Reach out to Jessica (${REVIEWER_MENTION}) to follow up on the next steps: https://aka.ms/pt-telemetry-process
|
||||
`;
|
||||
|
||||
const COMMENT_BODY_WITHOUT_PRIVACY_UPDATE = `${COMMENT_MARKER}
|
||||
Thank you for contributing to PowerToys. We've detected that this PR might include a new or modified telemetry event. Please ensure the following before merging:
|
||||
|
||||
- [ ] Add your telemetry events to [DATA_AND_PRIVACY](https://github.com/microsoft/PowerToys/blob/main/DATA_AND_PRIVACY.md).md within this PR.
|
||||
|
||||
- [ ] Reach out to Jessica (${REVIEWER_MENTION}) to follow up on the next steps: https://aka.ms/pt-telemetry-process`;
|
||||
|
||||
const TELEMETRY_PATH_PATTERNS = [
|
||||
/(^|\/)trace\.(h|hpp|cpp|cs)$/i,
|
||||
/(^|\/)telemetry\//i,
|
||||
/(^|\/)events\/.+event\.cs$/i,
|
||||
/^src\/common\/Telemetry\//i,
|
||||
/^src\/common\/ManagedTelemetry\//i,
|
||||
/^src\/runner\/trace\.(h|cpp)$/i,
|
||||
/^src\/settings-ui\/.+\/Telemetry\//i,
|
||||
];
|
||||
|
||||
const TELEMETRY_LINE_PATTERNS = [
|
||||
/TraceLoggingWriteWrapper\s*\(/,
|
||||
/\bTraceLoggingWrite\s*\(/,
|
||||
/\bTRACELOGGING_DEFINE_PROVIDER\b/,
|
||||
/\bTraceLoggingOptionProjectTelemetry\b/,
|
||||
/\bProjectTelemetryPrivacyDataTag\b/,
|
||||
/\bPROJECT_KEYWORD_MEASURE\b/,
|
||||
/\bRegisterProvider\s*\(/,
|
||||
/\bUnregisterProvider\s*\(/,
|
||||
/\bPowerToysTelemetry\.Log\.WriteEvent\s*\(/,
|
||||
/\bclass\s+\w+\s*:\s*EventBase\s*,\s*IEvent\b/,
|
||||
/\bclass\s+\w+\s*:\s*TelemetryBase\b/,
|
||||
/\bPartA_PrivTags\b/,
|
||||
/\[EventData\]/,
|
||||
/\bEventName\b/,
|
||||
];
|
||||
|
||||
function requireEnv(name) {
|
||||
const value = process.env[name];
|
||||
if (!value) {
|
||||
throw new Error(`Missing required environment variable: ${name}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function validateRepository(repository) {
|
||||
if (!/^[^/]+\/[^/]+$/.test(repository)) {
|
||||
throw new Error(
|
||||
`GITHUB_REPOSITORY must be in owner/repo format, received: ${JSON.stringify(repository)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function readEventPayload(eventPath) {
|
||||
let raw;
|
||||
try {
|
||||
raw = fs.readFileSync(eventPath, 'utf8');
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to read event payload at ${eventPath}: ${error.message}`);
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse JSON from ${eventPath}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePullNumber(event) {
|
||||
const fromPullRequest = event?.pull_request?.number;
|
||||
const fromWorkflowDispatch = event?.inputs?.pr_number;
|
||||
const rawPullNumber = fromPullRequest ?? fromWorkflowDispatch;
|
||||
|
||||
if (rawPullNumber === undefined || rawPullNumber === null || rawPullNumber === '') {
|
||||
throw new Error(
|
||||
'Unable to determine pull request number from event payload. Expected pull_request.number or inputs.pr_number.'
|
||||
);
|
||||
}
|
||||
|
||||
const pullNumber = Number.parseInt(String(rawPullNumber), 10);
|
||||
if (!Number.isInteger(pullNumber) || pullNumber <= 0) {
|
||||
throw new Error(`Invalid pull request number: ${JSON.stringify(rawPullNumber)}`);
|
||||
}
|
||||
|
||||
return pullNumber;
|
||||
}
|
||||
|
||||
function isTelemetryPath(filePath) {
|
||||
return TELEMETRY_PATH_PATTERNS.some((pattern) => pattern.test(filePath));
|
||||
}
|
||||
|
||||
function changedLinesFromPatch(patch) {
|
||||
if (!patch) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return patch
|
||||
.split('\n')
|
||||
.filter((line) => {
|
||||
if (line.startsWith('+++') || line.startsWith('---')) {
|
||||
return false;
|
||||
}
|
||||
return line.startsWith('+') || line.startsWith('-');
|
||||
})
|
||||
.map((line) => line.slice(1));
|
||||
}
|
||||
|
||||
function hasTelemetryLineSignal(lines) {
|
||||
return lines.some((line) => TELEMETRY_LINE_PATTERNS.some((pattern) => pattern.test(line)));
|
||||
}
|
||||
|
||||
async function apiRequest(url, method = 'GET', body) {
|
||||
const token = requireEnv('GITHUB_TOKEN');
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(`Network error during ${method} ${url}: ${error.message}`);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
const rateLimitReset = response.headers.get('x-ratelimit-reset');
|
||||
const rateLimitHint =
|
||||
response.status === 403 && rateLimitReset
|
||||
? ` (rate limit reset at epoch ${rateLimitReset})`
|
||||
: '';
|
||||
throw new Error(`${method} ${url} failed (${response.status})${rateLimitHint}: ${text}`);
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse JSON response for ${method} ${url}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function getAllPullFiles(apiBaseUrl, repository, pullNumber) {
|
||||
const files = [];
|
||||
let page = 1;
|
||||
|
||||
while (true) {
|
||||
const url = `${apiBaseUrl}/repos/${repository}/pulls/${pullNumber}/files?per_page=100&page=${page}`;
|
||||
const batch = await apiRequest(url);
|
||||
if (!Array.isArray(batch)) {
|
||||
throw new Error(`Unexpected response while listing PR files on page ${page}.`);
|
||||
}
|
||||
|
||||
if (batch.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
files.push(...batch);
|
||||
|
||||
if (batch.length < 100) {
|
||||
break;
|
||||
}
|
||||
|
||||
page += 1;
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
async function getPullRequest(apiBaseUrl, repository, pullNumber) {
|
||||
const url = `${apiBaseUrl}/repos/${repository}/pulls/${pullNumber}`;
|
||||
const pullRequest = await apiRequest(url);
|
||||
if (!pullRequest || typeof pullRequest !== 'object') {
|
||||
throw new Error('Unexpected response while fetching pull request details.');
|
||||
}
|
||||
return pullRequest;
|
||||
}
|
||||
|
||||
async function ensureReviewerRequested(apiBaseUrl, repository, pullNumber, pullRequest) {
|
||||
const authorLogin = String(pullRequest?.user?.login || '').toLowerCase();
|
||||
const targetReviewer = REVIEWER_LOGIN.toLowerCase();
|
||||
|
||||
if (authorLogin === targetReviewer) {
|
||||
console.log(`Skipping reviewer request: ${REVIEWER_LOGIN} is the PR author.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const requestedReviewers = Array.isArray(pullRequest?.requested_reviewers)
|
||||
? pullRequest.requested_reviewers
|
||||
: [];
|
||||
const alreadyRequested = requestedReviewers.some(
|
||||
(reviewer) => String(reviewer?.login || '').toLowerCase() === targetReviewer
|
||||
);
|
||||
|
||||
if (alreadyRequested) {
|
||||
console.log(`Reviewer ${REVIEWER_LOGIN} is already requested.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const url = `${apiBaseUrl}/repos/${repository}/pulls/${pullNumber}/requested_reviewers`;
|
||||
try {
|
||||
await apiRequest(url, 'POST', { reviewers: [REVIEWER_LOGIN] });
|
||||
console.log(`Requested reviewer ${REVIEWER_LOGIN}.`);
|
||||
} catch (error) {
|
||||
// Reviewer request should not fail the telemetry guidance workflow.
|
||||
console.warn(
|
||||
`Unable to request reviewer ${REVIEWER_LOGIN}: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function findExistingTelemetryComment(apiBaseUrl, repository, pullNumber) {
|
||||
let page = 1;
|
||||
|
||||
while (true) {
|
||||
const commentsUrl = `${apiBaseUrl}/repos/${repository}/issues/${pullNumber}/comments?per_page=100&page=${page}`;
|
||||
const comments = await apiRequest(commentsUrl);
|
||||
|
||||
if (!Array.isArray(comments)) {
|
||||
throw new Error(`Unexpected response while listing issue comments on page ${page}.`);
|
||||
}
|
||||
|
||||
const existing = comments.find(
|
||||
(comment) => typeof comment.body === 'string' && comment.body.includes(COMMENT_MARKER)
|
||||
);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
if (comments.length < 100) {
|
||||
return null;
|
||||
}
|
||||
|
||||
page += 1;
|
||||
}
|
||||
}
|
||||
|
||||
function detectTelemetryChanges(files) {
|
||||
const matches = [];
|
||||
|
||||
for (const file of files) {
|
||||
const filename = file.filename || '';
|
||||
const telemetryPath = isTelemetryPath(filename);
|
||||
const changedLines = changedLinesFromPatch(file.patch);
|
||||
const telemetryLineSignal = hasTelemetryLineSignal(changedLines);
|
||||
|
||||
// Some large diffs omit patch content. If the file path is telemetry-centric,
|
||||
// treat it as a telemetry modification to avoid false negatives.
|
||||
const patchUnavailable = !file.patch && telemetryPath;
|
||||
|
||||
if (telemetryPath || telemetryLineSignal || patchUnavailable) {
|
||||
matches.push({
|
||||
filename,
|
||||
telemetryPath,
|
||||
telemetryLineSignal,
|
||||
patchUnavailable,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
function hasDataAndPrivacyChange(files) {
|
||||
return files.some((file) => {
|
||||
const filename = (file.filename || '').toLowerCase();
|
||||
return filename === 'data_and_privacy.md';
|
||||
});
|
||||
}
|
||||
|
||||
async function upsertPrComment(apiBaseUrl, repository, pullNumber, body) {
|
||||
const existing = await findExistingTelemetryComment(apiBaseUrl, repository, pullNumber);
|
||||
|
||||
if (existing) {
|
||||
const updateUrl = `${apiBaseUrl}/repos/${repository}/issues/comments/${existing.id}`;
|
||||
await apiRequest(updateUrl, 'PATCH', { body });
|
||||
console.log(`Updated existing telemetry comment (id: ${existing.id}).`);
|
||||
return;
|
||||
}
|
||||
|
||||
const createUrl = `${apiBaseUrl}/repos/${repository}/issues/${pullNumber}/comments`;
|
||||
await apiRequest(createUrl, 'POST', { body });
|
||||
console.log('Created telemetry comment on PR.');
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const eventPath = requireEnv('GITHUB_EVENT_PATH');
|
||||
const repository = requireEnv('GITHUB_REPOSITORY');
|
||||
const apiBaseUrl = process.env.GITHUB_API_URL || 'https://api.github.com';
|
||||
validateRepository(repository);
|
||||
|
||||
let parsedApiBaseUrl;
|
||||
try {
|
||||
parsedApiBaseUrl = new URL(apiBaseUrl);
|
||||
} catch {
|
||||
throw new Error(`Invalid GITHUB_API_URL: ${JSON.stringify(apiBaseUrl)}`);
|
||||
}
|
||||
|
||||
const event = readEventPayload(eventPath);
|
||||
const pullNumber = resolvePullNumber(event);
|
||||
|
||||
console.log(`Event name: ${process.env.GITHUB_EVENT_NAME || 'unknown'}`);
|
||||
console.log(`Repository: ${repository}`);
|
||||
console.log(`PR number: ${pullNumber}`);
|
||||
|
||||
const files = await getAllPullFiles(parsedApiBaseUrl.origin, repository, pullNumber);
|
||||
|
||||
if (files.length === 0) {
|
||||
console.log('No changed files found for PR; skipping telemetry comment update.');
|
||||
return;
|
||||
}
|
||||
|
||||
const matches = detectTelemetryChanges(files);
|
||||
const dataAndPrivacyChanged = hasDataAndPrivacyChange(files);
|
||||
|
||||
console.log(`Scanned ${files.length} changed files.`);
|
||||
console.log(`Telemetry matches found: ${matches.length}.`);
|
||||
console.log(`DATA_AND_PRIVACY.md changed: ${dataAndPrivacyChanged}.`);
|
||||
|
||||
if (matches.length === 0) {
|
||||
console.log('No telemetry-related additions/modifications detected.');
|
||||
return;
|
||||
}
|
||||
|
||||
for (const match of matches) {
|
||||
console.log(
|
||||
`- ${match.filename} (telemetryPath=${match.telemetryPath}, telemetryLineSignal=${match.telemetryLineSignal}, patchUnavailable=${match.patchUnavailable})`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const pullRequest = await getPullRequest(parsedApiBaseUrl.origin, repository, pullNumber);
|
||||
await ensureReviewerRequested(parsedApiBaseUrl.origin, repository, pullNumber, pullRequest);
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
'Failed to fetch PR details or request reviewer; continuing to post telemetry guidance comment.'
|
||||
);
|
||||
console.warn(error instanceof Error ? error.stack || error.message : error);
|
||||
}
|
||||
|
||||
const commentBody = dataAndPrivacyChanged
|
||||
? COMMENT_BODY_WITH_PRIVACY_UPDATE
|
||||
: COMMENT_BODY_WITHOUT_PRIVACY_UPDATE;
|
||||
|
||||
await upsertPrComment(apiBaseUrl, repository, pullNumber, commentBody);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('Telemetry PR check failed.');
|
||||
console.error(error instanceof Error ? error.stack || error.message : error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
The MIT License
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -9,13 +9,13 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
130
.github/skills/issue-fix/SKILL.md
vendored
Normal file
130
.github/skills/issue-fix/SKILL.md
vendored
Normal file
@@ -0,0 +1,130 @@
|
||||
---
|
||||
name: issue-fix
|
||||
description: Automatically fix GitHub issues using AI-assisted code generation. Use when asked to fix an issue, implement a feature from an issue, auto-fix an issue, apply implementation plan, create code changes for an issue, or resolve a GitHub issue. Creates isolated git worktree and applies AI-generated fixes based on the implementation plan.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# Issue Fix Skill
|
||||
|
||||
Automatically fix GitHub issues by creating isolated worktrees and applying AI-generated code changes based on implementation plans.
|
||||
|
||||
## Skill Contents
|
||||
|
||||
This skill is **self-contained** with all required resources:
|
||||
|
||||
```
|
||||
.github/skills/issue-fix/
|
||||
├── SKILL.md # This file
|
||||
├── LICENSE.txt # MIT License
|
||||
├── scripts/
|
||||
│ └── Start-IssueAutoFix.ps1 # Main fix script
|
||||
└── references/
|
||||
└── fix-issue.prompt.md # Full AI prompt template
|
||||
```
|
||||
|
||||
## Output Directory
|
||||
|
||||
Worktrees are created at the drive root level:
|
||||
|
||||
```
|
||||
Q:/PowerToys-xxxx/ # Worktree for issue (xxxx = short hash)
|
||||
├── Generated Files/
|
||||
│ └── issueReview/
|
||||
│ └── <issue-number>/ # Copied from main repo
|
||||
│ ├── overview.md
|
||||
│ └── implementation-plan.md
|
||||
└── <normal repo structure>
|
||||
```
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Fix a specific GitHub issue automatically
|
||||
- Implement a feature described in an issue
|
||||
- Apply an existing implementation plan
|
||||
- Create code changes for an issue
|
||||
- Auto-fix high-confidence issues
|
||||
- Resolve issues that have been reviewed
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- GitHub CLI (`gh`) installed and authenticated
|
||||
- Issue must be reviewed first (use `issue-review` skill)
|
||||
- PowerShell 7+ for running scripts
|
||||
- Copilot CLI or Claude CLI installed
|
||||
|
||||
## Required Variables
|
||||
|
||||
⚠️ **Before starting**, confirm `{{IssueNumber}}` with the user. If not provided, **ASK**: "What issue number should I fix?"
|
||||
|
||||
| Variable | Description | Example |
|
||||
|----------|-------------|---------|
|
||||
| `{{IssueNumber}}` | GitHub issue number to fix | `44044` |
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Ensure Issue is Reviewed
|
||||
|
||||
If not already reviewed, use the `issue-review` skill first.
|
||||
|
||||
### Step 2: Run Auto-Fix
|
||||
|
||||
Execute the fix script (use paths relative to this skill folder):
|
||||
|
||||
```powershell
|
||||
# From repo root
|
||||
.github/skills/issue-fix/scripts/Start-IssueAutoFix.ps1 -IssueNumber {{IssueNumber}} -CLIType copilot
|
||||
```
|
||||
|
||||
This will:
|
||||
1. Create a new git worktree with branch `issue/{{IssueNumber}}`
|
||||
2. Copy the review files to the worktree
|
||||
3. Launch Copilot CLI to implement the fix
|
||||
4. Build and verify the changes
|
||||
|
||||
### Step 3: Verify Changes
|
||||
|
||||
Navigate to the worktree and review:
|
||||
|
||||
```powershell
|
||||
# List worktrees
|
||||
git worktree list
|
||||
|
||||
# Check changes in the worktree
|
||||
cd Q:/PowerToys-xxxx
|
||||
git diff
|
||||
git status
|
||||
```
|
||||
|
||||
## CLI Options
|
||||
|
||||
| Parameter | Description | Default |
|
||||
|-----------|-------------|---------|
|
||||
| `-IssueNumber` | Issue to fix | Required |
|
||||
| `-CLIType` | AI CLI to use: `copilot` or `claude` | `copilot` |
|
||||
| `-Force` | Skip confirmation prompts | `false` |
|
||||
|
||||
## Batch Fix
|
||||
|
||||
To fix multiple issues:
|
||||
|
||||
```powershell
|
||||
.github/skills/issue-fix/scripts/Start-IssueAutoFix.ps1 -IssueNumbers 44044, 32950 -CLIType copilot -Force
|
||||
```
|
||||
|
||||
## After Fixing
|
||||
|
||||
Once the fix is complete, use the `submit-pr` skill to create a PR.
|
||||
|
||||
## AI Prompt Reference
|
||||
|
||||
For manual AI invocation, the full prompt is at:
|
||||
- `references/fix-issue.prompt.md` (relative to this skill folder)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Solution |
|
||||
|---------|----------|
|
||||
| Worktree already exists | Use existing worktree or delete with `git worktree remove <path>` |
|
||||
| No implementation plan | Use `issue-review` skill first |
|
||||
| Build failures | Check build logs, may need manual intervention |
|
||||
| CLI not found | Install Copilot CLI |
|
||||
72
.github/skills/issue-fix/references/fix-issue.prompt.md
vendored
Normal file
72
.github/skills/issue-fix/references/fix-issue.prompt.md
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
---
|
||||
agent: 'agent'
|
||||
description: 'Execute the fix for a GitHub issue using the previously generated implementation plan'
|
||||
---
|
||||
|
||||
# Fix GitHub Issue
|
||||
|
||||
## Dependencies
|
||||
Source review prompt (for generating the implementation plan if missing):
|
||||
- .github/prompts/review-issue.prompt.md
|
||||
|
||||
Required plan file (single source of truth):
|
||||
- Generated Files/issueReview/{{issue_number}}/implementation-plan.md
|
||||
|
||||
## Dependency Handling
|
||||
1) If `implementation-plan.md` exists → proceed.
|
||||
2) If missing → run the review prompt:
|
||||
- Invoke: `.github/prompts/review-issue.prompt.md`
|
||||
- Pass: `issue_number={{issue_number}}`
|
||||
- Then re-check for `implementation-plan.md`.
|
||||
3) If still missing → stop and generate:
|
||||
- `Generated Files/issueFix/{{issue_number}}/manual-steps.md` containing:
|
||||
“implementation-plan.md not found; please run .github/prompts/review-issue.prompt.md for #{{issue_number}}.”
|
||||
|
||||
# GOAL
|
||||
For **#{{issue_number}}**:
|
||||
- Use implementation-plan.md as the single authority.
|
||||
- Apply code and test changes directly in the repository.
|
||||
- Produce a PR-ready description.
|
||||
|
||||
# OUTPUT FILES
|
||||
1) Generated Files/issueFix/{{issue_number}}/pr-description.md
|
||||
2) Generated Files/issueFix/{{issue_number}}/manual-steps.md # only if human interaction or external setup is required
|
||||
|
||||
# EXECUTION RULES
|
||||
1) Read implementation-plan.md and execute:
|
||||
- Layers & Files → edit/create as listed
|
||||
- Pattern Choices → follow repository conventions
|
||||
- Fundamentals (perf, security, compatibility, accessibility)
|
||||
- Logging & Exceptions
|
||||
- Telemetry (only if explicitly included in the plan)
|
||||
- Risks & Mitigations
|
||||
- Tests to Add
|
||||
2) Locate affected files via `rg` or `git grep`.
|
||||
3) Add/update tests to enforce the fixed behavior.
|
||||
4) If any ambiguity exists, add:
|
||||
// TODO(Human input needed): <clarification needed>
|
||||
5) Verify locally: build & tests run successfully.
|
||||
|
||||
# pr-description.md should include:
|
||||
- Title: `Fix: <short summary> (#{{issue_number}})`
|
||||
- What changed and why the fix works
|
||||
- Files or modules touched
|
||||
- Risks & mitigations (implemented)
|
||||
- Tests added/updated and how to run them
|
||||
- Telemetry behavior (if applicable)
|
||||
- Validation / reproduction steps
|
||||
- `Closes #{{issue_number}}`
|
||||
|
||||
# manual-steps.md (only if needed)
|
||||
- List required human actions: secrets, config, approvals, missing info, or code comments requiring human decisions.
|
||||
|
||||
# IMPORTANT
|
||||
- Apply code and tests directly; do not produce patch files.
|
||||
- Follow implementation-plan.md as the source of truth.
|
||||
- Insert comments for human review where a decision or input is required.
|
||||
- Use repository conventions and deterministic, minimal changes.
|
||||
|
||||
# FINALIZE
|
||||
- Write pr-description.md
|
||||
- Write manual-steps.md only if needed
|
||||
- Print concise success message or note items requiring human interaction
|
||||
9
.github/skills/issue-fix/references/mcp-config.json
vendored
Normal file
9
.github/skills/issue-fix/references/mcp-config.json
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"github-artifacts": {
|
||||
"command": "cmd",
|
||||
"args": ["/c", "for /f %i in ('git rev-parse --show-toplevel') do node %i/tools/mcp/github-artifacts/launch.js"],
|
||||
"tools": ["*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
643
.github/skills/issue-fix/scripts/IssueReviewLib.ps1
vendored
Normal file
643
.github/skills/issue-fix/scripts/IssueReviewLib.ps1
vendored
Normal file
@@ -0,0 +1,643 @@
|
||||
# IssueReviewLib.ps1 - Helpers for issue auto-fix workflow
|
||||
# Part of the PowerToys GitHub Copilot/Claude Code issue review system
|
||||
# This is a trimmed version with only what issue-fix needs
|
||||
|
||||
#region Console Output Helpers
|
||||
function Info { param([string]$Message) Write-Host $Message -ForegroundColor Cyan }
|
||||
function Warn { param([string]$Message) Write-Host $Message -ForegroundColor Yellow }
|
||||
function Err { param([string]$Message) Write-Host $Message -ForegroundColor Red }
|
||||
function Success { param([string]$Message) Write-Host $Message -ForegroundColor Green }
|
||||
#endregion
|
||||
|
||||
#region Repository Helpers
|
||||
function Get-RepoRoot {
|
||||
$root = git rev-parse --show-toplevel 2>$null
|
||||
if (-not $root) { throw 'Not inside a git repository.' }
|
||||
return (Resolve-Path $root).Path
|
||||
}
|
||||
|
||||
function Get-GeneratedFilesPath {
|
||||
param([string]$RepoRoot)
|
||||
return Join-Path $RepoRoot 'Generated Files'
|
||||
}
|
||||
|
||||
function Get-IssueReviewPath {
|
||||
param(
|
||||
[string]$RepoRoot,
|
||||
[int]$IssueNumber
|
||||
)
|
||||
$genFiles = Get-GeneratedFilesPath -RepoRoot $RepoRoot
|
||||
return Join-Path $genFiles "issueReview/$IssueNumber"
|
||||
}
|
||||
|
||||
function Ensure-DirectoryExists {
|
||||
param([string]$Path)
|
||||
if (-not (Test-Path $Path)) {
|
||||
New-Item -ItemType Directory -Path $Path -Force | Out-Null
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region CLI Detection
|
||||
function Get-AvailableCLI {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Detect which AI CLI is available: GitHub Copilot CLI or Claude Code.
|
||||
#>
|
||||
|
||||
# Check for standalone GitHub Copilot CLI
|
||||
$copilotCLI = Get-Command 'copilot' -ErrorAction SilentlyContinue
|
||||
if ($copilotCLI) {
|
||||
return @{ Name = 'GitHub Copilot CLI'; Command = 'copilot'; Type = 'copilot' }
|
||||
}
|
||||
|
||||
# Check for Claude Code CLI
|
||||
$claudeCode = Get-Command 'claude' -ErrorAction SilentlyContinue
|
||||
if ($claudeCode) {
|
||||
return @{ Name = 'Claude Code CLI'; Command = 'claude'; Type = 'claude' }
|
||||
}
|
||||
|
||||
# Check for GitHub Copilot CLI via gh extension
|
||||
$ghCopilot = Get-Command 'gh' -ErrorAction SilentlyContinue
|
||||
if ($ghCopilot) {
|
||||
$copilotCheck = gh extension list 2>&1 | Select-String -Pattern 'copilot'
|
||||
if ($copilotCheck) {
|
||||
return @{ Name = 'GitHub Copilot CLI (gh extension)'; Command = 'gh'; Type = 'gh-copilot' }
|
||||
}
|
||||
}
|
||||
|
||||
# Check for VS Code CLI
|
||||
$code = Get-Command 'code' -ErrorAction SilentlyContinue
|
||||
if ($code) {
|
||||
return @{ Name = 'VS Code (Copilot Chat)'; Command = 'code'; Type = 'vscode' }
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Issue Review Results Helpers
|
||||
function Get-IssueReviewResult {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Check if an issue has been reviewed and get its results.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$IssueNumber,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RepoRoot
|
||||
)
|
||||
|
||||
$reviewPath = Get-IssueReviewPath -RepoRoot $RepoRoot -IssueNumber $IssueNumber
|
||||
|
||||
$result = @{
|
||||
IssueNumber = $IssueNumber
|
||||
Path = $reviewPath
|
||||
HasOverview = $false
|
||||
HasImplementationPlan = $false
|
||||
OverviewPath = $null
|
||||
ImplementationPlanPath = $null
|
||||
}
|
||||
|
||||
$overviewPath = Join-Path $reviewPath 'overview.md'
|
||||
$implPlanPath = Join-Path $reviewPath 'implementation-plan.md'
|
||||
|
||||
if (Test-Path $overviewPath) {
|
||||
$result.HasOverview = $true
|
||||
$result.OverviewPath = $overviewPath
|
||||
}
|
||||
|
||||
if (Test-Path $implPlanPath) {
|
||||
$result.HasImplementationPlan = $true
|
||||
$result.ImplementationPlanPath = $implPlanPath
|
||||
}
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
function Get-HighConfidenceIssues {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Find issues with high confidence for auto-fix based on review results.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RepoRoot,
|
||||
[int]$MinFeasibilityScore = 70,
|
||||
[int]$MinClarityScore = 60,
|
||||
[int]$MaxEffortDays = 2,
|
||||
[int[]]$FilterIssueNumbers = @()
|
||||
)
|
||||
|
||||
$genFiles = Get-GeneratedFilesPath -RepoRoot $RepoRoot
|
||||
$reviewDir = Join-Path $genFiles 'issueReview'
|
||||
|
||||
if (-not (Test-Path $reviewDir)) {
|
||||
return @()
|
||||
}
|
||||
|
||||
$highConfidence = @()
|
||||
|
||||
Get-ChildItem -Path $reviewDir -Directory | ForEach-Object {
|
||||
$issueNum = [int]$_.Name
|
||||
|
||||
if ($FilterIssueNumbers.Count -gt 0 -and $issueNum -notin $FilterIssueNumbers) {
|
||||
return
|
||||
}
|
||||
|
||||
$overviewPath = Join-Path $_.FullName 'overview.md'
|
||||
$implPlanPath = Join-Path $_.FullName 'implementation-plan.md'
|
||||
|
||||
if (-not (Test-Path $overviewPath) -or -not (Test-Path $implPlanPath)) {
|
||||
return
|
||||
}
|
||||
|
||||
$overview = Get-Content $overviewPath -Raw
|
||||
|
||||
$feasibility = 0
|
||||
$clarity = 0
|
||||
$effortDays = 999
|
||||
|
||||
if ($overview -match 'Technical Feasibility[^\d]*(\d+)/100') {
|
||||
$feasibility = [int]$Matches[1]
|
||||
}
|
||||
if ($overview -match 'Requirement Clarity[^\d]*(\d+)/100') {
|
||||
$clarity = [int]$Matches[1]
|
||||
}
|
||||
if ($overview -match 'Effort Estimate[^|]*\|\s*[\d.]+(?:-(\d+))?\s*days?') {
|
||||
if ($Matches[1]) {
|
||||
$effortDays = [int]$Matches[1]
|
||||
} elseif ($overview -match 'Effort Estimate[^|]*\|\s*(\d+)\s*days?') {
|
||||
$effortDays = [int]$Matches[1]
|
||||
}
|
||||
}
|
||||
if ($overview -match 'Effort Estimate[^|]*\|[^|]*\|\s*(XS|S)\b') {
|
||||
if ($Matches[1] -eq 'XS') { $effortDays = 1 } else { $effortDays = 2 }
|
||||
} elseif ($overview -match 'Effort Estimate[^|]*\|[^|]*\(XS\)') {
|
||||
$effortDays = 1
|
||||
} elseif ($overview -match 'Effort Estimate[^|]*\|[^|]*\(S\)') {
|
||||
$effortDays = 2
|
||||
}
|
||||
|
||||
if ($feasibility -ge $MinFeasibilityScore -and
|
||||
$clarity -ge $MinClarityScore -and
|
||||
$effortDays -le $MaxEffortDays) {
|
||||
|
||||
$highConfidence += @{
|
||||
IssueNumber = $issueNum
|
||||
FeasibilityScore = $feasibility
|
||||
ClarityScore = $clarity
|
||||
EffortDays = $effortDays
|
||||
OverviewPath = $overviewPath
|
||||
ImplementationPlanPath = $implPlanPath
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $highConfidence | Sort-Object -Property FeasibilityScore -Descending
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Release & PR Status Helpers
|
||||
function Get-PRReleaseStatus {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Check if a PR has been merged and released.
|
||||
.DESCRIPTION
|
||||
Queries GitHub to determine:
|
||||
1. If the PR is merged
|
||||
2. What release (if any) contains the merge commit
|
||||
.OUTPUTS
|
||||
@{
|
||||
PRNumber = <int>
|
||||
IsMerged = $true | $false
|
||||
MergeCommit = <commit sha or $null>
|
||||
ReleasedIn = <version string or $null> # e.g., "v0.90.0"
|
||||
IsReleased = $true | $false
|
||||
}
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$PRNumber,
|
||||
[string]$Repo = 'microsoft/PowerToys'
|
||||
)
|
||||
|
||||
$result = @{
|
||||
PRNumber = $PRNumber
|
||||
IsMerged = $false
|
||||
MergeCommit = $null
|
||||
ReleasedIn = $null
|
||||
IsReleased = $false
|
||||
}
|
||||
|
||||
try {
|
||||
# Get PR details from GitHub
|
||||
$prJson = gh pr view $PRNumber --repo $Repo --json state,mergeCommit,mergedAt 2>$null
|
||||
if (-not $prJson) {
|
||||
return $result
|
||||
}
|
||||
|
||||
$pr = $prJson | ConvertFrom-Json
|
||||
|
||||
if ($pr.state -eq 'MERGED' -and $pr.mergeCommit) {
|
||||
$result.IsMerged = $true
|
||||
$result.MergeCommit = $pr.mergeCommit.oid
|
||||
|
||||
# Check which release tags contain this commit
|
||||
# Use git tag --contains to find tags that include the merge commit
|
||||
$tags = git tag --contains $result.MergeCommit 2>$null
|
||||
|
||||
if ($tags) {
|
||||
# Filter to release tags (v0.XX.X pattern) and get the earliest one
|
||||
$releaseTags = $tags | Where-Object { $_ -match '^v\d+\.\d+\.\d+$' } | Sort-Object
|
||||
if ($releaseTags) {
|
||||
$result.ReleasedIn = $releaseTags | Select-Object -First 1
|
||||
$result.IsReleased = $true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
# Silently fail - will return default "not merged" status
|
||||
}
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
function Get-LatestRelease {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Get the latest release version of PowerToys.
|
||||
#>
|
||||
param(
|
||||
[string]$Repo = 'microsoft/PowerToys'
|
||||
)
|
||||
|
||||
try {
|
||||
$releaseJson = gh release view --repo $Repo --json tagName 2>$null
|
||||
if ($releaseJson) {
|
||||
$release = $releaseJson | ConvertFrom-Json
|
||||
return $release.tagName
|
||||
}
|
||||
}
|
||||
catch {
|
||||
# Fallback: try to get from git tags
|
||||
$latestTag = git describe --tags --abbrev=0 2>$null
|
||||
if ($latestTag) {
|
||||
return $latestTag
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Implementation Plan Analysis
|
||||
function Get-ImplementationPlanStatus {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Parse implementation-plan.md to determine the recommended action.
|
||||
.DESCRIPTION
|
||||
Reads the implementation plan and extracts the status/recommendation.
|
||||
For "already resolved" issues, also checks if the fix has been released.
|
||||
Returns an object indicating what action should be taken.
|
||||
.OUTPUTS
|
||||
@{
|
||||
Status = 'AlreadyResolved' | 'FixedButUnreleased' | 'NeedsClarification' | 'Duplicate' | 'WontFix' | 'ReadyToImplement' | 'Unknown'
|
||||
Action = 'CloseIssue' | 'AddComment' | 'LinkDuplicate' | 'ImplementFix' | 'Skip'
|
||||
Reason = <string explaining why>
|
||||
RelatedPR = <PR number if already fixed>
|
||||
ReleasedIn = <version if released, e.g., "v0.90.0">
|
||||
DuplicateOf = <issue number if duplicate>
|
||||
CommentText = <suggested comment if applicable>
|
||||
}
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$ImplementationPlanPath,
|
||||
[switch]$SkipReleaseCheck
|
||||
)
|
||||
|
||||
$result = @{
|
||||
Status = 'Unknown'
|
||||
Action = 'Skip'
|
||||
Reason = 'Could not determine status from implementation plan'
|
||||
RelatedPR = $null
|
||||
ReleasedIn = $null
|
||||
DuplicateOf = $null
|
||||
CommentText = $null
|
||||
}
|
||||
|
||||
if (-not (Test-Path $ImplementationPlanPath)) {
|
||||
$result.Reason = 'Implementation plan file not found'
|
||||
return $result
|
||||
}
|
||||
|
||||
$content = Get-Content $ImplementationPlanPath -Raw
|
||||
|
||||
# Check for ALREADY RESOLVED status
|
||||
if ($content -match '(?i)STATUS:\s*ALREADY\s+RESOLVED' -or
|
||||
$content -match '(?i)⚠️\s*STATUS:\s*ALREADY\s+RESOLVED' -or
|
||||
$content -match '(?i)This issue has been fixed by' -or
|
||||
$content -match '(?i)No implementation work is needed') {
|
||||
|
||||
# Try to extract the PR number
|
||||
$prNumber = $null
|
||||
if ($content -match '\[PR #(\d+)\]' -or $content -match 'PR #(\d+)' -or $content -match '/pull/(\d+)') {
|
||||
$prNumber = [int]$Matches[1]
|
||||
$result.RelatedPR = $prNumber
|
||||
}
|
||||
|
||||
# Check if the fix has been released
|
||||
if ($prNumber -and -not $SkipReleaseCheck) {
|
||||
$prStatus = Get-PRReleaseStatus -PRNumber $prNumber
|
||||
|
||||
if ($prStatus.IsReleased) {
|
||||
# Fix is released - safe to close
|
||||
$result.Status = 'AlreadyResolved'
|
||||
$result.Action = 'CloseIssue'
|
||||
$result.ReleasedIn = $prStatus.ReleasedIn
|
||||
$result.Reason = "Issue fixed by PR #$prNumber, released in $($prStatus.ReleasedIn)"
|
||||
$result.CommentText = @"
|
||||
This issue has been fixed by PR #$prNumber and is available in **$($prStatus.ReleasedIn)**.
|
||||
|
||||
Please update to the latest version. If you're still experiencing this issue after updating, please reopen with additional details.
|
||||
"@
|
||||
}
|
||||
elseif ($prStatus.IsMerged) {
|
||||
# PR merged but not yet released - add comment but don't close
|
||||
$result.Status = 'FixedButUnreleased'
|
||||
$result.Action = 'AddComment'
|
||||
$result.Reason = "Issue fixed by PR #$prNumber, but not yet released"
|
||||
$result.CommentText = @"
|
||||
This issue has been fixed by PR #$prNumber, which has been merged but **not yet released**.
|
||||
|
||||
The fix will be available in the next PowerToys release. You can:
|
||||
- Wait for the next official release
|
||||
- Build from source to get the fix immediately
|
||||
|
||||
We'll close this issue once the fix is released.
|
||||
"@
|
||||
}
|
||||
else {
|
||||
# PR exists but not merged - treat as ready to implement (PR might have been reverted)
|
||||
$result.Status = 'ReadyToImplement'
|
||||
$result.Action = 'ImplementFix'
|
||||
$result.Reason = "PR #$prNumber exists but is not merged - may need reimplementation"
|
||||
}
|
||||
}
|
||||
elseif ($prNumber) {
|
||||
# Skip release check requested or no PR number - assume it's resolved
|
||||
$result.Status = 'AlreadyResolved'
|
||||
$result.Action = 'CloseIssue'
|
||||
$result.Reason = 'Issue has already been fixed'
|
||||
$result.CommentText = "This issue has been fixed by PR #$prNumber. Closing as resolved."
|
||||
}
|
||||
else {
|
||||
# No PR number found - just mark as resolved with generic message
|
||||
$result.Status = 'AlreadyResolved'
|
||||
$result.Action = 'CloseIssue'
|
||||
$result.Reason = 'Issue appears to have been resolved'
|
||||
$result.CommentText = "Based on analysis, this issue appears to have already been resolved. Please verify and reopen if the issue persists."
|
||||
}
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
# Check for DUPLICATE status
|
||||
if ($content -match '(?i)STATUS:\s*DUPLICATE' -or
|
||||
$content -match '(?i)This is a duplicate of' -or
|
||||
$content -match '(?i)duplicate of #(\d+)') {
|
||||
|
||||
$result.Status = 'Duplicate'
|
||||
$result.Action = 'LinkDuplicate'
|
||||
$result.Reason = 'Issue is a duplicate'
|
||||
|
||||
# Try to extract the duplicate issue number
|
||||
if ($content -match 'duplicate of #(\d+)' -or $content -match '#(\d+)') {
|
||||
$result.DuplicateOf = [int]$Matches[1]
|
||||
$result.CommentText = "This appears to be a duplicate of #$($result.DuplicateOf)."
|
||||
}
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
# Check for NEEDS CLARIFICATION status
|
||||
if ($content -match '(?i)STATUS:\s*NEEDS?\s+CLARIFICATION' -or
|
||||
$content -match '(?i)STATUS:\s*NEEDS?\s+MORE\s+INFO' -or
|
||||
$content -match '(?i)cannot proceed without' -or
|
||||
$content -match '(?i)need(?:s)? more information') {
|
||||
|
||||
$result.Status = 'NeedsClarification'
|
||||
$result.Action = 'AddComment'
|
||||
$result.Reason = 'Issue needs more information from reporter'
|
||||
|
||||
# Try to extract what information is needed
|
||||
if ($content -match '(?i)(?:need(?:s)?|require(?:s)?|missing)[:\s]+([^\n]+)') {
|
||||
$result.CommentText = "Additional information is needed to proceed with this issue: $($Matches[1].Trim())"
|
||||
} else {
|
||||
$result.CommentText = "Could you please provide more details about this issue? Specifically, steps to reproduce and expected vs actual behavior would help."
|
||||
}
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
# Check for WONT FIX / NOT FEASIBLE status
|
||||
if ($content -match '(?i)STATUS:\s*(?:WONT?\s+FIX|NOT\s+FEASIBLE|REJECTED)' -or
|
||||
$content -match '(?i)(?:not|cannot be) (?:feasible|implemented)' -or
|
||||
$content -match '(?i)recommend(?:ed)?\s+(?:to\s+)?close') {
|
||||
|
||||
$result.Status = 'WontFix'
|
||||
$result.Action = 'AddComment'
|
||||
$result.Reason = 'Issue is not feasible or recommended to close'
|
||||
|
||||
# Try to extract the reason
|
||||
if ($content -match '(?i)(?:because|reason|due to)[:\s]+([^\n]+)') {
|
||||
$result.CommentText = "After analysis, this issue cannot be implemented: $($Matches[1].Trim())"
|
||||
}
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
# Check for external dependency / blocked status
|
||||
if ($content -match '(?i)STATUS:\s*BLOCKED' -or
|
||||
$content -match '(?i)blocked by' -or
|
||||
$content -match '(?i)depends on external' -or
|
||||
$content -match '(?i)waiting for upstream') {
|
||||
|
||||
$result.Status = 'Blocked'
|
||||
$result.Action = 'AddComment'
|
||||
$result.Reason = 'Issue is blocked by external dependency'
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
# Check for READY TO IMPLEMENT (positive signals)
|
||||
if ($content -match '(?i)## \d+\)\s*Task Breakdown' -or
|
||||
$content -match '(?i)implementation steps' -or
|
||||
$content -match '(?i)## Layers & Files' -or
|
||||
($content -match '(?i)Feasibility' -and $content -notmatch '(?i)not\s+feasible')) {
|
||||
|
||||
$result.Status = 'ReadyToImplement'
|
||||
$result.Action = 'ImplementFix'
|
||||
$result.Reason = 'Implementation plan is ready'
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
# Default: if we have a detailed plan, assume it's ready
|
||||
if ($content.Length -gt 500 -and $content -match '(?i)##') {
|
||||
$result.Status = 'ReadyToImplement'
|
||||
$result.Action = 'ImplementFix'
|
||||
$result.Reason = 'Implementation plan appears complete'
|
||||
}
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
function Invoke-ImplementationPlanAction {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Execute the recommended action from the implementation plan analysis.
|
||||
.DESCRIPTION
|
||||
Based on the status from Get-ImplementationPlanStatus, takes appropriate action:
|
||||
- CloseIssue: Closes the issue with a comment
|
||||
- AddComment: Adds a comment to the issue
|
||||
- LinkDuplicate: Marks as duplicate
|
||||
- ImplementFix: Returns $true to indicate code fix should proceed
|
||||
- Skip: Returns $false
|
||||
.OUTPUTS
|
||||
@{
|
||||
ActionTaken = <string describing what was done>
|
||||
ShouldProceedWithFix = $true | $false
|
||||
Success = $true | $false
|
||||
}
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$IssueNumber,
|
||||
[Parameter(Mandatory)]
|
||||
[hashtable]$PlanStatus,
|
||||
[switch]$DryRun
|
||||
)
|
||||
|
||||
$result = @{
|
||||
ActionTaken = 'None'
|
||||
ShouldProceedWithFix = $false
|
||||
Success = $true
|
||||
}
|
||||
|
||||
switch ($PlanStatus.Action) {
|
||||
'ImplementFix' {
|
||||
$result.ActionTaken = 'Proceeding with code fix'
|
||||
$result.ShouldProceedWithFix = $true
|
||||
Info "[Issue #$IssueNumber] Status: $($PlanStatus.Status) - $($PlanStatus.Reason)"
|
||||
}
|
||||
|
||||
'CloseIssue' {
|
||||
$result.ActionTaken = "Closing issue: $($PlanStatus.Reason)"
|
||||
Info "[Issue #$IssueNumber] $($PlanStatus.Status): $($PlanStatus.Reason)"
|
||||
|
||||
if (-not $DryRun) {
|
||||
$comment = $PlanStatus.CommentText
|
||||
if (-not $comment) {
|
||||
$comment = "Closing based on automated analysis: $($PlanStatus.Reason)"
|
||||
}
|
||||
|
||||
try {
|
||||
# Add comment explaining closure
|
||||
gh issue comment $IssueNumber --body $comment 2>&1 | Out-Null
|
||||
|
||||
# Close the issue
|
||||
if ($PlanStatus.RelatedPR) {
|
||||
gh issue close $IssueNumber --reason "completed" --comment "Resolved by PR #$($PlanStatus.RelatedPR)" 2>&1 | Out-Null
|
||||
} else {
|
||||
gh issue close $IssueNumber --reason "completed" 2>&1 | Out-Null
|
||||
}
|
||||
|
||||
Success "[Issue #$IssueNumber] ✓ Closed with comment"
|
||||
}
|
||||
catch {
|
||||
Err "[Issue #$IssueNumber] Failed to close: $($_.Exception.Message)"
|
||||
$result.Success = $false
|
||||
}
|
||||
} else {
|
||||
Info "[Issue #$IssueNumber] (DryRun) Would close with: $($PlanStatus.CommentText)"
|
||||
}
|
||||
}
|
||||
|
||||
'AddComment' {
|
||||
$result.ActionTaken = "Adding comment: $($PlanStatus.Reason)"
|
||||
Info "[Issue #$IssueNumber] $($PlanStatus.Status): $($PlanStatus.Reason)"
|
||||
|
||||
if (-not $DryRun -and $PlanStatus.CommentText) {
|
||||
try {
|
||||
gh issue comment $IssueNumber --body $PlanStatus.CommentText 2>&1 | Out-Null
|
||||
Success "[Issue #$IssueNumber] ✓ Comment added"
|
||||
}
|
||||
catch {
|
||||
Err "[Issue #$IssueNumber] Failed to add comment: $($_.Exception.Message)"
|
||||
$result.Success = $false
|
||||
}
|
||||
} else {
|
||||
Info "[Issue #$IssueNumber] (DryRun) Would comment: $($PlanStatus.CommentText)"
|
||||
}
|
||||
}
|
||||
|
||||
'LinkDuplicate' {
|
||||
$result.ActionTaken = "Marking as duplicate of #$($PlanStatus.DuplicateOf)"
|
||||
Info "[Issue #$IssueNumber] Duplicate of #$($PlanStatus.DuplicateOf)"
|
||||
|
||||
if (-not $DryRun -and $PlanStatus.DuplicateOf) {
|
||||
try {
|
||||
gh issue close $IssueNumber --reason "not_planned" --comment "Closing as duplicate of #$($PlanStatus.DuplicateOf)" 2>&1 | Out-Null
|
||||
Success "[Issue #$IssueNumber] ✓ Closed as duplicate"
|
||||
}
|
||||
catch {
|
||||
Err "[Issue #$IssueNumber] Failed to close as duplicate: $($_.Exception.Message)"
|
||||
$result.Success = $false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
'Skip' {
|
||||
$result.ActionTaken = "Skipped: $($PlanStatus.Reason)"
|
||||
Warn "[Issue #$IssueNumber] Skipping: $($PlanStatus.Reason)"
|
||||
}
|
||||
}
|
||||
|
||||
return $result
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Worktree Integration
|
||||
function Copy-IssueReviewToWorktree {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Copy the Generated Files for an issue to a worktree.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$IssueNumber,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$SourceRepoRoot,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$WorktreePath
|
||||
)
|
||||
|
||||
$sourceReviewPath = Get-IssueReviewPath -RepoRoot $SourceRepoRoot -IssueNumber $IssueNumber
|
||||
$destReviewPath = Get-IssueReviewPath -RepoRoot $WorktreePath -IssueNumber $IssueNumber
|
||||
|
||||
if (-not (Test-Path $sourceReviewPath)) {
|
||||
throw "Issue review files not found at: $sourceReviewPath"
|
||||
}
|
||||
|
||||
Ensure-DirectoryExists -Path $destReviewPath
|
||||
|
||||
Copy-Item -Path "$sourceReviewPath\*" -Destination $destReviewPath -Recurse -Force
|
||||
|
||||
Info "Copied issue review files to: $destReviewPath"
|
||||
|
||||
return $destReviewPath
|
||||
}
|
||||
#endregion
|
||||
530
.github/skills/issue-fix/scripts/Start-IssueAutoFix.ps1
vendored
Normal file
530
.github/skills/issue-fix/scripts/Start-IssueAutoFix.ps1
vendored
Normal file
@@ -0,0 +1,530 @@
|
||||
<#!
|
||||
.SYNOPSIS
|
||||
Auto-fix high-confidence issues using worktrees and AI CLI.
|
||||
|
||||
.DESCRIPTION
|
||||
Finds issues with high confidence scores from the review results, creates worktrees
|
||||
for each, copies the Generated Files, and kicks off the FixIssue agent to implement fixes.
|
||||
|
||||
.PARAMETER IssueNumber
|
||||
Specific issue number to fix. If not specified, finds high-confidence issues automatically.
|
||||
|
||||
.PARAMETER MinFeasibilityScore
|
||||
Minimum Technical Feasibility score (0-100). Default: 70.
|
||||
|
||||
.PARAMETER MinClarityScore
|
||||
Minimum Requirement Clarity score (0-100). Default: 60.
|
||||
|
||||
.PARAMETER MaxEffortDays
|
||||
Maximum effort estimate in days. Default: 2 (Small fixes).
|
||||
|
||||
.PARAMETER MaxParallel
|
||||
Maximum parallel fix jobs. Default: 5 (worktrees are resource-intensive).
|
||||
|
||||
.PARAMETER CLIType
|
||||
AI CLI to use: claude, gh-copilot, or vscode. Auto-detected if not specified.
|
||||
|
||||
.PARAMETER DryRun
|
||||
List issues without starting fixes.
|
||||
|
||||
.PARAMETER SkipWorktree
|
||||
Fix in the current repository instead of creating worktrees (useful for single issue).
|
||||
|
||||
.PARAMETER VSCodeProfile
|
||||
VS Code profile to use when opening worktrees. Default: Default.
|
||||
|
||||
.PARAMETER AutoCommit
|
||||
Automatically commit changes after successful fix.
|
||||
|
||||
.PARAMETER CreatePR
|
||||
Automatically create a pull request after successful fix.
|
||||
|
||||
.EXAMPLE
|
||||
# Fix a specific issue
|
||||
./Start-IssueAutoFix.ps1 -IssueNumber 12345
|
||||
|
||||
.EXAMPLE
|
||||
# Find and fix all high-confidence issues (dry run)
|
||||
./Start-IssueAutoFix.ps1 -DryRun
|
||||
|
||||
.EXAMPLE
|
||||
# Fix issues with very high confidence
|
||||
./Start-IssueAutoFix.ps1 -MinFeasibilityScore 80 -MinClarityScore 70 -MaxEffortDays 1
|
||||
|
||||
.EXAMPLE
|
||||
# Fix single issue in current repo (no worktree)
|
||||
./Start-IssueAutoFix.ps1 -IssueNumber 12345 -SkipWorktree
|
||||
|
||||
.NOTES
|
||||
Prerequisites:
|
||||
- Run Start-BulkIssueReview.ps1 first to generate review files
|
||||
- GitHub CLI (gh) authenticated
|
||||
- Claude Code CLI or VS Code with Copilot
|
||||
|
||||
Results:
|
||||
- Worktrees created at ../<RepoName>-<hash>/
|
||||
- Generated Files copied to each worktree
|
||||
- Fix agent invoked in each worktree
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[int]$IssueNumber,
|
||||
|
||||
[int]$MinFeasibilityScore = 70,
|
||||
|
||||
[int]$MinClarityScore = 60,
|
||||
|
||||
[int]$MaxEffortDays = 2,
|
||||
|
||||
[int]$MaxParallel = 5,
|
||||
|
||||
[ValidateSet('claude', 'copilot', 'gh-copilot', 'vscode', 'auto')]
|
||||
[string]$CLIType = 'auto',
|
||||
|
||||
[switch]$DryRun,
|
||||
|
||||
[switch]$SkipWorktree,
|
||||
|
||||
[Alias('Profile')]
|
||||
[string]$VSCodeProfile = 'Default',
|
||||
|
||||
[switch]$AutoCommit,
|
||||
|
||||
[switch]$CreatePR,
|
||||
|
||||
[switch]$Force,
|
||||
|
||||
[switch]$Help
|
||||
)
|
||||
|
||||
# Load libraries
|
||||
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
. "$scriptDir/IssueReviewLib.ps1"
|
||||
|
||||
# Load worktree library from tools/build
|
||||
$repoRoot = Get-RepoRoot
|
||||
$worktreeLib = Join-Path $repoRoot 'tools/build/WorktreeLib.ps1'
|
||||
if (Test-Path $worktreeLib) {
|
||||
. $worktreeLib
|
||||
}
|
||||
|
||||
# Show help
|
||||
if ($Help) {
|
||||
Get-Help $MyInvocation.MyCommand.Path -Full
|
||||
return
|
||||
}
|
||||
|
||||
function Start-IssueFixInWorktree {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Analyze implementation plan and either take action or create worktree for fix.
|
||||
.DESCRIPTION
|
||||
First analyzes the implementation plan to determine if:
|
||||
- Issue is already resolved (close it)
|
||||
- Issue needs clarification (add comment)
|
||||
- Issue is a duplicate (close as duplicate)
|
||||
- Issue is ready to implement (create worktree and fix)
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$IssueNumber,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$SourceRepoRoot,
|
||||
[string]$CLIType = 'claude',
|
||||
[string]$VSCodeProfile = 'Default',
|
||||
[switch]$SkipWorktree,
|
||||
[switch]$DryRun
|
||||
)
|
||||
|
||||
$issueReviewPath = Get-IssueReviewPath -RepoRoot $SourceRepoRoot -IssueNumber $IssueNumber
|
||||
$overviewPath = Join-Path $issueReviewPath 'overview.md'
|
||||
$implPlanPath = Join-Path $issueReviewPath 'implementation-plan.md'
|
||||
|
||||
# Verify review files exist
|
||||
if (-not (Test-Path $overviewPath)) {
|
||||
throw "No overview.md found for issue #$IssueNumber. Run Start-BulkIssueReview.ps1 first."
|
||||
}
|
||||
if (-not (Test-Path $implPlanPath)) {
|
||||
throw "No implementation-plan.md found for issue #$IssueNumber. Run Start-BulkIssueReview.ps1 first."
|
||||
}
|
||||
|
||||
# =====================================
|
||||
# STEP 1: Analyze the implementation plan
|
||||
# =====================================
|
||||
Info "Analyzing implementation plan for issue #$IssueNumber..."
|
||||
$planStatus = Get-ImplementationPlanStatus -ImplementationPlanPath $implPlanPath
|
||||
|
||||
# =====================================
|
||||
# STEP 2: Execute the recommended action
|
||||
# =====================================
|
||||
$actionResult = Invoke-ImplementationPlanAction -IssueNumber $IssueNumber -PlanStatus $planStatus -DryRun:$DryRun
|
||||
|
||||
# If we shouldn't proceed with fix, return early
|
||||
if (-not $actionResult.ShouldProceedWithFix) {
|
||||
return @{
|
||||
IssueNumber = $IssueNumber
|
||||
WorktreePath = $null
|
||||
Success = $actionResult.Success
|
||||
ActionTaken = $actionResult.ActionTaken
|
||||
SkippedCodeFix = $true
|
||||
}
|
||||
}
|
||||
|
||||
# =====================================
|
||||
# STEP 3: Proceed with code fix
|
||||
# =====================================
|
||||
|
||||
$workingDir = $SourceRepoRoot
|
||||
|
||||
if (-not $SkipWorktree) {
|
||||
# Use the simplified New-WorktreeFromIssue.cmd which only needs issue number
|
||||
$worktreeCmd = Join-Path $SourceRepoRoot 'tools/build/New-WorktreeFromIssue.cmd'
|
||||
|
||||
Info "Creating worktree for issue #$IssueNumber..."
|
||||
|
||||
# Call the cmd script with issue number and -NoVSCode for automation
|
||||
& cmd /c $worktreeCmd $IssueNumber -NoVSCode
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Failed to create worktree for issue #$IssueNumber"
|
||||
}
|
||||
|
||||
# Find the created worktree
|
||||
$entries = Get-WorktreeEntries
|
||||
$worktreeEntry = $entries | Where-Object { $_.Branch -like "issue/$IssueNumber*" } | Select-Object -First 1
|
||||
|
||||
if (-not $worktreeEntry) {
|
||||
throw "Failed to find worktree for issue #$IssueNumber"
|
||||
}
|
||||
|
||||
$workingDir = $worktreeEntry.Path
|
||||
Info "Worktree created at: $workingDir"
|
||||
|
||||
# Copy Generated Files to worktree
|
||||
Info "Copying review files to worktree..."
|
||||
$destReviewPath = Copy-IssueReviewToWorktree -IssueNumber $IssueNumber -SourceRepoRoot $SourceRepoRoot -WorktreePath $workingDir
|
||||
Info "Review files copied to: $destReviewPath"
|
||||
|
||||
# Copy .github/skills folder to worktree (needed for MCP config)
|
||||
$sourceSkillsPath = Join-Path $SourceRepoRoot '.github/skills'
|
||||
$destSkillsPath = Join-Path $workingDir '.github/skills'
|
||||
if (Test-Path $sourceSkillsPath) {
|
||||
$destGithubPath = Join-Path $workingDir '.github'
|
||||
if (-not (Test-Path $destGithubPath)) {
|
||||
New-Item -ItemType Directory -Path $destGithubPath -Force | Out-Null
|
||||
}
|
||||
Copy-Item -Path $sourceSkillsPath -Destination $destGithubPath -Recurse -Force
|
||||
Info "Copied .github/skills to worktree"
|
||||
}
|
||||
}
|
||||
|
||||
# Build the prompt for the fix agent
|
||||
$prompt = @"
|
||||
You are the FixIssue agent. Fix GitHub issue #$IssueNumber.
|
||||
|
||||
The implementation plan is at: Generated Files/issueReview/$IssueNumber/implementation-plan.md
|
||||
The overview is at: Generated Files/issueReview/$IssueNumber/overview.md
|
||||
|
||||
Follow the implementation plan exactly. Build and verify after each change.
|
||||
"@
|
||||
|
||||
# Start the fix agent
|
||||
Info "Starting fix agent for issue #$IssueNumber in $workingDir..."
|
||||
|
||||
# MCP config for github-artifacts tools (relative to repo root)
|
||||
$mcpConfig = '@.github/skills/issue-fix/references/mcp-config.json'
|
||||
|
||||
switch ($CLIType) {
|
||||
'copilot' {
|
||||
# GitHub Copilot CLI (standalone copilot command)
|
||||
# -p: Non-interactive prompt mode (exits after completion)
|
||||
# --yolo: Enable all permissions for automated execution
|
||||
# -s: Silent mode - output only agent response
|
||||
# --additional-mcp-config: Load github-artifacts MCP for image/attachment analysis
|
||||
$copilotArgs = @(
|
||||
'--additional-mcp-config', $mcpConfig,
|
||||
'-p', $prompt,
|
||||
'--yolo',
|
||||
'-s'
|
||||
)
|
||||
Info "Running: copilot $($copilotArgs -join ' ')"
|
||||
Push-Location $workingDir
|
||||
try {
|
||||
& copilot @copilotArgs
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Warn "Copilot exited with code $LASTEXITCODE"
|
||||
}
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
'claude' {
|
||||
$claudeArgs = @(
|
||||
'--print',
|
||||
'--dangerously-skip-permissions',
|
||||
'--prompt', $prompt
|
||||
)
|
||||
Start-Process -FilePath 'claude' -ArgumentList $claudeArgs -WorkingDirectory $workingDir -Wait -NoNewWindow
|
||||
}
|
||||
'gh-copilot' {
|
||||
# Use GitHub Copilot CLI via gh extension
|
||||
# gh copilot suggest requires interactive mode, so we open VS Code with the prompt
|
||||
Info "GitHub Copilot CLI detected. Opening VS Code with prompt..."
|
||||
|
||||
# Create a prompt file in the worktree for easy access
|
||||
$promptFile = Join-Path $workingDir "Generated Files/issueReview/$IssueNumber/fix-prompt.md"
|
||||
$promptContent = @"
|
||||
# Fix Issue #$IssueNumber
|
||||
|
||||
## Instructions
|
||||
|
||||
$prompt
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. Read the implementation plan: ``Generated Files/issueReview/$IssueNumber/implementation-plan.md``
|
||||
2. Read the overview: ``Generated Files/issueReview/$IssueNumber/overview.md``
|
||||
3. Follow the plan step by step
|
||||
4. Build and test after each change
|
||||
"@
|
||||
Set-Content -Path $promptFile -Value $promptContent -Force
|
||||
|
||||
# Open VS Code with the worktree
|
||||
code --new-window $workingDir --profile $VSCodeProfile
|
||||
Info "VS Code opened at $workingDir"
|
||||
Info "Prompt file created at: $promptFile"
|
||||
Info "Use GitHub Copilot in VS Code to implement the fix."
|
||||
}
|
||||
'vscode' {
|
||||
# Open VS Code and let user manually trigger the fix
|
||||
code --new-window $workingDir --profile $VSCodeProfile
|
||||
Info "VS Code opened at $workingDir. Use Copilot to implement the fix."
|
||||
}
|
||||
default {
|
||||
Warn "CLI type '$CLIType' not fully supported for auto-fix. Opening VS Code..."
|
||||
code --new-window $workingDir --profile $VSCodeProfile
|
||||
}
|
||||
}
|
||||
|
||||
# Check if any changes were actually made
|
||||
$hasChanges = $false
|
||||
Push-Location $workingDir
|
||||
try {
|
||||
$uncommitted = git status --porcelain 2>$null
|
||||
$commitsAhead = git rev-list main..HEAD --count 2>$null
|
||||
if ($uncommitted -or ($commitsAhead -gt 0)) {
|
||||
$hasChanges = $true
|
||||
}
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
return @{
|
||||
IssueNumber = $IssueNumber
|
||||
WorktreePath = $workingDir
|
||||
Success = $true
|
||||
ActionTaken = 'CodeFixAttempted'
|
||||
SkippedCodeFix = $false
|
||||
HasChanges = $hasChanges
|
||||
}
|
||||
}
|
||||
|
||||
#region Main Script
|
||||
try {
|
||||
Info "Repository root: $repoRoot"
|
||||
|
||||
# Detect or validate CLI
|
||||
if ($CLIType -eq 'auto') {
|
||||
$cli = Get-AvailableCLI
|
||||
if ($cli) {
|
||||
$CLIType = $cli.Type
|
||||
Info "Auto-detected CLI: $($cli.Name)"
|
||||
} else {
|
||||
$CLIType = 'vscode'
|
||||
Info "No CLI detected, will use VS Code"
|
||||
}
|
||||
}
|
||||
|
||||
# Find issues to fix
|
||||
$issuesToFix = @()
|
||||
|
||||
if ($IssueNumber) {
|
||||
# Single issue specified
|
||||
$reviewResult = Get-IssueReviewResult -IssueNumber $IssueNumber -RepoRoot $repoRoot
|
||||
if (-not $reviewResult.HasOverview -or -not $reviewResult.HasImplementationPlan) {
|
||||
throw "Issue #$IssueNumber does not have review files. Run Start-BulkIssueReview.ps1 first."
|
||||
}
|
||||
$issuesToFix += @{
|
||||
IssueNumber = $IssueNumber
|
||||
OverviewPath = $reviewResult.OverviewPath
|
||||
ImplementationPlanPath = $reviewResult.ImplementationPlanPath
|
||||
}
|
||||
} else {
|
||||
# Find high-confidence issues
|
||||
Info "`nSearching for high-confidence issues..."
|
||||
Info " Min Feasibility Score: $MinFeasibilityScore"
|
||||
Info " Min Clarity Score: $MinClarityScore"
|
||||
Info " Max Effort: $MaxEffortDays days"
|
||||
|
||||
$highConfidence = Get-HighConfidenceIssues `
|
||||
-RepoRoot $repoRoot `
|
||||
-MinFeasibilityScore $MinFeasibilityScore `
|
||||
-MinClarityScore $MinClarityScore `
|
||||
-MaxEffortDays $MaxEffortDays
|
||||
|
||||
if ($highConfidence.Count -eq 0) {
|
||||
Warn "No high-confidence issues found matching criteria."
|
||||
Info "Try lowering the score thresholds or increasing MaxEffortDays."
|
||||
return
|
||||
}
|
||||
|
||||
$issuesToFix = $highConfidence
|
||||
}
|
||||
|
||||
Info "`nIssues ready for auto-fix: $($issuesToFix.Count)"
|
||||
Info ("-" * 80)
|
||||
foreach ($issue in $issuesToFix) {
|
||||
$scores = ""
|
||||
if ($issue.FeasibilityScore) {
|
||||
$scores = " [Feasibility: $($issue.FeasibilityScore), Clarity: $($issue.ClarityScore), Effort: $($issue.EffortDays)d]"
|
||||
}
|
||||
Info ("#{0,-6}{1}" -f $issue.IssueNumber, $scores)
|
||||
}
|
||||
Info ("-" * 80)
|
||||
|
||||
# In DryRun mode, still analyze plans but don't take action
|
||||
if ($DryRun) {
|
||||
Info "`nAnalyzing implementation plans (dry run)..."
|
||||
foreach ($issue in $issuesToFix) {
|
||||
$implPlanPath = Join-Path (Get-IssueReviewPath -RepoRoot $repoRoot -IssueNumber $issue.IssueNumber) 'implementation-plan.md'
|
||||
if (Test-Path $implPlanPath) {
|
||||
$planStatus = Get-ImplementationPlanStatus -ImplementationPlanPath $implPlanPath
|
||||
$color = switch ($planStatus.Action) {
|
||||
'ImplementFix' { 'Green' }
|
||||
'CloseIssue' { 'Yellow' }
|
||||
'AddComment' { 'Cyan' }
|
||||
'LinkDuplicate' { 'Magenta' }
|
||||
default { 'Gray' }
|
||||
}
|
||||
Write-Host (" #{0,-6} [{1,-20}] -> {2}" -f $issue.IssueNumber, $planStatus.Status, $planStatus.Action) -ForegroundColor $color
|
||||
if ($planStatus.RelatedPR) {
|
||||
$prInfo = "PR #$($planStatus.RelatedPR)"
|
||||
if ($planStatus.ReleasedIn) {
|
||||
$prInfo += " (released in $($planStatus.ReleasedIn))"
|
||||
} elseif ($planStatus.Status -eq 'FixedButUnreleased') {
|
||||
$prInfo += " (merged, awaiting release)"
|
||||
}
|
||||
Write-Host " $prInfo" -ForegroundColor DarkGray
|
||||
}
|
||||
if ($planStatus.DuplicateOf) {
|
||||
Write-Host " Duplicate of #$($planStatus.DuplicateOf)" -ForegroundColor DarkGray
|
||||
}
|
||||
}
|
||||
}
|
||||
Warn "`nDry run mode - no actions taken."
|
||||
return
|
||||
}
|
||||
|
||||
# Confirm before proceeding (skip if -Force)
|
||||
if (-not $Force) {
|
||||
$confirm = Read-Host "`nProceed with fixing $($issuesToFix.Count) issues? (y/N)"
|
||||
if ($confirm -notmatch '^[yY]') {
|
||||
Info "Cancelled."
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
# Process issues
|
||||
$results = @{
|
||||
Succeeded = @()
|
||||
Failed = @()
|
||||
AlreadyResolved = @()
|
||||
AwaitingRelease = @()
|
||||
NeedsClarification = @()
|
||||
Duplicates = @()
|
||||
NoChanges = @()
|
||||
}
|
||||
|
||||
foreach ($issue in $issuesToFix) {
|
||||
try {
|
||||
Info "`n" + ("=" * 60)
|
||||
Info "PROCESSING ISSUE #$($issue.IssueNumber)"
|
||||
Info ("=" * 60)
|
||||
|
||||
$result = Start-IssueFixInWorktree `
|
||||
-IssueNumber $issue.IssueNumber `
|
||||
-SourceRepoRoot $repoRoot `
|
||||
-CLIType $CLIType `
|
||||
-VSCodeProfile $VSCodeProfile `
|
||||
-SkipWorktree:$SkipWorktree `
|
||||
-DryRun:$DryRun
|
||||
|
||||
if ($result.SkippedCodeFix) {
|
||||
# Action was taken but no code fix (e.g., closed issue, added comment)
|
||||
switch -Wildcard ($result.ActionTaken) {
|
||||
'*Closing*' { $results.AlreadyResolved += $issue.IssueNumber }
|
||||
'*clarification*' { $results.NeedsClarification += $issue.IssueNumber }
|
||||
'*duplicate*' { $results.Duplicates += $issue.IssueNumber }
|
||||
'*merged*awaiting*' { $results.AwaitingRelease += $issue.IssueNumber }
|
||||
'*merged but not yet released*' { $results.AwaitingRelease += $issue.IssueNumber }
|
||||
default { $results.Succeeded += $issue.IssueNumber }
|
||||
}
|
||||
Success "✓ Issue #$($issue.IssueNumber) handled: $($result.ActionTaken)"
|
||||
}
|
||||
elseif ($result.HasChanges) {
|
||||
$results.Succeeded += $issue.IssueNumber
|
||||
Success "✓ Issue #$($issue.IssueNumber) fix completed with changes"
|
||||
}
|
||||
else {
|
||||
$results.NoChanges += $issue.IssueNumber
|
||||
Warn "⚠ Issue #$($issue.IssueNumber) fix ran but no code changes were made"
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Err "✗ Issue #$($issue.IssueNumber) failed: $($_.Exception.Message)"
|
||||
$results.Failed += $issue.IssueNumber
|
||||
}
|
||||
}
|
||||
|
||||
# Summary
|
||||
Info "`n" + ("=" * 80)
|
||||
Info "AUTO-FIX COMPLETE"
|
||||
Info ("=" * 80)
|
||||
Info "Total issues: $($issuesToFix.Count)"
|
||||
if ($results.Succeeded.Count -gt 0) {
|
||||
Success "Code fixes: $($results.Succeeded.Count)"
|
||||
}
|
||||
if ($results.AlreadyResolved.Count -gt 0) {
|
||||
Success "Already resolved: $($results.AlreadyResolved.Count) (issues closed)"
|
||||
}
|
||||
if ($results.AwaitingRelease.Count -gt 0) {
|
||||
Info "Awaiting release: $($results.AwaitingRelease.Count) (fix merged, pending release)"
|
||||
}
|
||||
if ($results.NeedsClarification.Count -gt 0) {
|
||||
Warn "Need clarification: $($results.NeedsClarification.Count) (comments added)"
|
||||
}
|
||||
if ($results.Duplicates.Count -gt 0) {
|
||||
Warn "Duplicates: $($results.Duplicates.Count) (issues closed)"
|
||||
}
|
||||
if ($results.NoChanges.Count -gt 0) {
|
||||
Warn "No changes made: $($results.NoChanges.Count)"
|
||||
}
|
||||
if ($results.Failed.Count -gt 0) {
|
||||
Err "Failed: $($results.Failed.Count)"
|
||||
Err "Failed issues: $($results.Failed -join ', ')"
|
||||
}
|
||||
Info ("=" * 80)
|
||||
|
||||
if (-not $SkipWorktree -and ($results.Succeeded.Count -gt 0 -or $results.NoChanges.Count -gt 0)) {
|
||||
Info "`nWorktrees created. Use 'git worktree list' to see all worktrees."
|
||||
Info "To clean up: Delete-Worktree.ps1 -Branch issue/<number>"
|
||||
}
|
||||
|
||||
return $results
|
||||
}
|
||||
catch {
|
||||
Err "Error: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
#endregion
|
||||
21
.github/skills/issue-review/LICENSE.txt
vendored
Normal file
21
.github/skills/issue-review/LICENSE.txt
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
114
.github/skills/issue-review/SKILL.md
vendored
Normal file
114
.github/skills/issue-review/SKILL.md
vendored
Normal file
@@ -0,0 +1,114 @@
|
||||
---
|
||||
name: issue-review
|
||||
description: Analyze GitHub issues for feasibility and implementation planning. Use when asked to review an issue, analyze if an issue is fixable, evaluate issue complexity, create implementation plan for an issue, triage issues, assess technical feasibility, or estimate effort for an issue. Outputs structured analysis including feasibility score, clarity score, effort estimate, and detailed implementation plan.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# Issue Review Skill
|
||||
|
||||
Analyze GitHub issues to determine technical feasibility, requirement clarity, and create detailed implementation plans for PowerToys.
|
||||
|
||||
## Skill Contents
|
||||
|
||||
This skill is **self-contained** with all required resources:
|
||||
|
||||
```
|
||||
.github/skills/issue-review/
|
||||
├── SKILL.md # This file
|
||||
├── LICENSE.txt # MIT License
|
||||
├── scripts/
|
||||
│ ├── IssueReviewLib.ps1 # Shared library functions
|
||||
│ └── Start-BulkIssueReview.ps1 # Main review script
|
||||
└── references/
|
||||
└── review-issue.prompt.md # Full AI prompt template
|
||||
```
|
||||
|
||||
## Output Directory
|
||||
|
||||
All generated artifacts are placed under `Generated Files/issueReview/<issue-number>/` at the repository root (gitignored).
|
||||
|
||||
```
|
||||
Generated Files/issueReview/
|
||||
└── <issue-number>/
|
||||
├── overview.md # High-level assessment with scores
|
||||
├── implementation-plan.md # Detailed step-by-step fix plan
|
||||
└── _raw-issue.json # Cached issue data from GitHub
|
||||
```
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Review a specific GitHub issue for feasibility
|
||||
- Analyze whether an issue can be fixed by AI
|
||||
- Create an implementation plan for an issue
|
||||
- Triage issues by complexity and clarity
|
||||
- Estimate effort for fixing an issue
|
||||
- Evaluate technical requirements of an issue
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- GitHub CLI (`gh`) installed and authenticated
|
||||
- PowerShell 7+ for running scripts
|
||||
|
||||
## Required Variables
|
||||
|
||||
⚠️ **Before starting**, confirm `{{IssueNumber}}` with the user. If not provided, **ASK**: "What issue number should I review?"
|
||||
|
||||
| Variable | Description | Example |
|
||||
|----------|-------------|---------|
|
||||
| `{{IssueNumber}}` | GitHub issue number to analyze | `44044` |
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Run Issue Review
|
||||
|
||||
Execute the review script (use paths relative to this skill folder):
|
||||
|
||||
```powershell
|
||||
# From repo root
|
||||
.github/skills/issue-review/scripts/Start-BulkIssueReview.ps1 -IssueNumber {{IssueNumber}}
|
||||
```
|
||||
|
||||
This will:
|
||||
1. Fetch issue details from GitHub
|
||||
2. Analyze the codebase for relevant files
|
||||
3. Generate `overview.md` with feasibility assessment
|
||||
4. Generate `implementation-plan.md` with detailed steps
|
||||
|
||||
### Step 2: Review Output
|
||||
|
||||
Check the generated files at `Generated Files/issueReview/{{IssueNumber}}/`:
|
||||
|
||||
| File | Contains |
|
||||
|------|----------|
|
||||
| `overview.md` | Feasibility score (0-100), Clarity score (0-100), Effort estimate, Risk assessment |
|
||||
| `implementation-plan.md` | Step-by-step implementation with file paths, code snippets, test requirements |
|
||||
|
||||
### Step 3: Interpret Scores
|
||||
|
||||
| Score Range | Interpretation |
|
||||
|-------------|----------------|
|
||||
| 80-100 | High confidence - straightforward fix |
|
||||
| 60-79 | Medium confidence - some complexity |
|
||||
| 40-59 | Low confidence - significant challenges |
|
||||
| 0-39 | Very low - may need human intervention |
|
||||
|
||||
## Batch Review
|
||||
|
||||
To review multiple issues at once:
|
||||
|
||||
```powershell
|
||||
.github/skills/issue-review/scripts/Start-BulkIssueReview.ps1 -IssueNumbers 44044, 32950, 45029
|
||||
```
|
||||
|
||||
## AI Prompt Reference
|
||||
|
||||
For manual AI invocation, the full prompt is at:
|
||||
- `references/review-issue.prompt.md` (relative to this skill folder)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Solution |
|
||||
|---------|----------|
|
||||
| Issue not found | Verify issue number exists: `gh issue view {{IssueNumber}}` |
|
||||
| No implementation plan | Issue may be unclear - check `overview.md` for clarity score |
|
||||
| Script errors | Ensure you're in the PowerToys repo root |
|
||||
9
.github/skills/issue-review/references/mcp-config.json
vendored
Normal file
9
.github/skills/issue-review/references/mcp-config.json
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"github-artifacts": {
|
||||
"command": "cmd",
|
||||
"args": ["/c", "for /f %i in ('git rev-parse --show-toplevel') do node %i/tools/mcp/github-artifacts/launch.js"],
|
||||
"tools": ["*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
165
.github/skills/issue-review/references/review-issue.prompt.md
vendored
Normal file
165
.github/skills/issue-review/references/review-issue.prompt.md
vendored
Normal file
@@ -0,0 +1,165 @@
|
||||
---
|
||||
agent: 'agent'
|
||||
description: 'Review a GitHub issue, score it (0-100), and generate an implementation plan'
|
||||
---
|
||||
|
||||
# Review GitHub Issue
|
||||
|
||||
## Goal
|
||||
For **#{{issue_number}}** produce:
|
||||
1) `Generated Files/issueReview/{{issue_number}}/overview.md`
|
||||
2) `Generated Files/issueReview/{{issue_number}}/implementation-plan.md`
|
||||
|
||||
## Inputs
|
||||
Figure out required inputs {{issue_number}} from the invocation context; if anything is missing, ask for the value or note it as a gap.
|
||||
|
||||
# CONTEXT (brief)
|
||||
Ground evidence using `gh issue view {{issue_number}} --json number,title,body,author,createdAt,updatedAt,state,labels,milestone,reactions,comments,linkedPullRequests`, download images via MCP `github_issue_images` to better understand the issue context. Finally, use MCP `github_issue_attachments` to download logs with parameter `extractFolder` as `Generated Files/issueReview/{{issue_number}}/logs`, and analyze the downloaded logs if available to identify relevant issues. Locate the source code in the current workspace (use `rg`/`git grep` as needed). Link related issues and PRs.
|
||||
|
||||
## When to call MCP tools
|
||||
If the following MCP "github-artifacts" tools are available in the environment, use them:
|
||||
- `github_issue_images`: use when the issue/PR likely contains screenshots or other visual evidence (UI bugs, glitches, design problems).
|
||||
- `github_issue_attachments`: use when the issue/PR mentions attached ZIPs (PowerToysReport_*.zip, logs.zip, debug.zip) or asks to analyze logs/diagnostics. Always provide `extractFolder` as `Generated Files/issueReview/{{issue_number}}/logs`
|
||||
|
||||
If these tools are not available (not listed by the runtime), start the MCP server "github-artifacts" first.
|
||||
|
||||
# OVERVIEW.MD
|
||||
## Summary
|
||||
Issue, state, milestone, labels. **Signals**: 👍/❤️/👎, comment count, last activity, linked PRs.
|
||||
|
||||
## At-a-Glance Score Table
|
||||
Present all ratings in a compact table for quick scanning:
|
||||
|
||||
| Dimension | Score | Assessment | Key Drivers |
|
||||
|-----------|-------|------------|-------------|
|
||||
| **A) Business Importance** | X/100 | Low/Medium/High | Top 2 factors with scores |
|
||||
| **B) Community Excitement** | X/100 | Low/Medium/High | Top 2 factors with scores |
|
||||
| **C) Technical Feasibility** | X/100 | Low/Medium/High | Top 2 factors with scores |
|
||||
| **D) Requirement Clarity** | X/100 | Low/Medium/High | Top 2 factors with scores |
|
||||
| **Overall Priority** | X/100 | Low/Medium/High/Critical | Average or weighted summary |
|
||||
| **Effort Estimate** | X days (T-shirt) | XS/S/M/L/XL/XXL/Epic | Type: bug/feature/chore |
|
||||
| **Similar Issues Found** | X open, Y closed | — | Quick reference to related work |
|
||||
| **Potential Assignees** | @username, @username | — | Top contributors to module |
|
||||
|
||||
**Assessment bands**: 0-25 Low, 26-50 Medium, 51-75 High, 76-100 Critical
|
||||
|
||||
## Ratings (0–100) — add evidence & short rationale
|
||||
### A) Business Importance
|
||||
- Labels (priority/security/regression): **≤35**
|
||||
- Milestone/roadmap: **≤25**
|
||||
- Customer/contract impact: **≤20**
|
||||
- Unblocks/platform leverage: **≤20**
|
||||
### B) Community Excitement
|
||||
- 👍+❤️ normalized: **≤45**
|
||||
- Comment volume & unique participants: **≤25**
|
||||
- Recent activity (≤30d): **≤15**
|
||||
- Duplicates/related issues: **≤15**
|
||||
### C) Technical Feasibility
|
||||
- Contained surface/clear seams: **≤30**
|
||||
- Existing patterns/utilities: **≤25**
|
||||
- Risk (perf/sec/compat) manageable: **≤25**
|
||||
- Testability & CI support: **≤20**
|
||||
### D) Requirement Clarity
|
||||
- Behavior/repro/constraints: **≤60**
|
||||
- Non-functionals (perf/sec/i18n/a11y): **≤25**
|
||||
- Decision owners/acceptance signals: **≤15**
|
||||
|
||||
## Effort
|
||||
Days + **T-shirt** (XS 0.5–1d, S 1–2, M 2–4, L 4–7, XL 7–14, XXL 14–30, Epic >30).
|
||||
Type/level: bug/feature/chore/docs/refactor/test-only; severity/value tier.
|
||||
|
||||
## Suggested Actions
|
||||
Provide actionable recommendations for issue triage and assignment:
|
||||
|
||||
### A) Requirement Clarification (if Clarity score <50)
|
||||
**When Requirement Clarity (Dimension D) is Medium or Low:**
|
||||
- Identify specific gaps in issue description: missing repro steps, unclear expected behavior, undefined acceptance criteria, missing non-functional requirements
|
||||
- Draft 3-5 clarifying questions to post as issue comment
|
||||
- Suggest additional information needed: screenshots, logs, environment details, OS version, PowerToys version, error messages
|
||||
- If behavior is ambiguous, propose 2-3 interpretation scenarios and ask reporter to confirm
|
||||
- Example questions:
|
||||
- "Can you provide exact steps to reproduce this issue?"
|
||||
- "What is the expected behavior vs. what you're actually seeing?"
|
||||
- "Does this happen on Windows 10, 11, or both?"
|
||||
- "Can you attach a screenshot or screen recording?"
|
||||
|
||||
### B) Correct Label Suggestions
|
||||
- Analyze issue type, module, and severity to suggest missing or incorrect labels
|
||||
- Recommend labels from: `Issue-Bug`, `Issue-Feature`, `Issue-Docs`, `Issue-Task`, `Priority-High`, `Priority-Medium`, `Priority-Low`, `Needs-Triage`, `Needs-Author-Feedback`, `Product-<ModuleName>`, etc.
|
||||
- If Requirement Clarity is low (<50), add `Needs-Author-Feedback` label
|
||||
- If current labels are incorrect or incomplete, provide specific label changes with rationale
|
||||
|
||||
### C) Find Similar Issues & Past Fixes
|
||||
- Search for similar issues using `gh issue list --search "keywords" --state all --json number,title,state,closedAt`
|
||||
- Identify patterns: duplicate issues, related bugs, or similar feature requests
|
||||
- For closed issues, find linked PRs that fixed them: check `linkedPullRequests` in issue data
|
||||
- Provide 3-5 examples of similar issues with format: `#<number> - <title> (closed by PR #<pr>)` or `(still open)`
|
||||
|
||||
### D) Identify Subject Matter Experts
|
||||
- Use git blame/log to find who fixed similar issues in the past
|
||||
- Search for PR authors who touched relevant files: `git log --all --format='%aN' -- <file_paths> | sort | uniq -c | sort -rn | head -5`
|
||||
- Check issue/PR history for frequent contributors to the affected module
|
||||
- Suggest 2-3 potential assignees with context: `@<username> - <reason>` (e.g., "fixed similar rendering bug in #12345", "maintains FancyZones module")
|
||||
|
||||
### E) Semantic Search for Related Work
|
||||
- Use semantic_search tool to find similar issues, code patterns, or past discussions
|
||||
- Search queries should include: issue keywords, module names, error messages, feature descriptions
|
||||
- Cross-reference semantic results with GitHub issue search for comprehensive coverage
|
||||
|
||||
**Output format for Suggested Actions section in overview.md:**
|
||||
```markdown
|
||||
## Suggested Actions
|
||||
|
||||
### Clarifying Questions (if Clarity <50)
|
||||
Post these questions as issue comment to gather missing information:
|
||||
1. <question>
|
||||
2. <question>
|
||||
3. <question>
|
||||
|
||||
**Recommended label**: `Needs-Author-Feedback`
|
||||
|
||||
### Label Recommendations
|
||||
- Add: `<label>` - <reason>
|
||||
- Remove: `<label>` - <reason>
|
||||
- Current labels are appropriate ✓
|
||||
|
||||
### Similar Issues Found
|
||||
1. #<number> - <title> (<state>, closed by PR #<pr> on <date>)
|
||||
2. #<number> - <title> (<state>)
|
||||
...
|
||||
|
||||
### Potential Assignees
|
||||
- @<username> - <reason>
|
||||
- @<username> - <reason>
|
||||
|
||||
### Related Code/Discussions
|
||||
- <semantic search findings>
|
||||
```
|
||||
|
||||
# IMPLEMENTATION-PLAN.MD
|
||||
1) **Problem Framing** — restate problem; current vs expected; scope boundaries.
|
||||
2) **Layers & Files** — layers (UI/domain/data/infra/build). For each, list **files/dirs to modify** and **new files** (exact paths + why). Prefer repo patterns; cite examples/PRs.
|
||||
3) **Pattern Choices** — reuse existing; if new, justify trade-offs & transition.
|
||||
4) **Fundamentals** (brief plan or N/A + reason):
|
||||
- Performance (hot paths, allocs, caching/streaming)
|
||||
- Security (validation, authN/Z, secrets, SSRF/XSS/CSRF)
|
||||
- G11N/L10N (resources, number/date, pluralization)
|
||||
- Compatibility (public APIs, formats, OS/runtime/toolchain)
|
||||
- Extensibility (DI seams, options/flags, plugin points)
|
||||
- Accessibility (roles, labels, focus, keyboard, contrast)
|
||||
- SOLID & repo conventions (naming, folders, dependency direction)
|
||||
5) **Logging & Exception Handling**
|
||||
- Where to log; levels; structured fields; correlation/traces.
|
||||
- What to catch vs rethrow; retries/backoff; user-visible errors.
|
||||
- **Privacy**: never log secrets/PII; redaction policy.
|
||||
6) **Telemetry (optional — business metrics only)**
|
||||
- Events/metrics (name, when, props); success signal; privacy/sampling; dashboards/alerts.
|
||||
7) **Risks & Mitigations** — flags/canary/shadow-write/config guards.
|
||||
8) **Task Breakdown (agent-ready)** — table (leave a blank line before the header so Markdown renders correctly):
|
||||
|
||||
| Task | Intent | Files/Areas | Steps | Tests (brief) | Owner (Agent/Human) | Human interaction needed? (why) |
|
||||
|---|---|---|---|---|---|---|
|
||||
|
||||
9) **Tests to Add (only)**
|
||||
- **Unit**: targets, cases (success/edge/error), mocks/fixtures, path, notes.
|
||||
- **UI** (if applicable): flows, locator strategy, env/data/flags, path, flake mitigation.
|
||||
731
.github/skills/issue-review/scripts/IssueReviewLib.ps1
vendored
Normal file
731
.github/skills/issue-review/scripts/IssueReviewLib.ps1
vendored
Normal file
@@ -0,0 +1,731 @@
|
||||
# IssueReviewLib.ps1 - Shared helpers for bulk issue review automation
|
||||
# Part of the PowerToys GitHub Copilot/Claude Code issue review system
|
||||
|
||||
#region Console Output Helpers
|
||||
function Info { param([string]$Message) Write-Host $Message -ForegroundColor Cyan }
|
||||
function Warn { param([string]$Message) Write-Host $Message -ForegroundColor Yellow }
|
||||
function Err { param([string]$Message) Write-Host $Message -ForegroundColor Red }
|
||||
function Success { param([string]$Message) Write-Host $Message -ForegroundColor Green }
|
||||
#endregion
|
||||
|
||||
#region Repository Helpers
|
||||
function Get-RepoRoot {
|
||||
$root = git rev-parse --show-toplevel 2>$null
|
||||
if (-not $root) { throw 'Not inside a git repository.' }
|
||||
return (Resolve-Path $root).Path
|
||||
}
|
||||
|
||||
function Get-GeneratedFilesPath {
|
||||
param([string]$RepoRoot)
|
||||
return Join-Path $RepoRoot 'Generated Files'
|
||||
}
|
||||
|
||||
function Get-IssueReviewPath {
|
||||
param(
|
||||
[string]$RepoRoot,
|
||||
[int]$IssueNumber
|
||||
)
|
||||
$genFiles = Get-GeneratedFilesPath -RepoRoot $RepoRoot
|
||||
return Join-Path $genFiles "issueReview/$IssueNumber"
|
||||
}
|
||||
|
||||
function Get-IssueTitleFromOverview {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Extract issue title from existing overview.md file.
|
||||
.DESCRIPTION
|
||||
Parses the overview.md to get the issue title without requiring GitHub CLI.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$OverviewPath
|
||||
)
|
||||
|
||||
if (-not (Test-Path $OverviewPath)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$content = Get-Content $OverviewPath -Raw
|
||||
|
||||
# Try to match title from Summary table: | **Title** | <title> |
|
||||
if ($content -match '\*\*Title\*\*\s*\|\s*([^|]+)\s*\|') {
|
||||
return $Matches[1].Trim()
|
||||
}
|
||||
|
||||
# Try to match from header: # Issue #XXXX: <title>
|
||||
if ($content -match '# Issue #\d+[:\s]+(.+)$' ) {
|
||||
return $Matches[1].Trim()
|
||||
}
|
||||
|
||||
# Try to match: # Issue #XXXX Review: <title>
|
||||
if ($content -match '# Issue #\d+ Review[:\s]+(.+)$') {
|
||||
return $Matches[1].Trim()
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function Ensure-DirectoryExists {
|
||||
param([string]$Path)
|
||||
if (-not (Test-Path $Path)) {
|
||||
New-Item -ItemType Directory -Path $Path -Force | Out-Null
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region GitHub Issue Query Helpers
|
||||
function Get-GitHubIssues {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Query GitHub issues by label, state, and sort order.
|
||||
.PARAMETER Labels
|
||||
Comma-separated list of labels to filter by (e.g., "bug,help wanted").
|
||||
.PARAMETER State
|
||||
Issue state: open, closed, or all. Default: open.
|
||||
.PARAMETER Sort
|
||||
Sort field: created, updated, comments, reactions. Default: created.
|
||||
.PARAMETER Order
|
||||
Sort order: asc or desc. Default: desc.
|
||||
.PARAMETER Limit
|
||||
Maximum number of issues to return. Default: 100.
|
||||
.PARAMETER Repository
|
||||
Repository in owner/repo format. Default: microsoft/PowerToys.
|
||||
#>
|
||||
param(
|
||||
[string]$Labels,
|
||||
[ValidateSet('open', 'closed', 'all')]
|
||||
[string]$State = 'open',
|
||||
[ValidateSet('created', 'updated', 'comments', 'reactions')]
|
||||
[string]$Sort = 'created',
|
||||
[ValidateSet('asc', 'desc')]
|
||||
[string]$Order = 'desc',
|
||||
[int]$Limit = 100,
|
||||
[string]$Repository = 'microsoft/PowerToys'
|
||||
)
|
||||
|
||||
$ghArgs = @('issue', 'list', '--repo', $Repository, '--state', $State, '--limit', $Limit)
|
||||
|
||||
if ($Labels) {
|
||||
foreach ($label in ($Labels -split ',')) {
|
||||
$ghArgs += @('--label', $label.Trim())
|
||||
}
|
||||
}
|
||||
|
||||
# Build JSON fields (use reactionGroups instead of reactions)
|
||||
$jsonFields = 'number,title,state,labels,createdAt,updatedAt,author,reactionGroups,comments'
|
||||
$ghArgs += @('--json', $jsonFields)
|
||||
|
||||
Info "Querying issues: gh $($ghArgs -join ' ')"
|
||||
$result = & gh @ghArgs 2>&1
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Failed to query issues: $result"
|
||||
}
|
||||
|
||||
$issues = $result | ConvertFrom-Json
|
||||
|
||||
# Sort by reactions if requested (gh CLI doesn't support this natively)
|
||||
if ($Sort -eq 'reactions') {
|
||||
$issues = $issues | ForEach-Object {
|
||||
# reactionGroups is an array of {content, users} - sum up user counts
|
||||
$totalReactions = ($_.reactionGroups | ForEach-Object { $_.users.totalCount } | Measure-Object -Sum).Sum
|
||||
if (-not $totalReactions) { $totalReactions = 0 }
|
||||
$_ | Add-Member -NotePropertyName 'totalReactions' -NotePropertyValue $totalReactions -PassThru
|
||||
}
|
||||
if ($Order -eq 'desc') {
|
||||
$issues = $issues | Sort-Object -Property totalReactions -Descending
|
||||
} else {
|
||||
$issues = $issues | Sort-Object -Property totalReactions
|
||||
}
|
||||
}
|
||||
|
||||
return $issues
|
||||
}
|
||||
|
||||
function Get-IssueDetails {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Get detailed information about a specific issue.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$IssueNumber,
|
||||
[string]$Repository = 'microsoft/PowerToys'
|
||||
)
|
||||
|
||||
$jsonFields = 'number,title,body,state,labels,createdAt,updatedAt,author,reactions,comments,linkedPullRequests,milestone'
|
||||
$result = gh issue view $IssueNumber --repo $Repository --json $jsonFields 2>&1
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Failed to get issue #$IssueNumber`: $result"
|
||||
}
|
||||
|
||||
return $result | ConvertFrom-Json
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region CLI Detection and Execution
|
||||
function Get-AvailableCLI {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Detect which AI CLI is available: GitHub Copilot CLI or Claude Code.
|
||||
.OUTPUTS
|
||||
Returns object with: Name, Command, PromptArg
|
||||
#>
|
||||
|
||||
# Check for standalone GitHub Copilot CLI (copilot command)
|
||||
$copilotCLI = Get-Command 'copilot' -ErrorAction SilentlyContinue
|
||||
if ($copilotCLI) {
|
||||
return @{
|
||||
Name = 'GitHub Copilot CLI'
|
||||
Command = 'copilot'
|
||||
Args = @('-p') # Non-interactive prompt mode
|
||||
Type = 'copilot'
|
||||
}
|
||||
}
|
||||
|
||||
# Check for Claude Code CLI
|
||||
$claudeCode = Get-Command 'claude' -ErrorAction SilentlyContinue
|
||||
if ($claudeCode) {
|
||||
return @{
|
||||
Name = 'Claude Code CLI'
|
||||
Command = 'claude'
|
||||
Args = @()
|
||||
Type = 'claude'
|
||||
}
|
||||
}
|
||||
|
||||
# Check for GitHub Copilot CLI via gh extension
|
||||
$ghCopilot = Get-Command 'gh' -ErrorAction SilentlyContinue
|
||||
if ($ghCopilot) {
|
||||
$copilotCheck = gh extension list 2>&1 | Select-String -Pattern 'copilot'
|
||||
if ($copilotCheck) {
|
||||
return @{
|
||||
Name = 'GitHub Copilot CLI (gh extension)'
|
||||
Command = 'gh'
|
||||
Args = @('copilot', 'suggest')
|
||||
Type = 'gh-copilot'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Check for VS Code CLI with Copilot
|
||||
$code = Get-Command 'code' -ErrorAction SilentlyContinue
|
||||
if ($code) {
|
||||
return @{
|
||||
Name = 'VS Code (Copilot Chat)'
|
||||
Command = 'code'
|
||||
Args = @()
|
||||
Type = 'vscode'
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function Invoke-AIReview {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Invoke AI CLI to review a single issue.
|
||||
.PARAMETER IssueNumber
|
||||
The issue number to review.
|
||||
.PARAMETER RepoRoot
|
||||
Repository root path.
|
||||
.PARAMETER CLIType
|
||||
CLI type: 'claude', 'copilot', 'gh-copilot', or 'vscode'.
|
||||
.PARAMETER WorkingDirectory
|
||||
Working directory for the CLI command.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$IssueNumber,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RepoRoot,
|
||||
[ValidateSet('claude', 'copilot', 'gh-copilot', 'vscode')]
|
||||
[string]$CLIType = 'copilot',
|
||||
[string]$WorkingDirectory
|
||||
)
|
||||
|
||||
if (-not $WorkingDirectory) {
|
||||
$WorkingDirectory = $RepoRoot
|
||||
}
|
||||
|
||||
$promptFile = Join-Path $RepoRoot '.github/prompts/review-issue.prompt.md'
|
||||
if (-not (Test-Path $promptFile)) {
|
||||
throw "Prompt file not found: $promptFile"
|
||||
}
|
||||
|
||||
# Prepare the prompt with issue number substitution
|
||||
$promptContent = Get-Content $promptFile -Raw
|
||||
$promptContent = $promptContent -replace '\{\{issue_number\}\}', $IssueNumber
|
||||
|
||||
# Create temp prompt file
|
||||
$tempPromptDir = Join-Path $env:TEMP "issue-review-$IssueNumber"
|
||||
Ensure-DirectoryExists -Path $tempPromptDir
|
||||
$tempPromptFile = Join-Path $tempPromptDir "prompt.md"
|
||||
$promptContent | Set-Content -Path $tempPromptFile -Encoding UTF8
|
||||
|
||||
# Build the prompt text for CLI
|
||||
$promptText = "Review GitHub issue #$IssueNumber following the template in .github/prompts/review-issue.prompt.md. Generate overview.md and implementation-plan.md in 'Generated Files/issueReview/$IssueNumber/'"
|
||||
|
||||
switch ($CLIType) {
|
||||
'copilot' {
|
||||
# GitHub Copilot CLI (standalone copilot command)
|
||||
# Use --yolo for full permissions (--allow-all-tools --allow-all-paths --allow-all-urls)
|
||||
# Use -s (silent) for cleaner output in batch mode
|
||||
# Enable ALL GitHub MCP tools (issues, PRs, repos, etc.) + github-artifacts for images/attachments
|
||||
# MCP config path relative to repo root for github-artifacts tools
|
||||
$mcpConfig = '@.github/skills/issue-review/references/mcp-config.json'
|
||||
$args = @(
|
||||
'--additional-mcp-config', $mcpConfig, # Load github-artifacts MCP for image/attachment analysis
|
||||
'-p', $promptText, # Non-interactive prompt mode (exits after completion)
|
||||
'--yolo', # Enable all permissions for automated execution
|
||||
'-s', # Silent mode - output only agent response
|
||||
'--enable-all-github-mcp-tools', # Enable ALL GitHub MCP tools (issues, PRs, search, etc.)
|
||||
'--allow-tool', 'github-artifacts' # Also enable our custom github-artifacts MCP
|
||||
)
|
||||
|
||||
return @{
|
||||
Command = 'copilot'
|
||||
Arguments = $args
|
||||
WorkingDirectory = $WorkingDirectory
|
||||
IssueNumber = $IssueNumber
|
||||
}
|
||||
}
|
||||
'claude' {
|
||||
# Claude Code CLI
|
||||
$args = @(
|
||||
'--print', # Non-interactive mode
|
||||
'--dangerously-skip-permissions',
|
||||
'--prompt', $promptText
|
||||
)
|
||||
|
||||
return @{
|
||||
Command = 'claude'
|
||||
Arguments = $args
|
||||
WorkingDirectory = $WorkingDirectory
|
||||
IssueNumber = $IssueNumber
|
||||
}
|
||||
}
|
||||
'gh-copilot' {
|
||||
# GitHub Copilot CLI via gh
|
||||
$args = @(
|
||||
'copilot', 'suggest',
|
||||
'-t', 'shell',
|
||||
"Review GitHub issue #$IssueNumber and generate analysis files"
|
||||
)
|
||||
|
||||
return @{
|
||||
Command = 'gh'
|
||||
Arguments = $args
|
||||
WorkingDirectory = $WorkingDirectory
|
||||
IssueNumber = $IssueNumber
|
||||
}
|
||||
}
|
||||
'vscode' {
|
||||
# VS Code with Copilot - open with prompt
|
||||
$args = @(
|
||||
'--new-window',
|
||||
$WorkingDirectory,
|
||||
'--goto', $tempPromptFile
|
||||
)
|
||||
|
||||
return @{
|
||||
Command = 'code'
|
||||
Arguments = $args
|
||||
WorkingDirectory = $WorkingDirectory
|
||||
IssueNumber = $IssueNumber
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Parallel Job Management
|
||||
function Start-ParallelIssueReviews {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Start parallel issue reviews with throttling.
|
||||
.PARAMETER Issues
|
||||
Array of issue objects to review.
|
||||
.PARAMETER MaxParallel
|
||||
Maximum number of parallel jobs. Default: 20.
|
||||
.PARAMETER CLIType
|
||||
CLI type to use for reviews.
|
||||
.PARAMETER RepoRoot
|
||||
Repository root path.
|
||||
.PARAMETER TimeoutMinutes
|
||||
Timeout per issue in minutes. Default: 30.
|
||||
.PARAMETER MaxRetries
|
||||
Maximum number of retries for failed issues. Default: 2.
|
||||
.PARAMETER RetryDelaySeconds
|
||||
Delay between retries in seconds. Default: 10.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[array]$Issues,
|
||||
[int]$MaxParallel = 20,
|
||||
[ValidateSet('claude', 'copilot', 'gh-copilot', 'vscode')]
|
||||
[string]$CLIType = 'copilot',
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RepoRoot,
|
||||
[int]$TimeoutMinutes = 30,
|
||||
[int]$MaxRetries = 2,
|
||||
[int]$RetryDelaySeconds = 10
|
||||
)
|
||||
|
||||
$totalIssues = $Issues.Count
|
||||
$completed = 0
|
||||
$failed = @()
|
||||
$succeeded = @()
|
||||
$retryQueue = [System.Collections.Queue]::new()
|
||||
|
||||
Info "Starting parallel review of $totalIssues issues (max $MaxParallel concurrent, $MaxRetries retries)"
|
||||
|
||||
# Use PowerShell jobs for parallelization
|
||||
$jobs = @()
|
||||
$issueQueue = [System.Collections.Queue]::new($Issues)
|
||||
|
||||
while ($issueQueue.Count -gt 0 -or $jobs.Count -gt 0 -or $retryQueue.Count -gt 0) {
|
||||
# Process retry queue when main queue is empty
|
||||
if ($issueQueue.Count -eq 0 -and $retryQueue.Count -gt 0 -and $jobs.Count -lt $MaxParallel) {
|
||||
$retryItem = $retryQueue.Dequeue()
|
||||
Warn "🔄 Retrying issue #$($retryItem.IssueNumber) (attempt $($retryItem.Attempt + 1)/$($MaxRetries + 1))"
|
||||
Start-Sleep -Seconds $RetryDelaySeconds
|
||||
$issueQueue.Enqueue(@{ number = $retryItem.IssueNumber; _retryAttempt = $retryItem.Attempt + 1 })
|
||||
}
|
||||
|
||||
# Start new jobs up to MaxParallel
|
||||
while ($jobs.Count -lt $MaxParallel -and $issueQueue.Count -gt 0) {
|
||||
$issue = $issueQueue.Dequeue()
|
||||
$issueNum = $issue.number
|
||||
$retryAttempt = if ($issue._retryAttempt) { $issue._retryAttempt } else { 0 }
|
||||
|
||||
$attemptInfo = if ($retryAttempt -gt 0) { " (retry $retryAttempt)" } else { "" }
|
||||
Info "Starting review for issue #$issueNum$attemptInfo ($($totalIssues - $issueQueue.Count)/$totalIssues)"
|
||||
|
||||
$job = Start-Job -Name "Issue-$issueNum" -ScriptBlock {
|
||||
param($IssueNumber, $RepoRoot, $CLIType)
|
||||
|
||||
Set-Location $RepoRoot
|
||||
|
||||
# Import the library in the job context
|
||||
. "$RepoRoot/.github/review-tools/IssueReviewLib.ps1"
|
||||
|
||||
try {
|
||||
$reviewCmd = Invoke-AIReview -IssueNumber $IssueNumber -RepoRoot $RepoRoot -CLIType $CLIType
|
||||
|
||||
# Execute the command using invocation operator (works for .ps1 scripts and executables)
|
||||
Set-Location $reviewCmd.WorkingDirectory
|
||||
$argList = $reviewCmd.Arguments
|
||||
|
||||
# Capture both stdout and stderr for better error reporting
|
||||
$output = & $reviewCmd.Command @argList 2>&1
|
||||
$exitCode = $LASTEXITCODE
|
||||
|
||||
# Get last 20 lines of output for error context
|
||||
$outputLines = $output | Out-String
|
||||
$lastLines = ($outputLines -split "`n" | Select-Object -Last 20) -join "`n"
|
||||
|
||||
# Check if output files were created (success indicator)
|
||||
$overviewPath = Join-Path $RepoRoot "Generated Files/issueReview/$IssueNumber/overview.md"
|
||||
$implPlanPath = Join-Path $RepoRoot "Generated Files/issueReview/$IssueNumber/implementation-plan.md"
|
||||
$filesCreated = (Test-Path $overviewPath) -and (Test-Path $implPlanPath)
|
||||
|
||||
return @{
|
||||
IssueNumber = $IssueNumber
|
||||
Success = ($exitCode -eq 0) -or $filesCreated
|
||||
ExitCode = $exitCode
|
||||
FilesCreated = $filesCreated
|
||||
Output = $lastLines
|
||||
Error = if ($exitCode -ne 0 -and -not $filesCreated) { "Exit code: $exitCode`n$lastLines" } else { $null }
|
||||
}
|
||||
}
|
||||
catch {
|
||||
return @{
|
||||
IssueNumber = $IssueNumber
|
||||
Success = $false
|
||||
ExitCode = -1
|
||||
FilesCreated = $false
|
||||
Output = $null
|
||||
Error = $_.Exception.Message
|
||||
}
|
||||
}
|
||||
} -ArgumentList $issueNum, $RepoRoot, $CLIType
|
||||
|
||||
$jobs += @{
|
||||
Job = $job
|
||||
IssueNumber = $issueNum
|
||||
StartTime = Get-Date
|
||||
RetryAttempt = $retryAttempt
|
||||
}
|
||||
}
|
||||
|
||||
# Check for completed jobs
|
||||
$completedJobs = @()
|
||||
foreach ($jobInfo in $jobs) {
|
||||
$job = $jobInfo.Job
|
||||
$issueNum = $jobInfo.IssueNumber
|
||||
$startTime = $jobInfo.StartTime
|
||||
$retryAttempt = $jobInfo.RetryAttempt
|
||||
|
||||
if ($job.State -eq 'Completed') {
|
||||
$result = Receive-Job -Job $job
|
||||
Remove-Job -Job $job -Force
|
||||
|
||||
if ($result.Success) {
|
||||
Success "✓ Issue #$issueNum completed (files created: $($result.FilesCreated))"
|
||||
$succeeded += $issueNum
|
||||
$completed++
|
||||
} else {
|
||||
# Check if we should retry
|
||||
if ($retryAttempt -lt $MaxRetries) {
|
||||
$errorPreview = if ($result.Error) { ($result.Error -split "`n" | Select-Object -First 3) -join " | " } else { "Unknown error" }
|
||||
Warn "⚠ Issue #$issueNum failed (will retry): $errorPreview"
|
||||
$retryQueue.Enqueue(@{ IssueNumber = $issueNum; Attempt = $retryAttempt; LastError = $result.Error })
|
||||
} else {
|
||||
$errorMsg = if ($result.Error) { $result.Error } else { "Exit code: $($result.ExitCode)" }
|
||||
Err "✗ Issue #$issueNum failed after $($retryAttempt + 1) attempts:"
|
||||
Err " Error: $errorMsg"
|
||||
$failed += @{ IssueNumber = $issueNum; Error = $errorMsg; Attempts = $retryAttempt + 1 }
|
||||
$completed++
|
||||
}
|
||||
}
|
||||
$completedJobs += $jobInfo
|
||||
}
|
||||
elseif ($job.State -eq 'Failed') {
|
||||
$jobError = $job.ChildJobs[0].JobStateInfo.Reason.Message
|
||||
Remove-Job -Job $job -Force
|
||||
|
||||
if ($retryAttempt -lt $MaxRetries) {
|
||||
Warn "⚠ Issue #$issueNum job crashed (will retry): $jobError"
|
||||
$retryQueue.Enqueue(@{ IssueNumber = $issueNum; Attempt = $retryAttempt; LastError = $jobError })
|
||||
} else {
|
||||
Err "✗ Issue #$issueNum job failed after $($retryAttempt + 1) attempts: $jobError"
|
||||
$failed += @{ IssueNumber = $issueNum; Error = $jobError; Attempts = $retryAttempt + 1 }
|
||||
$completed++
|
||||
}
|
||||
$completedJobs += $jobInfo
|
||||
}
|
||||
elseif ((Get-Date) - $startTime -gt [TimeSpan]::FromMinutes($TimeoutMinutes)) {
|
||||
Stop-Job -Job $job -ErrorAction SilentlyContinue
|
||||
Remove-Job -Job $job -Force
|
||||
|
||||
if ($retryAttempt -lt $MaxRetries) {
|
||||
Warn "⏱ Issue #$issueNum timed out after $TimeoutMinutes min (will retry)"
|
||||
$retryQueue.Enqueue(@{ IssueNumber = $issueNum; Attempt = $retryAttempt; LastError = "Timeout after $TimeoutMinutes minutes" })
|
||||
} else {
|
||||
Err "⏱ Issue #$issueNum timed out after $($retryAttempt + 1) attempts"
|
||||
$failed += @{ IssueNumber = $issueNum; Error = "Timeout after $TimeoutMinutes minutes"; Attempts = $retryAttempt + 1 }
|
||||
$completed++
|
||||
}
|
||||
$completedJobs += $jobInfo
|
||||
}
|
||||
}
|
||||
|
||||
# Remove completed jobs from active list
|
||||
$jobs = $jobs | Where-Object { $_ -notin $completedJobs }
|
||||
|
||||
# Brief pause to avoid tight loop
|
||||
if ($jobs.Count -gt 0) {
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
}
|
||||
|
||||
# Extract just issue numbers for the failed list
|
||||
$failedNumbers = $failed | ForEach-Object { $_.IssueNumber }
|
||||
|
||||
return @{
|
||||
Total = $totalIssues
|
||||
Succeeded = $succeeded
|
||||
Failed = $failedNumbers
|
||||
FailedDetails = $failed
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Issue Review Results Helpers
|
||||
function Get-IssueReviewResult {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Check if an issue has been reviewed and get its results.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$IssueNumber,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RepoRoot
|
||||
)
|
||||
|
||||
$reviewPath = Get-IssueReviewPath -RepoRoot $RepoRoot -IssueNumber $IssueNumber
|
||||
|
||||
$result = @{
|
||||
IssueNumber = $IssueNumber
|
||||
Path = $reviewPath
|
||||
HasOverview = $false
|
||||
HasImplementationPlan = $false
|
||||
OverviewPath = $null
|
||||
ImplementationPlanPath = $null
|
||||
}
|
||||
|
||||
$overviewPath = Join-Path $reviewPath 'overview.md'
|
||||
$implPlanPath = Join-Path $reviewPath 'implementation-plan.md'
|
||||
|
||||
if (Test-Path $overviewPath) {
|
||||
$result.HasOverview = $true
|
||||
$result.OverviewPath = $overviewPath
|
||||
}
|
||||
|
||||
if (Test-Path $implPlanPath) {
|
||||
$result.HasImplementationPlan = $true
|
||||
$result.ImplementationPlanPath = $implPlanPath
|
||||
}
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
function Get-HighConfidenceIssues {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Find issues with high confidence for auto-fix based on review results.
|
||||
.PARAMETER RepoRoot
|
||||
Repository root path.
|
||||
.PARAMETER MinFeasibilityScore
|
||||
Minimum Technical Feasibility score (0-100). Default: 70.
|
||||
.PARAMETER MinClarityScore
|
||||
Minimum Requirement Clarity score (0-100). Default: 60.
|
||||
.PARAMETER MaxEffortDays
|
||||
Maximum effort estimate in days. Default: 2 (S = Small).
|
||||
.PARAMETER FilterIssueNumbers
|
||||
Optional array of issue numbers to filter to. If specified, only these issues are considered.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RepoRoot,
|
||||
[int]$MinFeasibilityScore = 70,
|
||||
[int]$MinClarityScore = 60,
|
||||
[int]$MaxEffortDays = 2,
|
||||
[int[]]$FilterIssueNumbers = @()
|
||||
)
|
||||
|
||||
$genFiles = Get-GeneratedFilesPath -RepoRoot $RepoRoot
|
||||
$reviewDir = Join-Path $genFiles 'issueReview'
|
||||
|
||||
if (-not (Test-Path $reviewDir)) {
|
||||
return @()
|
||||
}
|
||||
|
||||
$highConfidence = @()
|
||||
|
||||
Get-ChildItem -Path $reviewDir -Directory | ForEach-Object {
|
||||
$issueNum = [int]$_.Name
|
||||
|
||||
# Skip if filter is specified and this issue is not in the filter list
|
||||
if ($FilterIssueNumbers.Count -gt 0 -and $issueNum -notin $FilterIssueNumbers) {
|
||||
return
|
||||
}
|
||||
|
||||
$overviewPath = Join-Path $_.FullName 'overview.md'
|
||||
$implPlanPath = Join-Path $_.FullName 'implementation-plan.md'
|
||||
|
||||
if (-not (Test-Path $overviewPath) -or -not (Test-Path $implPlanPath)) {
|
||||
return
|
||||
}
|
||||
|
||||
# Parse overview.md to extract scores
|
||||
$overview = Get-Content $overviewPath -Raw
|
||||
|
||||
# Extract scores using regex (looking for score table or inline scores)
|
||||
$feasibility = 0
|
||||
$clarity = 0
|
||||
$effortDays = 999
|
||||
|
||||
# Try to extract from At-a-Glance Score Table
|
||||
if ($overview -match 'Technical Feasibility[^\d]*(\d+)/100') {
|
||||
$feasibility = [int]$Matches[1]
|
||||
}
|
||||
if ($overview -match 'Requirement Clarity[^\d]*(\d+)/100') {
|
||||
$clarity = [int]$Matches[1]
|
||||
}
|
||||
# Match effort formats like "0.5-1 day", "1-2 days", "2-3 days" - extract the upper bound
|
||||
if ($overview -match 'Effort Estimate[^|]*\|\s*[\d.]+(?:-(\d+))?\s*days?') {
|
||||
if ($Matches[1]) {
|
||||
$effortDays = [int]$Matches[1]
|
||||
} elseif ($overview -match 'Effort Estimate[^|]*\|\s*(\d+)\s*days?') {
|
||||
$effortDays = [int]$Matches[1]
|
||||
}
|
||||
}
|
||||
# Also check for XS/S sizing in the table (e.g., "| XS |" or "| S |" or "(XS)" or "(S)")
|
||||
if ($overview -match 'Effort Estimate[^|]*\|[^|]*\|\s*(XS|S)\b') {
|
||||
# XS = 1 day, S = 2 days
|
||||
if ($Matches[1] -eq 'XS') {
|
||||
$effortDays = 1
|
||||
} else {
|
||||
$effortDays = 2
|
||||
}
|
||||
} elseif ($overview -match 'Effort Estimate[^|]*\|[^|]*\(XS\)') {
|
||||
$effortDays = 1
|
||||
} elseif ($overview -match 'Effort Estimate[^|]*\|[^|]*\(S\)') {
|
||||
$effortDays = 2
|
||||
}
|
||||
|
||||
if ($feasibility -ge $MinFeasibilityScore -and
|
||||
$clarity -ge $MinClarityScore -and
|
||||
$effortDays -le $MaxEffortDays) {
|
||||
|
||||
$highConfidence += @{
|
||||
IssueNumber = $issueNum
|
||||
FeasibilityScore = $feasibility
|
||||
ClarityScore = $clarity
|
||||
EffortDays = $effortDays
|
||||
OverviewPath = $overviewPath
|
||||
ImplementationPlanPath = $implPlanPath
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $highConfidence | Sort-Object -Property FeasibilityScore -Descending
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Worktree Integration
|
||||
function Copy-IssueReviewToWorktree {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Copy the Generated Files for an issue to a worktree.
|
||||
.PARAMETER IssueNumber
|
||||
The issue number.
|
||||
.PARAMETER SourceRepoRoot
|
||||
Source repository root (main repo).
|
||||
.PARAMETER WorktreePath
|
||||
Destination worktree path.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$IssueNumber,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$SourceRepoRoot,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$WorktreePath
|
||||
)
|
||||
|
||||
$sourceReviewPath = Get-IssueReviewPath -RepoRoot $SourceRepoRoot -IssueNumber $IssueNumber
|
||||
$destReviewPath = Get-IssueReviewPath -RepoRoot $WorktreePath -IssueNumber $IssueNumber
|
||||
|
||||
if (-not (Test-Path $sourceReviewPath)) {
|
||||
throw "Issue review files not found at: $sourceReviewPath"
|
||||
}
|
||||
|
||||
Ensure-DirectoryExists -Path $destReviewPath
|
||||
|
||||
# Copy all files from the issue review folder
|
||||
Copy-Item -Path "$sourceReviewPath\*" -Destination $destReviewPath -Recurse -Force
|
||||
|
||||
Info "Copied issue review files to: $destReviewPath"
|
||||
|
||||
return $destReviewPath
|
||||
}
|
||||
#endregion
|
||||
|
||||
# Note: This script is dot-sourced, not imported as a module.
|
||||
# All functions above are available after: . "path/to/IssueReviewLib.ps1"
|
||||
238
.github/skills/issue-review/scripts/Start-BulkIssueReview.ps1
vendored
Normal file
238
.github/skills/issue-review/scripts/Start-BulkIssueReview.ps1
vendored
Normal file
@@ -0,0 +1,238 @@
|
||||
<#!
|
||||
.SYNOPSIS
|
||||
Bulk review GitHub issues using AI CLI (Claude Code or GitHub Copilot).
|
||||
|
||||
.DESCRIPTION
|
||||
Queries GitHub issues by labels, state, and sort order, then kicks off parallel
|
||||
AI-powered reviews for each issue. Results are stored in Generated Files/issueReview/<number>/.
|
||||
|
||||
.PARAMETER Labels
|
||||
Comma-separated list of labels to filter issues (e.g., "bug,help wanted").
|
||||
|
||||
.PARAMETER State
|
||||
Issue state: open, closed, or all. Default: open.
|
||||
|
||||
.PARAMETER Sort
|
||||
Sort field: created, updated, comments, reactions. Default: created.
|
||||
|
||||
.PARAMETER Order
|
||||
Sort order: asc or desc. Default: desc.
|
||||
|
||||
.PARAMETER Limit
|
||||
Maximum number of issues to process. Default: 100.
|
||||
|
||||
.PARAMETER MaxParallel
|
||||
Maximum parallel review jobs. Default: 20.
|
||||
|
||||
.PARAMETER CLIType
|
||||
AI CLI to use: claude, gh-copilot, or vscode. Auto-detected if not specified.
|
||||
|
||||
.PARAMETER DryRun
|
||||
List issues without starting reviews.
|
||||
|
||||
.PARAMETER SkipExisting
|
||||
Skip issues that already have review files.
|
||||
|
||||
.PARAMETER Repository
|
||||
Repository in owner/repo format. Default: microsoft/PowerToys.
|
||||
|
||||
.PARAMETER TimeoutMinutes
|
||||
Timeout per issue review in minutes. Default: 30.
|
||||
|
||||
.EXAMPLE
|
||||
# Review all open bugs sorted by reactions
|
||||
./Start-BulkIssueReview.ps1 -Labels "bug" -Sort reactions -Order desc
|
||||
|
||||
.EXAMPLE
|
||||
# Dry run to see which issues would be reviewed
|
||||
./Start-BulkIssueReview.ps1 -Labels "help wanted" -DryRun
|
||||
|
||||
.EXAMPLE
|
||||
# Review top 50 issues with Claude Code, max 10 parallel
|
||||
./Start-BulkIssueReview.ps1 -Labels "Issue-Bug" -Limit 50 -MaxParallel 10 -CLIType claude
|
||||
|
||||
.EXAMPLE
|
||||
# Skip already-reviewed issues
|
||||
./Start-BulkIssueReview.ps1 -Labels "Issue-Feature" -SkipExisting
|
||||
|
||||
.NOTES
|
||||
Requires: GitHub CLI (gh) authenticated, and either Claude Code CLI or VS Code with Copilot.
|
||||
Results: Generated Files/issueReview/<issue_number>/overview.md and implementation-plan.md
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Position = 0)]
|
||||
[string]$Labels,
|
||||
|
||||
[ValidateSet('open', 'closed', 'all')]
|
||||
[string]$State = 'open',
|
||||
|
||||
[ValidateSet('created', 'updated', 'comments', 'reactions')]
|
||||
[string]$Sort = 'created',
|
||||
|
||||
[ValidateSet('asc', 'desc')]
|
||||
[string]$Order = 'desc',
|
||||
|
||||
[int]$Limit = 1000,
|
||||
|
||||
[int]$MaxParallel = 20,
|
||||
|
||||
[ValidateSet('claude', 'copilot', 'gh-copilot', 'vscode', 'auto')]
|
||||
[string]$CLIType = 'auto',
|
||||
|
||||
[switch]$DryRun,
|
||||
|
||||
[switch]$SkipExisting,
|
||||
|
||||
[string]$Repository = 'microsoft/PowerToys',
|
||||
|
||||
[int]$TimeoutMinutes = 30,
|
||||
|
||||
[int]$MaxRetries = 2,
|
||||
|
||||
[int]$RetryDelaySeconds = 10,
|
||||
|
||||
[switch]$Force,
|
||||
|
||||
[switch]$Help
|
||||
)
|
||||
|
||||
# Load library
|
||||
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
. "$scriptDir/IssueReviewLib.ps1"
|
||||
|
||||
# Show help
|
||||
if ($Help) {
|
||||
Get-Help $MyInvocation.MyCommand.Path -Full
|
||||
return
|
||||
}
|
||||
|
||||
#region Main Script
|
||||
try {
|
||||
# Get repo root
|
||||
$repoRoot = Get-RepoRoot
|
||||
Info "Repository root: $repoRoot"
|
||||
|
||||
# Detect or validate CLI
|
||||
if ($CLIType -eq 'auto') {
|
||||
$cli = Get-AvailableCLI
|
||||
if (-not $cli) {
|
||||
throw "No AI CLI found. Please install Claude Code CLI or GitHub Copilot CLI extension."
|
||||
}
|
||||
$CLIType = $cli.Type
|
||||
Info "Auto-detected CLI: $($cli.Name)"
|
||||
}
|
||||
|
||||
# Query issues
|
||||
Info "`nQuerying issues with filters:"
|
||||
Info " Labels: $(if ($Labels) { $Labels } else { '(none)' })"
|
||||
Info " State: $State"
|
||||
Info " Sort: $Sort $Order"
|
||||
Info " Limit: $Limit"
|
||||
|
||||
$issues = Get-GitHubIssues -Labels $Labels -State $State -Sort $Sort -Order $Order -Limit $Limit -Repository $Repository
|
||||
|
||||
if ($issues.Count -eq 0) {
|
||||
Warn "No issues found matching the criteria."
|
||||
return
|
||||
}
|
||||
|
||||
Info "`nFound $($issues.Count) issues"
|
||||
|
||||
# Filter out existing reviews if requested
|
||||
if ($SkipExisting) {
|
||||
$originalCount = $issues.Count
|
||||
$issues = $issues | Where-Object {
|
||||
$result = Get-IssueReviewResult -IssueNumber $_.number -RepoRoot $repoRoot
|
||||
-not ($result.HasOverview -and $result.HasImplementationPlan)
|
||||
}
|
||||
$skipped = $originalCount - $issues.Count
|
||||
if ($skipped -gt 0) {
|
||||
Info "Skipping $skipped issues with existing reviews"
|
||||
}
|
||||
}
|
||||
|
||||
if ($issues.Count -eq 0) {
|
||||
Warn "All issues already have reviews. Nothing to do."
|
||||
return
|
||||
}
|
||||
|
||||
# Display issue list
|
||||
Info "`nIssues to review:"
|
||||
Info ("-" * 80)
|
||||
foreach ($issue in $issues) {
|
||||
$labels = ($issue.labels | ForEach-Object { $_.name }) -join ', '
|
||||
$reactions = if ($issue.reactions) { $issue.reactions.totalCount } else { 0 }
|
||||
Info ("#{0,-6} {1,-50} [👍{2}] [{3}]" -f $issue.number, ($issue.title.Substring(0, [Math]::Min(50, $issue.title.Length))), $reactions, $labels)
|
||||
}
|
||||
Info ("-" * 80)
|
||||
|
||||
if ($DryRun) {
|
||||
Warn "`nDry run mode - no reviews started."
|
||||
Info "Would review $($issues.Count) issues with CLI: $CLIType"
|
||||
return
|
||||
}
|
||||
|
||||
# Confirm before proceeding (skip if -Force)
|
||||
if (-not $Force) {
|
||||
$confirm = Read-Host "`nProceed with reviewing $($issues.Count) issues using $CLIType? (y/N)"
|
||||
if ($confirm -notmatch '^[yY]') {
|
||||
Info "Cancelled."
|
||||
return
|
||||
}
|
||||
} else {
|
||||
Info "`nProceeding with $($issues.Count) issues (Force mode)"
|
||||
}
|
||||
|
||||
# Create output directory
|
||||
$genFiles = Get-GeneratedFilesPath -RepoRoot $repoRoot
|
||||
Ensure-DirectoryExists -Path (Join-Path $genFiles 'issueReview')
|
||||
|
||||
# Start parallel reviews
|
||||
Info "`nStarting bulk review..."
|
||||
Info " Max retries: $MaxRetries (delay: ${RetryDelaySeconds}s)"
|
||||
$startTime = Get-Date
|
||||
|
||||
$results = Start-ParallelIssueReviews `
|
||||
-Issues $issues `
|
||||
-MaxParallel $MaxParallel `
|
||||
-CLIType $CLIType `
|
||||
-RepoRoot $repoRoot `
|
||||
-TimeoutMinutes $TimeoutMinutes `
|
||||
-MaxRetries $MaxRetries `
|
||||
-RetryDelaySeconds $RetryDelaySeconds
|
||||
|
||||
$duration = (Get-Date) - $startTime
|
||||
|
||||
# Summary
|
||||
Info "`n" + ("=" * 80)
|
||||
Info "BULK REVIEW COMPLETE"
|
||||
Info ("=" * 80)
|
||||
Info "Total issues: $($results.Total)"
|
||||
Success "Succeeded: $($results.Succeeded.Count)"
|
||||
if ($results.Failed.Count -gt 0) {
|
||||
Err "Failed: $($results.Failed.Count)"
|
||||
Err "Failed issues: $($results.Failed -join ', ')"
|
||||
Info ""
|
||||
Info "Failed Issue Details:"
|
||||
Info ("-" * 40)
|
||||
foreach ($failedItem in $results.FailedDetails) {
|
||||
Err " #$($failedItem.IssueNumber) (attempts: $($failedItem.Attempts)):"
|
||||
$errorLines = ($failedItem.Error -split "`n" | Select-Object -First 5) -join "`n "
|
||||
Err " $errorLines"
|
||||
}
|
||||
Info ("-" * 40)
|
||||
}
|
||||
Info "Duration: $($duration.ToString('hh\:mm\:ss'))"
|
||||
Info "Output: $genFiles/issueReview/"
|
||||
Info ("=" * 80)
|
||||
|
||||
# Return results for pipeline
|
||||
return $results
|
||||
}
|
||||
catch {
|
||||
Err "Error: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
#endregion
|
||||
21
.github/skills/issue-to-pr-cycle/LICENSE.txt
vendored
Normal file
21
.github/skills/issue-to-pr-cycle/LICENSE.txt
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
136
.github/skills/issue-to-pr-cycle/SKILL.md
vendored
Normal file
136
.github/skills/issue-to-pr-cycle/SKILL.md
vendored
Normal file
@@ -0,0 +1,136 @@
|
||||
---
|
||||
name: issue-to-pr-cycle
|
||||
description: End-to-end automation from issue analysis to PR creation and review. Use when asked to fix multiple issues automatically, run full issue cycle, batch process issues, automate issue resolution, create PRs for high-confidence issues, or process issues end-to-end. Orchestrates issue review, auto-fix, PR submission, and PR review in parallel batches.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# Issue-to-PR Full Cycle Skill
|
||||
|
||||
Orchestrate the complete workflow from issue analysis to PR creation and review. Processes multiple issues in parallel with configurable confidence thresholds.
|
||||
|
||||
## Skill Contents
|
||||
|
||||
This skill is **self-contained** with all required resources:
|
||||
|
||||
```
|
||||
.github/skills/issue-to-pr-cycle/
|
||||
├── SKILL.md # This file
|
||||
├── LICENSE.txt # MIT License
|
||||
└── scripts/
|
||||
└── Start-FullIssueCycle.ps1 # Main orchestration script
|
||||
```
|
||||
|
||||
**Note**: This skill orchestrates other skills via their PowerShell scripts:
|
||||
- `issue-review` skill scripts
|
||||
- `issue-fix` skill scripts
|
||||
- `submit-pr` skill scripts
|
||||
- `pr-review` skill scripts
|
||||
|
||||
## Output
|
||||
|
||||
The skill produces:
|
||||
1. Issue review files in `Generated Files/issueReview/<issue-number>/`
|
||||
2. Git worktrees with fixes at `Q:/PowerToys-xxxx/`
|
||||
3. Pull requests on GitHub
|
||||
4. PR review files in `Generated Files/prReview/<pr-number>/`
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Process multiple issues end-to-end automatically
|
||||
- Batch fix high-confidence issues
|
||||
- Run full automation cycle for triaged issues
|
||||
- Create PRs for multiple reviewed issues
|
||||
- Automate issue-to-PR workflow
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- GitHub CLI (`gh`) installed and authenticated
|
||||
- Copilot CLI or Claude CLI installed
|
||||
- PowerShell 7+ for running scripts
|
||||
- Issues already reviewed (have `Generated Files/issueReview/` data)
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Option 1: Dry Run First
|
||||
|
||||
See what would be processed without making changes:
|
||||
|
||||
```powershell
|
||||
# From repo root
|
||||
.github/skills/issue-to-pr-cycle/scripts/Start-FullIssueCycle.ps1 `
|
||||
-MinFeasibilityScore 70 `
|
||||
-MinClarityScore 70 `
|
||||
-MaxEffortDays 10 `
|
||||
-SkipExisting `
|
||||
-DryRun
|
||||
```
|
||||
|
||||
### Option 2: Run Full Cycle
|
||||
|
||||
Process all matching issues:
|
||||
|
||||
```powershell
|
||||
.github/skills/issue-to-pr-cycle/scripts/Start-FullIssueCycle.ps1 `
|
||||
-MinFeasibilityScore 70 `
|
||||
-MinClarityScore 70 `
|
||||
-MaxEffortDays 10 `
|
||||
-SkipExisting `
|
||||
-CLIType copilot `
|
||||
-Force
|
||||
```
|
||||
|
||||
## CLI Options
|
||||
|
||||
| Parameter | Description | Default |
|
||||
|-----------|-------------|---------|
|
||||
| `-MinFeasibilityScore` | Minimum technical feasibility score (0-100) | `70` |
|
||||
| `-MinClarityScore` | Minimum requirement clarity score (0-100) | `70` |
|
||||
| `-MaxEffortDays` | Maximum effort estimate in days | `10` |
|
||||
| `-ExcludeIssues` | Array of issue numbers to skip | `@()` |
|
||||
| `-SkipExisting` | Skip issues that already have PRs | `false` |
|
||||
| `-CLIType` | AI CLI to use: `copilot` or `claude` | `copilot` |
|
||||
| `-FixThrottleLimit` | Parallel limit for fix phase | `5` |
|
||||
| `-PRThrottleLimit` | Parallel limit for PR phase | `5` |
|
||||
| `-ReviewThrottleLimit` | Parallel limit for review phase | `3` |
|
||||
| `-DryRun` | Show what would be done | `false` |
|
||||
| `-Force` | Skip confirmation prompts | `false` |
|
||||
|
||||
## Workflow Phases
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ PHASE 1: Auto-Fix Issues (Parallel) │
|
||||
│ Uses: issue-fix skill scripts │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ PHASE 2: Submit PRs (Parallel) │
|
||||
│ Uses: submit-pr skill scripts │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ PHASE 3: Review PRs (Parallel) │
|
||||
│ Uses: pr-review skill scripts │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Related Skills
|
||||
|
||||
This skill orchestrates (via PowerShell, not skill-to-skill):
|
||||
|
||||
| Skill | Script Location | Purpose |
|
||||
|-------|-----------------|---------|
|
||||
| `issue-review` | `.github/skills/issue-review/scripts/` | Analyze issues |
|
||||
| `issue-fix` | `.github/skills/issue-fix/scripts/` | Create fixes |
|
||||
| `submit-pr` | `.github/skills/submit-pr/scripts/` | Create PRs |
|
||||
| `pr-review` | `.github/skills/pr-review/scripts/` | Review PRs |
|
||||
|
||||
You can use each skill independently for finer control.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Solution |
|
||||
|---------|----------|
|
||||
| No issues found | Lower score thresholds or run more issue reviews |
|
||||
| All issues skipped | Remove `-SkipExisting` or check for existing PRs |
|
||||
| Parallel failures | Reduce throttle limits |
|
||||
123
.github/skills/issue-to-pr-cycle/scripts/IssueReviewLib.ps1
vendored
Normal file
123
.github/skills/issue-to-pr-cycle/scripts/IssueReviewLib.ps1
vendored
Normal file
@@ -0,0 +1,123 @@
|
||||
# IssueReviewLib.ps1 - Helpers for full issue-to-PR cycle workflow
|
||||
# Part of the PowerToys GitHub Copilot/Claude Code issue review system
|
||||
# This is a trimmed version with only what issue-to-pr-cycle needs
|
||||
|
||||
#region Console Output Helpers
|
||||
function Info { param([string]$Message) Write-Host $Message -ForegroundColor Cyan }
|
||||
function Warn { param([string]$Message) Write-Host $Message -ForegroundColor Yellow }
|
||||
function Err { param([string]$Message) Write-Host $Message -ForegroundColor Red }
|
||||
function Success { param([string]$Message) Write-Host $Message -ForegroundColor Green }
|
||||
#endregion
|
||||
|
||||
#region Repository Helpers
|
||||
function Get-RepoRoot {
|
||||
$root = git rev-parse --show-toplevel 2>$null
|
||||
if (-not $root) { throw 'Not inside a git repository.' }
|
||||
return (Resolve-Path $root).Path
|
||||
}
|
||||
|
||||
function Get-GeneratedFilesPath {
|
||||
param([string]$RepoRoot)
|
||||
return Join-Path $RepoRoot 'Generated Files'
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Issue Review Results Helpers
|
||||
function Get-HighConfidenceIssues {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Find issues with high confidence for auto-fix based on review results.
|
||||
.PARAMETER RepoRoot
|
||||
Repository root path.
|
||||
.PARAMETER MinFeasibilityScore
|
||||
Minimum Technical Feasibility score (0-100). Default: 70.
|
||||
.PARAMETER MinClarityScore
|
||||
Minimum Requirement Clarity score (0-100). Default: 60.
|
||||
.PARAMETER MaxEffortDays
|
||||
Maximum effort estimate in days. Default: 2 (S = Small).
|
||||
.PARAMETER FilterIssueNumbers
|
||||
Optional array of issue numbers to filter to. If specified, only these issues are considered.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RepoRoot,
|
||||
[int]$MinFeasibilityScore = 70,
|
||||
[int]$MinClarityScore = 60,
|
||||
[int]$MaxEffortDays = 2,
|
||||
[int[]]$FilterIssueNumbers = @()
|
||||
)
|
||||
|
||||
$genFiles = Get-GeneratedFilesPath -RepoRoot $RepoRoot
|
||||
$reviewDir = Join-Path $genFiles 'issueReview'
|
||||
|
||||
if (-not (Test-Path $reviewDir)) {
|
||||
return @()
|
||||
}
|
||||
|
||||
$highConfidence = @()
|
||||
|
||||
Get-ChildItem -Path $reviewDir -Directory | ForEach-Object {
|
||||
$issueNum = [int]$_.Name
|
||||
|
||||
# Skip if filter is specified and this issue is not in the filter list
|
||||
if ($FilterIssueNumbers.Count -gt 0 -and $issueNum -notin $FilterIssueNumbers) {
|
||||
return
|
||||
}
|
||||
|
||||
$overviewPath = Join-Path $_.FullName 'overview.md'
|
||||
$implPlanPath = Join-Path $_.FullName 'implementation-plan.md'
|
||||
|
||||
if (-not (Test-Path $overviewPath) -or -not (Test-Path $implPlanPath)) {
|
||||
return
|
||||
}
|
||||
|
||||
# Parse overview.md to extract scores
|
||||
$overview = Get-Content $overviewPath -Raw
|
||||
|
||||
# Extract scores using regex (looking for score table or inline scores)
|
||||
$feasibility = 0
|
||||
$clarity = 0
|
||||
$effortDays = 999
|
||||
|
||||
# Try to extract from At-a-Glance Score Table
|
||||
if ($overview -match 'Technical Feasibility[^\d]*(\d+)/100') {
|
||||
$feasibility = [int]$Matches[1]
|
||||
}
|
||||
if ($overview -match 'Requirement Clarity[^\d]*(\d+)/100') {
|
||||
$clarity = [int]$Matches[1]
|
||||
}
|
||||
# Match effort formats like "0.5-1 day", "1-2 days", "2-3 days" - extract the upper bound
|
||||
if ($overview -match 'Effort Estimate[^|]*\|\s*[\d.]+(?:-(\d+))?\s*days?') {
|
||||
if ($Matches[1]) {
|
||||
$effortDays = [int]$Matches[1]
|
||||
} elseif ($overview -match 'Effort Estimate[^|]*\|\s*(\d+)\s*days?') {
|
||||
$effortDays = [int]$Matches[1]
|
||||
}
|
||||
}
|
||||
# Also check for XS/S sizing in the table
|
||||
if ($overview -match 'Effort Estimate[^|]*\|[^|]*\|\s*(XS|S)\b') {
|
||||
if ($Matches[1] -eq 'XS') { $effortDays = 1 } else { $effortDays = 2 }
|
||||
} elseif ($overview -match 'Effort Estimate[^|]*\|[^|]*\(XS\)') {
|
||||
$effortDays = 1
|
||||
} elseif ($overview -match 'Effort Estimate[^|]*\|[^|]*\(S\)') {
|
||||
$effortDays = 2
|
||||
}
|
||||
|
||||
if ($feasibility -ge $MinFeasibilityScore -and
|
||||
$clarity -ge $MinClarityScore -and
|
||||
$effortDays -le $MaxEffortDays) {
|
||||
|
||||
$highConfidence += @{
|
||||
IssueNumber = $issueNum
|
||||
FeasibilityScore = $feasibility
|
||||
ClarityScore = $clarity
|
||||
EffortDays = $effortDays
|
||||
OverviewPath = $overviewPath
|
||||
ImplementationPlanPath = $implPlanPath
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $highConfidence | Sort-Object -Property FeasibilityScore -Descending
|
||||
}
|
||||
#endregion
|
||||
478
.github/skills/issue-to-pr-cycle/scripts/Start-FullIssueCycle.ps1
vendored
Normal file
478
.github/skills/issue-to-pr-cycle/scripts/Start-FullIssueCycle.ps1
vendored
Normal file
@@ -0,0 +1,478 @@
|
||||
<#!
|
||||
.SYNOPSIS
|
||||
Run the complete issue-to-PR cycle: fix issues, create PRs, review, and fix comments.
|
||||
|
||||
.DESCRIPTION
|
||||
Orchestrates the full workflow:
|
||||
1. Find high-confidence issues matching criteria
|
||||
2. Create worktrees and run auto-fix for each issue
|
||||
3. Commit changes and create PRs
|
||||
4. Run PR review workflow (assign Copilot, review, fix comments)
|
||||
|
||||
.PARAMETER MinFeasibilityScore
|
||||
Minimum Technical Feasibility score. Default: 70.
|
||||
|
||||
.PARAMETER MinClarityScore
|
||||
Minimum Requirement Clarity score. Default: 70.
|
||||
|
||||
.PARAMETER MaxEffortDays
|
||||
Maximum effort in days. Default: 10.
|
||||
|
||||
.PARAMETER ExcludeIssues
|
||||
Array of issue numbers to exclude (already processed).
|
||||
|
||||
.PARAMETER CLIType
|
||||
AI CLI to use: copilot or claude. Default: copilot.
|
||||
|
||||
.PARAMETER DryRun
|
||||
Show what would be done without executing.
|
||||
|
||||
.PARAMETER SkipExisting
|
||||
Skip issues that already have worktrees or PRs.
|
||||
|
||||
.EXAMPLE
|
||||
./Start-FullIssueCycle.ps1 -MinFeasibilityScore 70 -MinClarityScore 70 -MaxEffortDays 10
|
||||
|
||||
.EXAMPLE
|
||||
./Start-FullIssueCycle.ps1 -ExcludeIssues 44044,45029,32950,35703,44480 -DryRun
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Labels = '',
|
||||
[int]$Limit = 500, # GitHub API max is 1000, default to 500 to get most issues
|
||||
[int]$MinFeasibilityScore = 70,
|
||||
[int]$MinClarityScore = 70,
|
||||
[int]$MaxEffortDays = 10,
|
||||
[int[]]$ExcludeIssues = @(),
|
||||
[ValidateSet('copilot', 'claude')]
|
||||
[string]$CLIType = 'copilot',
|
||||
[int]$FixThrottleLimit = 5,
|
||||
[int]$PRThrottleLimit = 5,
|
||||
[int]$ReviewThrottleLimit = 3,
|
||||
[switch]$DryRun,
|
||||
[switch]$SkipExisting,
|
||||
[switch]$SkipReview,
|
||||
[switch]$Force,
|
||||
[switch]$Help
|
||||
)
|
||||
|
||||
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$skillsDir = Split-Path -Parent (Split-Path -Parent $scriptDir) # .github/skills
|
||||
. (Join-Path $scriptDir 'IssueReviewLib.ps1')
|
||||
|
||||
# Paths to other skills' scripts
|
||||
$issueFixScript = Join-Path $skillsDir 'issue-fix/scripts/Start-IssueAutoFix.ps1'
|
||||
$submitPRScript = Join-Path $skillsDir 'submit-pr/scripts/Submit-IssueFixes.ps1'
|
||||
$prReviewScript = Join-Path $skillsDir 'pr-review/scripts/Start-PRReviewWorkflow.ps1'
|
||||
|
||||
$repoRoot = Get-RepoRoot
|
||||
$worktreeLib = Join-Path $repoRoot 'tools/build/WorktreeLib.ps1'
|
||||
if (Test-Path $worktreeLib) {
|
||||
. $worktreeLib
|
||||
}
|
||||
|
||||
if ($Help) {
|
||||
Get-Help $MyInvocation.MyCommand.Path -Full
|
||||
return
|
||||
}
|
||||
|
||||
#region Helper Functions
|
||||
function Get-ExistingIssuePRs {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Get ALL issues that already have PRs (open, closed, or merged) - checking GitHub directly.
|
||||
#>
|
||||
param(
|
||||
[int[]]$IssueNumbers
|
||||
)
|
||||
|
||||
$existingPRs = @{}
|
||||
|
||||
foreach ($issueNum in $IssueNumbers) {
|
||||
# Check if there's a PR that mentions this issue (any state: open, closed, merged)
|
||||
$prs = gh pr list --search "fixes #$issueNum OR closes #$issueNum OR resolves #$issueNum" --state all --json number,url,headRefName,state 2>$null | ConvertFrom-Json
|
||||
if ($prs -and $prs.Count -gt 0) {
|
||||
$existingPRs[$issueNum] = @{
|
||||
PRNumber = $prs[0].number
|
||||
PRUrl = $prs[0].url
|
||||
Branch = $prs[0].headRefName
|
||||
State = $prs[0].state
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
# Also check for branch pattern issue/<number>* (any state)
|
||||
$branchPrs = gh pr list --head "issue/$issueNum" --state all --json number,url,headRefName,state 2>$null | ConvertFrom-Json
|
||||
if (-not $branchPrs -or $branchPrs.Count -eq 0) {
|
||||
# Try with wildcard search via gh api
|
||||
$branchPrs = gh pr list --state all --json number,url,headRefName,state 2>$null | ConvertFrom-Json | Where-Object { $_.headRefName -like "issue/$issueNum*" }
|
||||
}
|
||||
if ($branchPrs -and $branchPrs.Count -gt 0) {
|
||||
$existingPRs[$issueNum] = @{
|
||||
PRNumber = $branchPrs[0].number
|
||||
PRUrl = $branchPrs[0].url
|
||||
Branch = $branchPrs[0].headRefName
|
||||
State = $branchPrs[0].state
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $existingPRs
|
||||
}
|
||||
|
||||
function Get-ExistingWorktrees {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Get issues that already have worktrees.
|
||||
#>
|
||||
$existingWorktrees = @{}
|
||||
$worktrees = Get-WorktreeEntries | Where-Object { $_.Branch -like 'issue/*' }
|
||||
|
||||
foreach ($wt in $worktrees) {
|
||||
if ($wt.Branch -match 'issue/(\d+)') {
|
||||
$issueNum = [int]$Matches[1]
|
||||
$existingWorktrees[$issueNum] = $wt.Path
|
||||
}
|
||||
}
|
||||
|
||||
return $existingWorktrees
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Main Script
|
||||
try {
|
||||
$startTime = Get-Date
|
||||
|
||||
Info "=" * 80
|
||||
Info "FULL ISSUE-TO-PR CYCLE"
|
||||
Info "=" * 80
|
||||
Info "Repository root: $repoRoot"
|
||||
Info "CLI type: $CLIType"
|
||||
if ($Labels) {
|
||||
Info "Labels filter: $Labels"
|
||||
}
|
||||
Info "Criteria: Feasibility >= $MinFeasibilityScore, Clarity >= $MinClarityScore, Effort <= $MaxEffortDays days"
|
||||
|
||||
# Step 0: Review issues first (if labels specified and not skipping review)
|
||||
if ($Labels -and -not $SkipReview) {
|
||||
Info "`n" + ("=" * 60)
|
||||
Info "STEP 0: Reviewing issues with label '$Labels'"
|
||||
Info ("=" * 60)
|
||||
|
||||
$reviewScript = Join-Path $scriptDir '../../issue-review/scripts/Start-BulkIssueReview.ps1'
|
||||
if (Test-Path $reviewScript) {
|
||||
$reviewArgs = @{
|
||||
Labels = $Labels
|
||||
Limit = $Limit
|
||||
CLIType = $CLIType
|
||||
Force = $Force
|
||||
}
|
||||
if ($DryRun) {
|
||||
Info "[DRY RUN] Would run: Start-BulkIssueReview.ps1 -Labels '$Labels' -Limit $Limit -CLIType $CLIType -Force"
|
||||
} else {
|
||||
Info "Running bulk issue review..."
|
||||
& $reviewScript @reviewArgs
|
||||
}
|
||||
} else {
|
||||
Warn "Review script not found at: $reviewScript"
|
||||
Warn "Proceeding with existing review data..."
|
||||
}
|
||||
}
|
||||
|
||||
# Step 1: Find high-confidence issues
|
||||
Info "`n" + ("=" * 60)
|
||||
Info "STEP 1: Finding high-confidence issues"
|
||||
Info ("=" * 60)
|
||||
|
||||
# If labels specified, get the list of issue numbers with that label first
|
||||
# This ensures we ONLY look at issues with the specified label, not all reviewed issues
|
||||
$filterIssueNumbers = @()
|
||||
if ($Labels) {
|
||||
Info "Fetching issues with label '$Labels' from GitHub..."
|
||||
$labeledIssues = gh issue list --repo microsoft/PowerToys --label "$Labels" --state open --limit $Limit --json number 2>$null | ConvertFrom-Json
|
||||
$filterIssueNumbers = @($labeledIssues | ForEach-Object { $_.number })
|
||||
Info "Found $($filterIssueNumbers.Count) issues with label '$Labels'"
|
||||
}
|
||||
|
||||
$highConfidence = Get-HighConfidenceIssues `
|
||||
-RepoRoot $repoRoot `
|
||||
-MinFeasibilityScore $MinFeasibilityScore `
|
||||
-MinClarityScore $MinClarityScore `
|
||||
-MaxEffortDays $MaxEffortDays `
|
||||
-FilterIssueNumbers $filterIssueNumbers
|
||||
|
||||
Info "Found $($highConfidence.Count) high-confidence issues matching criteria"
|
||||
|
||||
if ($highConfidence.Count -eq 0) {
|
||||
Warn "No issues found matching criteria."
|
||||
return
|
||||
}
|
||||
|
||||
# Get issue numbers for checking
|
||||
$issueNumbers = $highConfidence | ForEach-Object { $_.IssueNumber }
|
||||
|
||||
# Get existing PRs to skip (check GitHub directly)
|
||||
Info "Checking for existing PRs..."
|
||||
$existingPRs = Get-ExistingIssuePRs -IssueNumbers $issueNumbers
|
||||
Info "Found $($existingPRs.Count) issues with existing PRs"
|
||||
|
||||
# Filter out excluded issues and those with existing PRs
|
||||
$issuesToProcess = $highConfidence | Where-Object {
|
||||
$issueNum = $_.IssueNumber
|
||||
$excluded = $issueNum -in $ExcludeIssues
|
||||
$hasPR = $existingPRs.ContainsKey($issueNum)
|
||||
|
||||
if ($excluded) {
|
||||
Info " Excluding #$issueNum (in exclude list)"
|
||||
}
|
||||
if ($hasPR -and $SkipExisting) {
|
||||
$prState = $existingPRs[$issueNum].State
|
||||
Info " Skipping #$issueNum (has $prState PR #$($existingPRs[$issueNum].PRNumber))"
|
||||
}
|
||||
|
||||
-not $excluded -and (-not $hasPR -or -not $SkipExisting)
|
||||
}
|
||||
|
||||
if ($issuesToProcess.Count -eq 0) {
|
||||
Warn "No new issues to process after filtering."
|
||||
return
|
||||
}
|
||||
|
||||
Info "`nIssues to process: $($issuesToProcess.Count)"
|
||||
Info ("-" * 80)
|
||||
foreach ($issue in $issuesToProcess) {
|
||||
$prInfo = if ($existingPRs.ContainsKey($issue.IssueNumber)) {
|
||||
$state = $existingPRs[$issue.IssueNumber].State
|
||||
" [has $state PR #$($existingPRs[$issue.IssueNumber].PRNumber)]"
|
||||
} else { "" }
|
||||
Info ("#{0,-6} [F:{1}, C:{2}, E:{3}d]{4}" -f $issue.IssueNumber, $issue.FeasibilityScore, $issue.ClarityScore, $issue.EffortDays, $prInfo)
|
||||
}
|
||||
Info ("-" * 80)
|
||||
|
||||
if ($DryRun) {
|
||||
Warn "`nDry run mode - showing what would be done:"
|
||||
Info " 1. Create worktrees for $($issuesToProcess.Count) issues (parallel)"
|
||||
Info " 2. Run Copilot auto-fix in each worktree (parallel)"
|
||||
Info " 3. Commit and create PRs (parallel)"
|
||||
Info " 4. Run PR review workflow (parallel)"
|
||||
return
|
||||
}
|
||||
|
||||
# Confirm
|
||||
if (-not $Force) {
|
||||
$confirm = Read-Host "`nProceed with full cycle for $($issuesToProcess.Count) issues? (y/N)"
|
||||
if ($confirm -notmatch '^[yY]') {
|
||||
Info "Cancelled."
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
# Track results
|
||||
$results = @{
|
||||
FixSucceeded = [System.Collections.Concurrent.ConcurrentBag[object]]::new()
|
||||
FixFailed = [System.Collections.Concurrent.ConcurrentBag[object]]::new()
|
||||
PRCreated = [System.Collections.Concurrent.ConcurrentBag[object]]::new()
|
||||
PRFailed = [System.Collections.Concurrent.ConcurrentBag[object]]::new()
|
||||
PRSkipped = [System.Collections.Concurrent.ConcurrentBag[object]]::new()
|
||||
ReviewSucceeded = [System.Collections.Concurrent.ConcurrentBag[object]]::new()
|
||||
ReviewFailed = [System.Collections.Concurrent.ConcurrentBag[object]]::new()
|
||||
}
|
||||
|
||||
# ========================================
|
||||
# PHASE 1: Create worktrees and fix issues (PARALLEL)
|
||||
# ========================================
|
||||
Info "`n" + ("=" * 60)
|
||||
Info "PHASE 1: Auto-Fix Issues (Parallel)"
|
||||
Info ("=" * 60)
|
||||
|
||||
$issuesNeedingFix = $issuesToProcess | Where-Object { -not $existingPRs.ContainsKey($_.IssueNumber) }
|
||||
$issuesWithPR = $issuesToProcess | Where-Object { $existingPRs.ContainsKey($_.IssueNumber) }
|
||||
|
||||
Info "Issues needing fix: $($issuesNeedingFix.Count)"
|
||||
Info "Issues with existing PR (skip to review): $($issuesWithPR.Count)"
|
||||
|
||||
if ($issuesNeedingFix.Count -gt 0) {
|
||||
$issuesNeedingFix | ForEach-Object -ThrottleLimit $FixThrottleLimit -Parallel {
|
||||
$issue = $_
|
||||
$issueNum = $issue.IssueNumber
|
||||
$issueFixScript = $using:issueFixScript
|
||||
$CLIType = $using:CLIType
|
||||
$results = $using:results
|
||||
|
||||
try {
|
||||
Write-Host "[Issue #$issueNum] Starting auto-fix..." -ForegroundColor Cyan
|
||||
& $issueFixScript -IssueNumber $issueNum -CLIType $CLIType -Force 2>&1 | Out-Null
|
||||
$results.FixSucceeded.Add($issueNum)
|
||||
Write-Host "[Issue #$issueNum] ✓ Fix completed" -ForegroundColor Green
|
||||
}
|
||||
catch {
|
||||
$results.FixFailed.Add(@{ IssueNumber = $issueNum; Error = $_.Exception.Message })
|
||||
Write-Host "[Issue #$issueNum] ✗ Fix failed: $($_.Exception.Message)" -ForegroundColor Red
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Info "`nPhase 1 complete: $($results.FixSucceeded.Count) succeeded, $($results.FixFailed.Count) failed"
|
||||
|
||||
# ========================================
|
||||
# PHASE 2: Commit and create PRs (PARALLEL)
|
||||
# ========================================
|
||||
Info "`n" + ("=" * 60)
|
||||
Info "PHASE 2: Submit PRs (Parallel)"
|
||||
Info ("=" * 60)
|
||||
|
||||
$fixedIssues = $results.FixSucceeded.ToArray()
|
||||
|
||||
if ($fixedIssues.Count -gt 0) {
|
||||
$fixedIssues | ForEach-Object -ThrottleLimit $PRThrottleLimit -Parallel {
|
||||
$issueNum = $_
|
||||
$submitPRScript = $using:submitPRScript
|
||||
$CLIType = $using:CLIType
|
||||
$results = $using:results
|
||||
|
||||
try {
|
||||
Write-Host "[Issue #$issueNum] Creating PR..." -ForegroundColor Cyan
|
||||
$submitResult = & $submitPRScript -IssueNumbers $issueNum -CLIType $CLIType -Force 2>&1
|
||||
|
||||
# Parse output to find PR URL
|
||||
$prUrl = $null
|
||||
$prNum = 0
|
||||
|
||||
if ($submitResult -match 'https://github.com/[^/]+/[^/]+/pull/(\d+)') {
|
||||
$prUrl = $Matches[0]
|
||||
$prNum = [int]$Matches[1]
|
||||
}
|
||||
|
||||
if ($prNum -gt 0) {
|
||||
$results.PRCreated.Add(@{ IssueNumber = $issueNum; PRNumber = $prNum; PRUrl = $prUrl })
|
||||
Write-Host "[Issue #$issueNum] ✓ PR #$prNum created" -ForegroundColor Green
|
||||
} else {
|
||||
# Check if PR was already created
|
||||
$existingPr = gh pr list --head "issue/$issueNum" --state open --json number,url 2>$null | ConvertFrom-Json
|
||||
if ($existingPr -and $existingPr.Count -gt 0) {
|
||||
$results.PRSkipped.Add(@{ IssueNumber = $issueNum; PRNumber = $existingPr[0].number; PRUrl = $existingPr[0].url; Reason = "Already exists" })
|
||||
Write-Host "[Issue #$issueNum] PR already exists: #$($existingPr[0].number)" -ForegroundColor Yellow
|
||||
} else {
|
||||
$results.PRFailed.Add(@{ IssueNumber = $issueNum; Error = "No PR created" })
|
||||
Write-Host "[Issue #$issueNum] ✗ PR creation failed" -ForegroundColor Red
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
$results.PRFailed.Add(@{ IssueNumber = $issueNum; Error = $_.Exception.Message })
|
||||
Write-Host "[Issue #$issueNum] ✗ PR failed: $($_.Exception.Message)" -ForegroundColor Red
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Info "`nPhase 2 complete: $($results.PRCreated.Count) created, $($results.PRSkipped.Count) skipped, $($results.PRFailed.Count) failed"
|
||||
|
||||
# ========================================
|
||||
# PHASE 3: Review PRs (PARALLEL)
|
||||
# ========================================
|
||||
Info "`n" + ("=" * 60)
|
||||
Info "PHASE 3: Review PRs (Parallel)"
|
||||
Info ("=" * 60)
|
||||
|
||||
# Collect all PRs to review (newly created + existing)
|
||||
$prsToReview = @()
|
||||
|
||||
foreach ($pr in $results.PRCreated.ToArray()) {
|
||||
$prsToReview += @{ IssueNumber = $pr.IssueNumber; PRNumber = $pr.PRNumber }
|
||||
}
|
||||
foreach ($pr in $results.PRSkipped.ToArray()) {
|
||||
$prsToReview += @{ IssueNumber = $pr.IssueNumber; PRNumber = $pr.PRNumber }
|
||||
}
|
||||
foreach ($issue in $issuesWithPR) {
|
||||
$prInfo = $existingPRs[$issue.IssueNumber]
|
||||
$prsToReview += @{ IssueNumber = $issue.IssueNumber; PRNumber = $prInfo.PRNumber }
|
||||
}
|
||||
|
||||
Info "PRs to review: $($prsToReview.Count)"
|
||||
|
||||
if ($prsToReview.Count -gt 0) {
|
||||
$prsToReview | ForEach-Object -ThrottleLimit $ReviewThrottleLimit -Parallel {
|
||||
$pr = $_
|
||||
$issueNum = $pr.IssueNumber
|
||||
$prNum = $pr.PRNumber
|
||||
$prReviewScript = $using:prReviewScript
|
||||
$CLIType = $using:CLIType
|
||||
$results = $using:results
|
||||
|
||||
try {
|
||||
Write-Host "[PR #$prNum] Starting review workflow..." -ForegroundColor Cyan
|
||||
& $prReviewScript -PRNumbers $prNum -CLIType $CLIType -Force 2>&1 | Out-Null
|
||||
$results.ReviewSucceeded.Add(@{ IssueNumber = $issueNum; PRNumber = $prNum })
|
||||
Write-Host "[PR #$prNum] ✓ Review completed" -ForegroundColor Green
|
||||
}
|
||||
catch {
|
||||
$results.ReviewFailed.Add(@{ IssueNumber = $issueNum; PRNumber = $prNum; Error = $_.Exception.Message })
|
||||
Write-Host "[PR #$prNum] ✗ Review failed: $($_.Exception.Message)" -ForegroundColor Red
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Info "`nPhase 3 complete: $($results.ReviewSucceeded.Count) succeeded, $($results.ReviewFailed.Count) failed"
|
||||
|
||||
# Final Summary
|
||||
$duration = (Get-Date) - $startTime
|
||||
|
||||
Info "`n" + ("=" * 80)
|
||||
Info "FULL CYCLE COMPLETE"
|
||||
Info ("=" * 80)
|
||||
Info "Duration: $($duration.ToString('hh\:mm\:ss'))"
|
||||
Info ""
|
||||
Info "Issues processed: $($issuesToProcess.Count)"
|
||||
Success "Fixes succeeded: $($results.FixSucceeded.Count)"
|
||||
if ($results.FixFailed.Count -gt 0) {
|
||||
Err "Fixes failed: $($results.FixFailed.Count)"
|
||||
}
|
||||
Success "PRs created: $($results.PRCreated.Count)"
|
||||
if ($results.PRSkipped.Count -gt 0) {
|
||||
Warn "PRs skipped: $($results.PRSkipped.Count) (already existed)"
|
||||
}
|
||||
if ($results.PRFailed.Count -gt 0) {
|
||||
Err "PRs failed: $($results.PRFailed.Count)"
|
||||
}
|
||||
Success "Reviews completed: $($results.ReviewSucceeded.Count)"
|
||||
if ($results.ReviewFailed.Count -gt 0) {
|
||||
Err "Reviews failed: $($results.ReviewFailed.Count)"
|
||||
}
|
||||
|
||||
Info ""
|
||||
Info "Summary by issue:"
|
||||
foreach ($issue in $issuesToProcess) {
|
||||
$issueNum = $issue.IssueNumber
|
||||
$prInfo = $results.PRCreated.ToArray() | Where-Object { $_.IssueNumber -eq $issueNum } | Select-Object -First 1
|
||||
if (-not $prInfo) {
|
||||
$prInfo = $results.PRSkipped.ToArray() | Where-Object { $_.IssueNumber -eq $issueNum } | Select-Object -First 1
|
||||
}
|
||||
if (-not $prInfo -and $existingPRs.ContainsKey($issueNum)) {
|
||||
$prInfo = @{ PRNumber = $existingPRs[$issueNum].PRNumber }
|
||||
}
|
||||
|
||||
$prNum = if ($prInfo) { "PR #$($prInfo.PRNumber)" } else { "No PR" }
|
||||
$fixStatus = if ($results.FixSucceeded.ToArray() -contains $issueNum) { "✓" } elseif ($results.FixFailed.ToArray().IssueNumber -contains $issueNum) { "✗" } else { "-" }
|
||||
$reviewStatus = if ($results.ReviewSucceeded.ToArray().IssueNumber -contains $issueNum -or $results.ReviewSucceeded.ToArray().PRNumber -contains $prInfo.PRNumber) { "✓" } else { "-" }
|
||||
|
||||
Info (" Issue #{0,-6} [{1}Fix] [{2}Review] -> {3}" -f $issueNum, $fixStatus, $reviewStatus, $prNum)
|
||||
}
|
||||
|
||||
Info ("=" * 80)
|
||||
|
||||
return @{
|
||||
FixSucceeded = $results.FixSucceeded.ToArray()
|
||||
FixFailed = $results.FixFailed.ToArray()
|
||||
PRCreated = $results.PRCreated.ToArray()
|
||||
PRSkipped = $results.PRSkipped.ToArray()
|
||||
PRFailed = $results.PRFailed.ToArray()
|
||||
ReviewSucceeded = $results.ReviewSucceeded.ToArray()
|
||||
ReviewFailed = $results.ReviewFailed.ToArray()
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Err "Error: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
#endregion
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 Microsoft Corporation
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,302 +0,0 @@
|
||||
---
|
||||
name: powertoys-module-verification
|
||||
description: "Verify a single PowerToys module's release checklist items end-to-end. Drive each checkbox via UIA / Named Events / settings.json edits / clipboard inspection / GPO / SendInput. Output a structured PASS / FAIL / BLOCKED verdict per item with evidence (FAIL distinguishes product defects from stale/ambiguous checklist items). Combine standard winapp ui mechanics (see references/winapp-ui-testing.md) with PT-specific recipes and the helper .ps1 files shipped with this skill."
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
## When to use this skill
|
||||
|
||||
Use this skill when you need to **verify every checklist item for a single PowerToys module** for a release sign-off — e.g. "verify all 18 Color Picker items", "verify all 88 Command Palette items". Each item produces a PASS / FAIL / BLOCKED verdict with evidence (UIA enumeration, log line, settings.json diff, screenshot, etc.).
|
||||
|
||||
The **checklist to verify is supplied with the task** (the calling prompt points you at the module's checklist file). This skill is the *how* — the drive techniques, helpers, taxonomy, and reporting format — independent of any specific checklist.
|
||||
|
||||
## Required reads (in order)
|
||||
|
||||
1. **`references/winapp-ui-testing.md`** — the **prerequisite** UIA mechanics doc (winapp ui verbs, scripted batch testing, file pickers, accessibility audits, screenshots, click-vs-invoke, PostMessage, SendInput cb=40, stunted-UIA recovery, settings-mutation safety contract). **Read this first** — this skill assumes you know its content and only adds PT-specific extensions.
|
||||
2. **This `SKILL.md`** — the PT-specific playbook: the 3-bucket drive-technique selector (Step 2), classification taxonomy, critical pitfalls, helper-script catalog.
|
||||
3. **`references/modules/<module>.md` IF IT EXISTS** — per-module entry-paths, item-by-item recipes, common BLOCKED traps, fixture lists, source citations. **Always check `references/modules/` first.** If no profile exists, fall back to this SKILL.md and create one after you finish (template in `references/modules/README.md`).
|
||||
4. **`references/explorer-context-menu-flow.md` IF your module registers an Explorer right-click entry** (PowerRename, File Locksmith, Image Resizer, New+, Preview Pane, RegistryPreview) — shared synthetic-right-click + UIA-invoke + multi-file-selection flow + module-caption table. Helper: `scripts/pt-explorer-contextmenu.ps1`.
|
||||
5. **`references/pre-flight.md`** — pre-flight checks, bootstrap snippet, state-hygiene cleanup, final wrap-up, hard rules.
|
||||
6. **`references/reporting-format.md`** — per-item table template, top-of-report summary, step-table rules, anti-patterns, worked example.
|
||||
7. **`references/environment-setup.md`** — RDP/sleep/screensaver/session-attachment gotchas. Cite in BLK-ENV verdicts.
|
||||
8. **`references/release-checklist/<module>.md`** — the checklist for the module under test (one file per module; see `references/release-checklist/index.md` for the full list). Each item carries `[ADMIN: …]` + `[CLARITY: …]` metadata. **This file IS the set of items to verify.**
|
||||
|
||||
## Helper scripts shipped with this skill
|
||||
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
| `scripts/pt-shared-events.ps1` | `Invoke-PtSharedEvent`, `Test-PtSharedEvent`, `Get-PtSharedEventCatalog` — 56-entry friendly-name map for PT Named Events (CmdPal.Show, AOT.Pin, PowerLauncher.Invoke, LightSwitch.Toggle, ZoomIt.Draw, ...). The deterministic, foreground-free, UIPI-immune way to trigger a module. |
|
||||
| `scripts/pt-sendinput-chord.ps1` | `Send-PtChord`, `Wait-PtHotkeyAccepted` — last-resort SendInput hotkey injection with the cb=40 fix. Use only when the module has no Named Event and the hotkey itself is the test subject. |
|
||||
| `scripts/pt-foreground-guard.ps1` | `Test-PtForeground`, `Force-PtForeground`, `Assert-PtForegroundOrAbort` — guard helpers to ensure target window IS foreground before SendInput, so keys don't leak to caller's terminal. |
|
||||
| `scripts/pt-cmdpal-recycle.ps1` | `Reset-CmdPalAppX`, `Reset-CmdPalToHome`, `Test-CmdPalDegraded`, `Invoke-CmdPalQuery` — CmdPal-specific lifecycle (handles TextChanged-broken state, BackButton navigation, AppX recycle). |
|
||||
| `scripts/pt-admin-probe.ps1` | `Test-PtAdmin`, `Test-ProcessElevated`, `Test-PtRunnerAdmin` — TokenElevation probes to verify your session and the PT runner have the right elevation for the test. |
|
||||
| `scripts/pt-clipboard-diff.ps1` | `Get-PtClipboardFormats`, `Compare-PtClipboardFormatDiff`, `Set-PtClipboardRich` — multi-format clipboard inspection for Advanced Paste tests. |
|
||||
| `scripts/pt-explorer-com.ps1` | `Get-PtExplorerWindows`, `Open-PtExplorerAtPath`, `Select-PtExplorerFiles`, `Invoke-PtPeekWithExplorerSelection`, `Test-PtInteractiveDesktop` — drive Explorer via Shell COM to set up multi-file selections, then trigger Peek/FZ/PowerRename/Image Resizer/Workspaces via their hotkeys. **Use this for Peek L706-L709, L719-L720 and any test that needs an Explorer file selection.** |
|
||||
| `scripts/pt-explorer-contextmenu.ps1` | `Test-PtDesktopInteractive`, `Open-PtExplorerContextMenu`, `Invoke-PtContextMenuItem`, `Get-PtContextMenuItems` — open Win11's real context menu via synthetic right-click (with retry), then UIA-invoke a menu item by name. **Canonical user-flow path for File Locksmith / Image Resizer / PowerRename / New+ menu-presence + launch tests.** Needs an unlocked interactive desktop. See `references/explorer-context-menu-flow.md` for the full write-up, stability notes, and per-module captions. |
|
||||
| `scripts/pt-shell-verbs.ps1` | `Get-PtShellVerbs`, `Invoke-PtShellVerb`, `Reset-PtShellComCache` — enumerate + invoke CLASSIC HKCR shell verbs via Shell.Application COM. **NOT for PT context-menu modules on Win11** (PT registers via IExplorerCommand, not classic — use `pt-explorer-contextmenu.ps1` for those). Useful for non-PT verbs (Open/Edit/Send-to/third-party) and as a negative check that PT verbs are NOT classic-shadowed. |
|
||||
| `scripts/pt-state.ps1` | `Get-PtSettings`, `Get-PtModuleSettings`, `Get-CmdPalSettings`, `Get-PtRunnerLogTail`, `Test-PtModuleEnabled`, `Test-PtModuleProcess`, `Restart-PtRunner`, `Backup-PtModuleSettings`, `Restore-PtModuleSettings` — common state checks. |
|
||||
| `scripts/pt-nonelevated.ps1` | `Start-PtNonElevated`, `Invoke-PtNonElevatedCapture` — launch an exe at **Medium IL (non-elevated)** from an elevated agent shell via a one-shot `RunLevel Limited` scheduled task. Required for elevation-visibility tests (a non-elevated module must NOT see higher-integrity processes; e.g. File Locksmith L649/L650). Verify the result with `Test-ProcessElevated`. |
|
||||
|
||||
Dot-source them **all** at once in your bootstrap (the `Get-ChildItem` loop loads every helper — see **Step 1 — Bootstrap**):
|
||||
```powershell
|
||||
$skill = '<this skill folder>' # the folder containing SKILL.md, e.g. <PT-repo>\.github\skills\powertoys-module-verification
|
||||
Get-ChildItem "$skill\scripts" -Filter '*.ps1' | ForEach-Object { . $_.FullName }
|
||||
```
|
||||
|
||||
## Step 1 — Bootstrap
|
||||
|
||||
```powershell
|
||||
$module = 'AdvancedPaste' # or 'CmdPal', 'FZ', 'Peek', ...
|
||||
# Work out of %TEMP% during the run (keeps screenshots/scratch off OneDrive); move to the
|
||||
# sign-off archive at the very end (see Step 7).
|
||||
$workspace = "$env:TEMP\verify-$module-$(Get-Date -Format yyyyMMdd-HHmmss)"
|
||||
New-Item -ItemType Directory -Path $workspace, "$workspace\artifacts" -Force | Out-Null
|
||||
$report = "$workspace\verify-$module.md"
|
||||
|
||||
# Dot-source helpers
|
||||
$skill = '<this skill folder>' # set once at top of your script (the folder containing SKILL.md)
|
||||
Get-ChildItem "$skill\scripts" -Filter '*.ps1' | ForEach-Object { . $_.FullName }
|
||||
|
||||
# Verify environment
|
||||
"=== Environment ===" | Tee-Object $report -Append
|
||||
"IsAdmin: $(Test-PtAdmin)" | Tee-Object $report -Append
|
||||
$rn = Test-PtRunnerAdmin
|
||||
"PT runner: PID=$($rn.Pid) Elevated=$($rn.Elevated)" | Tee-Object $report -Append
|
||||
|
||||
# The checklist items to verify are supplied with the task (see the calling prompt).
|
||||
# Read that module's checklist file and iterate its items (see Step 6 — Verifier loop).
|
||||
```
|
||||
|
||||
## Step 2 — Drive techniques
|
||||
|
||||
Every checklist item boils down to ONE of three intents. **Pick the bucket from the verb in the item, then use the best technique inside it.** Stop at the first technique that works.
|
||||
|
||||
| Intent | Verb-cues in the checklist item | Bucket |
|
||||
|---|---|---|
|
||||
| Change a setting | "default is X", "setting persists", "is enabled/disabled by default", "value Y is accepted" | §2.A |
|
||||
| Interact with a UI element | "click X", "toggle X", "type into Y", "X button is visible", "selecting Z does W" | §2.B |
|
||||
| Trigger a module action | "pressing hotkey X opens Y", "module launches", "Z happens when invoked" | §2.C |
|
||||
|
||||
### §2.A — Change a setting (single technique)
|
||||
|
||||
Edit the JSON file the module reads, wait for the file-watcher debounce, assert, then restore from backup. Zero external tools.
|
||||
|
||||
```powershell
|
||||
$bk = Backup-PtModuleSettings -ModuleDir AdvancedPaste
|
||||
try {
|
||||
$j = Get-PtModuleSettings -ModuleDir AdvancedPaste
|
||||
$j.properties.IsAdvancedAIEnabled.value = $false
|
||||
$j | ConvertTo-Json -Depth 12 | Set-Content "$env:LOCALAPPDATA\Microsoft\PowerToys\AdvancedPaste\settings.json"
|
||||
Start-Sleep -Seconds 4 # debounce — runner re-reads via file-watcher
|
||||
# ... assertion ...
|
||||
} finally {
|
||||
Restore-PtModuleSettings -ModuleDir AdvancedPaste -BackupPath $bk
|
||||
}
|
||||
```
|
||||
|
||||
> For shell-extension modules (PowerRename, File Locksmith, Image Resizer, New+) edit the **module-owned** file under `%LOCALAPPDATA%\Microsoft\PowerToys\<Module>\`, then `Restart-PtRunner` (and on stubborn handlers, restart Explorer). See pitfall #18 below.
|
||||
>
|
||||
> If you need to flip the *enabled* bit for a whole module, debounce isn't enough — call `Restart-PtRunner` after the write.
|
||||
|
||||
### §2.B — Interact with a UI element (2 techniques, most-reliable first)
|
||||
|
||||
#### B1. UIA invoke / set-value — **always try first**
|
||||
```powershell
|
||||
winapp ui invoke 'SubmitButton' -a PowerToys.Settings
|
||||
winapp ui set-value 'QueryTextBox' '=2+3*4' -a PowerToys.PowerLauncher
|
||||
Start-Sleep -Milliseconds 600
|
||||
winapp ui inspect -a PowerToys.PowerLauncher --depth 7 -i 2>$null
|
||||
```
|
||||
Invoke goes through UIA InvokePattern COM IPC — no foreground steal, no UIPI. See references/winapp-ui-testing.md §CRITICAL — invoke vs click.
|
||||
|
||||
#### B2. PostMessage WM_KEYDOWN/CHAR — when UIA can't reach the target
|
||||
For elevated targets, AppX windows with stunted UIA trees, or keystrokes that UIA `set-value` can't dispatch (arrow-key ListView nav, Enter to commit). See references/winapp-ui-testing.md §CRITICAL — Keystroke input that bypasses UIPI (PostMessage). Esc is often filtered by WinUI 3 raw-input hook — use BackButton invoke instead.
|
||||
|
||||
### §2.C — Trigger a module action (2 techniques, most-reliable first)
|
||||
|
||||
| | C1 Named Event | C2 SendInput chord |
|
||||
|---|---|---|
|
||||
| **Proves** | The action fires (the path *downstream* of the hotkey). **Not** that the chord is bound. | The full path: real keys → runner hook → action. The **only** method that proves the chord binding itself. |
|
||||
| **Robustness** | Highest — no foreground, no input desktop, UIPI-immune; works headless / RDP-minimized. | Lowest — needs an attached input desktop (else `BLK-ENV`), steals foreground, can't inject OS-reserved chords (Win+L / Win+Tab). |
|
||||
| **Precondition** | Owning module process is running (the event only exists while it is). | Attached input desktop + foreground. |
|
||||
|
||||
**Pick by what the item asserts:** for "does action Y happen" use C1; for "pressing chord X triggers Y" or "the rebind takes effect", C1 is insufficient (it bypasses the chord) — use C2, or C1 *plus* a runner-log line proving the chord was accepted.
|
||||
|
||||
#### C1. Named Event signal — preferred
|
||||
```powershell
|
||||
Invoke-PtSharedEvent -Name 'CmdPal.Show' # opens CmdPal without keyboard
|
||||
Invoke-PtSharedEvent -Name 'AOT.Pin' # pins foreground window via AOT
|
||||
Invoke-PtSharedEvent -Name 'PowerLauncher.Invoke' # opens PT Run
|
||||
Invoke-PtSharedEvent -Name 'LightSwitch.Toggle' # toggles theme
|
||||
Get-PtSharedEventCatalog | Format-Table # full list
|
||||
```
|
||||
No synthetic input — it's a `SetEvent` on the kernel event the module waits on, the same downstream path the runner's hotkey handler signals. Verify the side effect via UIA (`winapp ui list-windows -a <module>`), a log line (`Get-PtRunnerLogTail`), or settings.json diff (`Get-PtModuleSettings`). The event only exists while the owning process runs, so `Test-PtSharedEvent` doubles as an "is the module alive" check.
|
||||
|
||||
#### C2. SendInput chord — last resort / chord-binding verification
|
||||
Real synthetic keys. Loud (steals foreground) and fragile, but the only way to prove the activation chord is actually bound. The runner's global keyboard hook catches the chord regardless of focus, so the precondition is just an **attached input desktop** (pitfall #13; on a detached desktop `SendInput` returns `ACCESS_DENIED` and the keys vanish → mark `BLK-ENV`).
|
||||
```powershell
|
||||
# Precondition: input desktop attached? 0 = detached → don't bother sending, mark BLK-ENV (pitfall #13)
|
||||
if ([PtFg]::GetForegroundWindow() -eq [IntPtr]::Zero) { throw 'No input desktop — BLK-ENV (pitfall #13)' }
|
||||
|
||||
Send-PtChord -Mods 0x5B,0x10 -Key 0x43 # Win+Shift+C → Color Picker (cb=40 fix is inside the helper)
|
||||
$line = Wait-PtHotkeyAccepted -ModuleHint 'Color' -TimeoutSec 3
|
||||
if (-not $line) { throw 'Runner did not log hotkey invocation' }
|
||||
```
|
||||
|
||||
> **Rare fallback — a module that uses its own `RegisterHotKey` and exposes no Named Event.** Post `WM_HOTKEY` (`0x312`) straight to its message window (find the HWND via `EnumWindows`+`GetClassName` through `Add-Type` — same P/Invoke pattern as `pt-foreground-guard.ps1`). **No current PT module needs this:** ZoomIt — the obvious candidate — also waits on Named Events (`ZoomIt.Zoom`, `ZoomIt.Draw`, …; source: `Zoomit.cpp` `CreateEventW(ZOOMIT_ZOOM_EVENT)`), so drive it with C1.
|
||||
|
||||
> **Different case — sending keys *into* a specific focused window** (e.g. a CmdPal alias like `=` / `<` / `>` that `winapp ui set-value` can't trigger because it bypasses TextChanged; see pitfalls #4 and #6). Here the keystrokes go to whatever currently has focus, so you must bring the target window foreground first:
|
||||
> ```powershell
|
||||
> Assert-PtForegroundOrAbort -AppId Microsoft.CmdPal.UI # -AppId = the window you're typing INTO
|
||||
> Send-PtChord -Key 0xBB # '=' (no modifiers) to trigger the calculator alias
|
||||
> ```
|
||||
> The `-AppId` is whatever window you're targeting — it's **not** CmdPal-specific. CmdPal is just the worst offender: its AppX foreground-lock drops focus after the first `SetForegroundWindow`, so without the guard the keys silently leak to your terminal.
|
||||
|
||||
> Verdict decisions (PASS if behavior matches spec; **FAIL** if the product is wrong *or* the checklist item is stale/ambiguous; BLOCKED if you couldn't run the check after ≥2 entry-paths) live in **Step 3 — Classification taxonomy** below. Don't put verdict logic in Step 2.
|
||||
|
||||
## Step 3 — Classification taxonomy
|
||||
|
||||
### Verdicts (assign exactly ONE per item)
|
||||
|
||||
| Verdict | Meaning |
|
||||
|---|---|
|
||||
| **PASS** | You drove/observed the behavior and it matched the spec. **A pass is a pass — there is no PASS sub-type.** Record *how* you verified in the item's **Category** field as free text, e.g. "full UIA flow + asserted popup", "settings.json round-trip", "runner-log line", "Shell COM / IExplorerCommand", "screenshot pixel-diff", "output matches fixture", "process spawn/exit", "module CLI", "admin GPO write". |
|
||||
| **FAIL** | The item is **red** — something is wrong and action is required. Treat the checklist as test code: a test fails because **the product is wrong** *or* **the test/checklist is wrong**. Record the **cause** in the **Category** field: <br>• **product** — behavior contradicts a valid spec → file a product bug (repro + expected-vs-actual + screenshot/log + build version). <br>• **checklist** — the item itself is broken: *stale* (feature was removed/deprecated — cite the source grep proving it's gone) or *ambiguous* (`[CLARITY: VAGUE-*]`, no definable pass/fail criterion — quote the original wording). Fix the checklist, not the product. |
|
||||
| **BLOCKED** | Couldn't run the check in this environment / with this toolset *after ≥2 entry-paths* — inconclusive, like a skipped test. **Not red against the product.** Tag exactly one concrete reason below. |
|
||||
|
||||
### BLOCKED reasons
|
||||
Different failure reasons stay distinct because each drives a different remediation.
|
||||
|
||||
| Reason | When |
|
||||
|---|---|
|
||||
| `BLK-ENV` | This specific shell can't drive it (non-interactive / Session 0, RDP-minimized, missing Explorer windows) but a normal interactive desktop CAN. Triggers a "re-run on an interactive desktop" recommendation. Cite `references/environment-setup.md`. |
|
||||
| `BLK-HARDWARE` | Needs hardware this session lacks — multi-monitor, 2 physical PCs (MWB), real camera / battery / game-mode, or live screen/device capture. State the specific shortfall in **Category**. |
|
||||
| `BLK-DRAG-REQUIRED` | Needs a real mouse-drag gesture; synthetic drag is insufficient (e.g. FancyZones snap). |
|
||||
| `BLK-DESTRUCTIVE` | Reboot, hibernate, install/uninstall, or mid-session AppX uninstall — would damage the run environment. |
|
||||
| `BLK-VISUAL-RENDER` | The thing to verify is a rendered surface UIA can't see — WinUI3 islands, WebView2, or Explorer-side context-menu rendering/localization. Needs pixel/OCR or a manual eyeball. |
|
||||
| `BLK-OVERLAY-INPUT-BLOCK` | Overlay both blocks input and excludes itself from capture (`BlockInput` + `WDA_EXCLUDEFROMCAPTURE`, e.g. ZoomIt draw mode) — can neither drive nor screenshot it. |
|
||||
| `BLK-EXTERNAL-APP` | Needs a 3rd-party tool, a real API key, or a system locale change. |
|
||||
|
||||
**Rule of thumb**: in your report, separate the two FAIL causes — *product* FAILs are bugs to file; *checklist* FAILs are items to rewrite or prune. `BLOCKED` is only for a concrete, named obstacle (cite it), never a substitute for effort. If a large share of a module's items are checklist-FAILs, the checklist needs an overhaul before re-verifying.
|
||||
|
||||
## Step 4 — Report format
|
||||
|
||||
**See `references/reporting-format.md` for the full template** (per-item table, summary, step-table rules, anti-patterns, worked example). Don't paraphrase; copy the templates literally. This includes a mandatory **§G Retrospective** — a self-reflection on the *run itself*: list every friction encountered (classified by source — `SKILL-UNCLEAR` / `WINAPP-TOOL-BUG` / `WINAPP-DOC-UNCLEAR` / `HELPER-FLAW` / `PT-PRODUCT` / `ENVIRONMENT` — with severity + minutes/attempts cost + a suggested fix), or write `Everything was smooth — no friction encountered.` if there was none. This is how the skill improves run over run, so don't skip it.
|
||||
|
||||
## Step 5 — State hygiene (CRITICAL)
|
||||
|
||||
**See `references/pre-flight.md` §State hygiene** for the backup/restore pattern and cleanup commands. Always wrap mutations in `try { ... } finally { Restore-* }`.
|
||||
|
||||
## Module-specific quick reference
|
||||
|
||||
**Look for `references/modules/<module>.md` FIRST.** Each per-module profile contains paths, entry-paths, item-by-item recipes, common BLOCKED traps, fixture lists, and source citations specific to that module.
|
||||
|
||||
Catalog: see `references/modules/README.md`. Currently authored: `peek.md`, `power-rename.md`, `file-locksmith.md`, `image-resizer.md`.
|
||||
|
||||
If your module has NO profile yet:
|
||||
1. Fall back to the generic drive-stack in §2 above.
|
||||
2. **For Explorer-context-menu modules** (PowerRename / File Locksmith / Image Resizer / New+ / Preview Pane / RegistryPreview): read **`references/explorer-context-menu-flow.md`** first — it has the synthetic-right-click + UIA-invoke pattern with stability rules and module-caption table. Per-module profiles cite it and only document module-specific quirks. The canonical helper is `scripts/pt-explorer-contextmenu.ps1`.
|
||||
3. After finishing the verification, **create the profile** using the template in `references/modules/README.md` so the next agent benefits from what you learned.
|
||||
|
||||
Quick one-liners for modules without dedicated profiles (will be moved to per-module files as they're authored):
|
||||
|
||||
- **Advanced Paste**: `Invoke-PtSharedEvent -Name 'AdvancedPaste.ShowUI'` + `Set-PtClipboardRich` + `Compare-PtClipboardFormatDiff` (see `scripts/pt-clipboard-diff.ps1`).
|
||||
- **Command Palette**: `Invoke-PtSharedEvent -Name 'CmdPal.Show'` + `Invoke-CmdPalQuery` (auto-handles degraded state via `scripts/pt-cmdpal-recycle.ps1`). Settings file via `Get-CmdPalSettings`.
|
||||
- **PowerToys Run**: `Invoke-PtSharedEvent -Name 'PowerLauncher.Invoke'` + `winapp ui set-value QueryTextBox`. Window has 2 HWNDs — filter by width ≥ 800.
|
||||
- **FancyZones**: `Invoke-PtSharedEvent -Name 'FancyZones.ToggleEditor'`. Snap-drag tests are usually `BLK-DRAG-REQUIRED`; settings verify via settings.json round-trip.
|
||||
- **Light Switch**: `Invoke-PtSharedEvent -Name 'LightSwitch.Toggle' | LightSwitch.Light | LightSwitch.Dark`. Verify via `HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize\AppsUseLightTheme`.
|
||||
- **Always on Top**: `Invoke-PtSharedEvent -Name 'AOT.Pin'`. Verify `WS_EX_TOPMOST` on pinned HWND.
|
||||
- **Hosts File Editor** (admin): `Invoke-PtSharedEvent -Name 'Hosts.Show' | Hosts.ShowAdmin`.
|
||||
- **GPO** (admin): write `HKLM:\Software\Policies\PowerToys` + `Restart-PtRunner` + `Get-PtRunnerLogTail -Pattern 'GPO sets'`. Cleanup: `Remove-Item HKLM:\Software\Policies\PowerToys -Recurse -Force`.
|
||||
- **Mouse Without Borders**: most items `BLK-HARDWARE` (need 2 physical PCs).
|
||||
- **ZoomIt**: most modes inside `BlockInput + WDA_EXCLUDEFROMCAPTURE` overlay → `BLK-OVERLAY-INPUT-BLOCK`. Mode triggers: `ZoomIt.Zoom`, `ZoomIt.Draw`, `ZoomIt.Break`, etc.
|
||||
- **Peek**: see `references/modules/peek.md` for the full recipe (CLI back-door + Shell.Application + Ctrl+Space).
|
||||
|
||||
## Step 6 — Verifier loop per checkbox
|
||||
|
||||
```
|
||||
For each item in module:
|
||||
1. Pick a bucket from the verb in the item (§2.A change a setting / §2.B interact with UI / §2.C trigger an action)
|
||||
2. Walk that bucket's techniques top-to-bottom; stop at the first one that drives the item
|
||||
3. Compare observed behavior to the spec:
|
||||
• matches the spec → PASS (note the method in Category)
|
||||
• product behaves wrong → FAIL, cause=product (repro + expected/actual + screenshot/log + build)
|
||||
4. Checklist item itself is broken — feature removed from source, or spec too ambiguous to judge → FAIL, cause=checklist (cite the source proof / quote the wording)
|
||||
5. Couldn't drive it after ≥2 entry-paths → BLOCKED with a concrete reason (§3)
|
||||
6. Record verdict + evidence + cleanup
|
||||
7. Next item
|
||||
```
|
||||
|
||||
When done, run state hygiene cleanup, write the report **including the §G retrospective**, archive the workspace (Step 7), and exit.
|
||||
|
||||
## Step 7 — Archive the workspace to the sign-off folder (do this LAST)
|
||||
|
||||
The live run works out of `%TEMP%`, but the **final deliverable must live in the module sign-off archive** so reports persist and sync via OneDrive:
|
||||
|
||||
```powershell
|
||||
# After the report is written AND the artifact-existence check passes:
|
||||
$signoff = "$env:OneDrive\PowerToys\Module-Signoff" # e.g. C:\Users\<you>\OneDrive - Microsoft\PowerToys\Module-Signoff
|
||||
New-Item -ItemType Directory -Path $signoff -Force | Out-Null
|
||||
$final = Join-Path $signoff (Split-Path $workspace -Leaf)
|
||||
Move-Item -Path $workspace -Destination $final -Force
|
||||
# Report uses RELATIVE artifacts/… paths, so all links stay valid after the move.
|
||||
Write-Host "Final report: $(Join-Path $final (Split-Path $report -Leaf))"
|
||||
```
|
||||
|
||||
Print the **moved** report path (under `…\PowerToys\Module-Signoff\`) as the last line — never the `%TEMP%` path.
|
||||
|
||||
## Invocation & placeholders
|
||||
|
||||
This skill auto-activates when you ask to verify a PowerToys module's checklist (e.g. "verify all Color Picker items"). **One module per run** — never chain multiple modules into one report. Resolve these placeholders for the module under test:
|
||||
|
||||
| Placeholder | Substitute with |
|
||||
|---|---|
|
||||
| `<Module>` | Exact display name, e.g. `Color Picker`, `Command Palette`, `PowerToys Run`, `FancyZones` (see `references/release-checklist/index.md`). |
|
||||
| `<module>` | Lowercase-kebab-case for file lookup, e.g. `color-picker`, `command-palette`, `power-rename` — used for BOTH `references/release-checklist/<module>.md` (checklist) and `references/modules/<module>.md` (profile, if any). |
|
||||
| `<ModuleDir>` | settings.json sub-dir under `%LOCALAPPDATA%\Microsoft\PowerToys\` (e.g. `AdvancedPaste`, `FancyZones`, `PowerToys Run` (with space)). |
|
||||
| `<N>` | Total item count for this module. |
|
||||
|
||||
**Execution order:** `references/pre-flight.md` → per item, the §2 drive-stack (this file) → `references/reporting-format.md` per-item table → Step 6 verifier loop → `references/pre-flight.md` §Final wrap-up → Step 7 archive → print the final report path.
|
||||
|
||||
## What NOT to do
|
||||
|
||||
- Do NOT chain multiple modules in one report — one module per run.
|
||||
- Do NOT mark an item BLOCKED without a concrete, named obstacle (see §3 and `references/pre-flight.md` §Hard rules).
|
||||
- Do NOT invent steps for a VAGUE checklist item — if the spec is too ambiguous to judge, that is FAIL (cause=checklist), not a guess.
|
||||
- All other rules (foreground guard, always restore mutated state, etc.) live in `references/pre-flight.md` §Hard rules — follow them.
|
||||
|
||||
## Critical pitfalls (PT-specific)
|
||||
|
||||
*Reference, not a sequential step — skim before you start and consult while driving. Numbered for cross-reference only.*
|
||||
|
||||
1. **PT runner does NOT auto-pickup edits to master `settings.json`** (top-level `enabled.<Module>` flags). Call `Restart-PtRunner`.
|
||||
2. **Each module's own `<Module>\settings.json` IS hot-reloaded** via per-module file watcher (~3s debounce). **EXCEPTION — shell-extension/context-menu modules do NOT read this file; see pitfall #18.**
|
||||
3. **PT Run setting key has a space**: `"PowerToys Run"` not `PowerToysRun`.
|
||||
4. **CmdPal AppX foreground from external CLI is unreliable** — Windows foreground-lock blocks `SetForegroundWindow` after the first call. SendInput keys silently leak to your terminal. **Always `Assert-PtForegroundOrAbort` before SendInput.**
|
||||
5. **CmdPal AppX enters TextChanged-broken state** every ~30 probes — `Test-CmdPalDegraded` + `Reset-CmdPalAppX` to recover.
|
||||
6. **CmdPal alias detection (`=`, `<`, `>`, `:`, `$`, `??`, `)`) requires real keystrokes** — `winapp ui set-value` bypasses TextChanged and the alias never fires. Use Send-PtChord + `Assert-PtForegroundOrAbort` for aliases; use set-value for plain queries.
|
||||
7. **CmdPal Esc handler is filtered** by WinUI 3 raw-input hook — use `winapp ui invoke BackButton` instead (see `Reset-CmdPalToHome`).
|
||||
8. **GPO HKLM vs HKCU**: HKLM wins when both are set with conflicting values.
|
||||
9. **HKLM `Software\Policies\PowerToys` writes require admin** — verify with `Test-PtAdmin`.
|
||||
10. **`Stop-Process` is policy-blocked in this session unless you pass `-Id <int>` literally**. Always inline the PID.
|
||||
11. **WinUI 3 islands are largely invisible to UIA** (QuickAccess flyout, RegistryPreview Monaco editor, Peek WebView2). For these, fall back to screenshot + OCR or settings.json diff.
|
||||
12. **OS-reserved chords (Win+L, Win+Tab)** are consumed by Windows before any hook and cannot be injected via SendInput at all.
|
||||
13. **RDP minimized = `SendInput` denied.** Even though `quser` shows the remote session State=Active, minimizing the mstsc client detaches the session's input desktop. `GetForegroundWindow()` returns 0; `SendInput` returns `ACCESS_DENIED (5)`; tests that need synthetic input fail. **Same applies to: closed mstsc with X (Disconnected), local PC sleep (RDP TCP drops), remote screensaver/workstation lock, remote machine sleep.** Run `scripts/pt-session-diagnose.ps1` in pre-flight to detect, and see `references/environment-setup.md` for the full per-scenario table + `powercfg` setup commands the user should run before starting the agent. The agent should call `Test-PtForeground` mid-run before each input-injection-dependent item; if it returns False, mark `BLK-ENV` with mitigation citation (an environment block — not a product FAIL).
|
||||
14. **`winapp ui` arg-order quirk**: `winapp ui inspect --depth N -w $hwnd` may intermittently fail to parse `--depth` as Int64 if `-w` precedes it. **Put `-w $hwnd` AFTER `--depth N`** or as the first arg before any flag. If you see "Cannot bind argument" or numeric parse errors, swap the order and retry.
|
||||
15. **`winapp ui list-windows` line wrapping**: when window titles or process names are long, output may wrap a single window's `HWND <id>: "<title>" ... (proc, PID N)` across multiple lines, breaking single-line regexes. Either pipe through `Out-String` and use a multi-line regex, or use `--json` (when supported) and parse structured output.
|
||||
16. **De-elevation: launching a NON-elevated (Medium IL) child from an elevated agent shell.** The drive-stack only covers gaining *more* privilege; some items need the opposite. From a High-IL shell you cannot `Start-Process` a Medium-IL child directly. Use `scripts/pt-nonelevated.ps1` (`Start-PtNonElevated` / `Invoke-PtNonElevatedCapture`) — a one-shot `RunLevel Limited` + `LogonType Interactive` scheduled task that lands on the user's desktop at their filtered token. Confirm with `Test-ProcessElevated`. Needed for elevation-visibility pairs (File Locksmith L649/L650: non-elevated FL must not see the elevated runner; elevated FL must).
|
||||
17. **Win11 packaged context menus are not observable without real Explorer.** Modern PT context-menu entries are packaged `IExplorerCommand`s (sparse MSIX, e.g. File Locksmith CLSID `{AAF1E27D-…}`). They are **NOT** enumerable via classic `Shell.Application … FolderItem.Verbs()` and **NOT** `CoCreate`-able from a non-Explorer host (`REGDB_E_CLASSNOTREGISTERED`). So "verify the entry appears / no longer appears" cannot be pixel-verified by API. Verify instead via the gate flag the entry's `GetState` reads (e.g. general `enabled.<Module>`) + a source citation that maps it to `ECS_HIDDEN`; treat the literal render as `BLK-VISUAL-RENDER` and recommend a 5-second manual right-click. (Disabling does NOT unregister the package — it stays `Status Ok`; the entry is hidden dynamically.)
|
||||
18. **Shell-extension modules read a module-OWNED settings file, NOT the PT-store `<Module>\settings.json`.** PowerRename, File Locksmith, Image Resizer, and New+ context-menu handlers and exes run *outside* the runner (hosted by Explorer / launched on demand) and cannot use the PT-Settings IPC. Each reads its **own** json in `%LOCALAPPDATA%\Microsoft\PowerToys\<Module>\` *at process/handler launch* (registry-migrated `CSettings`/`Settings` classes — `lib/Settings.cpp` `Load→ParseJson`). The PT-Settings UI writes the *PT-store* `settings.json` (the `bool_*`/`int_*` file `Get-PtModuleSettings` reads); the runner's module DLL syncs PT-store→module-store **only on a Settings-UI change event** — so the PT-store file can be **stale for days** and editing it has **no effect** on the running shell handler. **To drive a settings item on these modules, edit the module-owned file directly (drive-stack §2.A) and relaunch the module (or restart runner+Explorer for the menu handlers), then restore.**
|
||||
|
||||
**Pitfall #18 — module-owned files + their key style** (verified 2026-06-10 against `<PT-repo>\src`):
|
||||
|
||||
| Module | Module-owned file (under `…\PowerToys\<Module>\`) | Key style | PT-store `settings.json` keys (UI/`Get-PtModuleSettings`) |
|
||||
|---|---|---|---|
|
||||
| PowerRename | `power-rename-settings.json` (+ `power-rename-last-run-data.json`, `search-mru.json`, `replace-mru.json`) | `ShowIcon`, `ExtendedContextMenuOnly`, `PersistState`, `MRUEnabled`, `MaxMRUSize`, `UseBoostLib` | `bool_show_icon_on_menu`, `bool_show_extended_menu`, `bool_persist_input`, `bool_mru_enabled`, `int_max_mru_size`, `bool_use_boost_lib` |
|
||||
| File Locksmith | `file-locksmith-settings.json` | `ShowInExtendedContextMenu` | `bool_show_extended_context_menu` |
|
||||
| Image Resizer | `image-resizer-settings.json` | (resize sizes/encoder/etc.) | mirrored `imageresizer*` keys |
|
||||
| New+ | `NewPlus\settings.json` (sub-folder **`NewPlus`**, verified on disk + `constants.h` `powertoy_name=L"NewPlus"`) | `HideFileExtension`, `HideStartingDigits`, `TemplateLocation`, `ReplaceVariables`, `BuiltInNewHidePreference` | mirrored `newplus*` keys |
|
||||
|
||||
Confirm which file actually drives behavior with a quick A/B: edit the module-owned file → relaunch → observe; if behavior follows, that's the source of truth (PowerRename L394/L395/L396/L397/L409 were all driven this way).
|
||||
|
||||
If you find another gap during verification, update this skill (add a recipe) AND consider proposing the addition to references/winapp-ui-testing.md if it's generic enough.
|
||||
@@ -1,143 +0,0 @@
|
||||
# Environment setup for PowerToys verification
|
||||
|
||||
**Audience**: human user preparing a test machine before running a verification agent.
|
||||
**One-time** (per test session) — restore afterward.
|
||||
|
||||
## Why this matters
|
||||
|
||||
PowerToys release checklists test real user interactions: pressing hotkeys, dragging files, switching windows. Many tests use `SendInput` to inject keystrokes. Windows refuses `SendInput` when the calling session has **no attached input desktop** — and several common Windows states cause exactly that to happen:
|
||||
|
||||
- RDP client minimized
|
||||
- Workstation locked (screensaver kicked in, idle timeout)
|
||||
- Remote machine asleep
|
||||
- Local machine asleep (RDP TCP drops)
|
||||
|
||||
If any of these happens mid-verification, items that need synthetic input fail with `BLK-ENV` even though the feature itself works fine. This guide eliminates the env causes so the only BLOCKED verdicts you see are real test/framework limitations.
|
||||
|
||||
## Per-scenario reference table
|
||||
|
||||
| Scenario | Remote session State | `GetForegroundWindow()` | `SendInput` | Verdict for input-injection tests |
|
||||
|---|---|---|---|---|
|
||||
| mstsc window focused | Active | Real HWND | Works | ✅ Drivable |
|
||||
| mstsc visible but not focused (covered or alt-tabbed) | Active | Real HWND | Works | ✅ Drivable |
|
||||
| **mstsc MINIMIZED** | Active | **0** | **ACCESS_DENIED (5)** | ❌ BLK-ENV |
|
||||
| Local machine sleeps / RDP TCP drops | **Disconnected** | 0 | ACCESS_DENIED | ❌ BLK-ENV |
|
||||
| User closes mstsc with X (no signout) | **Disconnected** | 0 | ACCESS_DENIED | ❌ BLK-ENV |
|
||||
| Sign out from the remote | Session destroyed | — | — | ❌ Agent killed |
|
||||
| Remote machine sleeps | Suspended | — | — | ❌ Catastrophic — timing corruption |
|
||||
| Remote screensaver / auto-lock kicks in | Active but desktop locked | 0 | ACCESS_DENIED | ❌ BLK-ENV |
|
||||
| **2nd RDP login as the SAME user** (you reconnect from another client) | the OLD session flips to **Disconnected** | 0 (in the old session) | ACCESS_DENIED | ❌ BLK-ENV — your running test's session got taken over |
|
||||
|
||||
**Key insight**: "Active" in `quser` ≠ "can inject input". Always check `GetForegroundWindow()` first (the diagnostic script `scripts/pt-session-diagnose.ps1` does this).
|
||||
|
||||
## Can I verify two modules at once in two RDP sessions?
|
||||
|
||||
Short answer on a **client edition of Windows (Windows 10/11, ProductType=1)**: **no — not as the same user, and effectively not at all.** This was investigated live on this machine (Windows 11 Enterprise, build 26200, `fSingleSessionPerUser=1` default):
|
||||
|
||||
- **Two monitors ≠ two sessions.** A multi-monitor setup is **one** session spanning both screens — it shares a single input desktop, foreground window, and `SendInput` queue across the monitors. Monitor count has nothing to do with session count, so "I have two monitors" does not give you two sessions to run two modules in.
|
||||
- **Sessions are isolated** — each Windows session has its own input desktop, its own foreground window, and its own `SendInput` queue. So *typing in session B genuinely does NOT disturb session A's foreground or input.* Cross-session interference is **not** the problem (so if you somehow DID have two live sessions — Server/RDS — they could run in parallel without colliding).
|
||||
- **The real blocker is session takeover.** Client Windows allows only **one interactive (console/owning) session at a time**, and `fSingleSessionPerUser=1` (the default) means one user gets **one** session. When you open the *second* RDP connection (as the same user), Windows **disconnects the first session** — it flips to `Disconnected`, its input desktop detaches, `GetForegroundWindow()` → 0, and any in-flight UI test there fails with `ACCESS_DENIED` → BLK-ENV. It's not your *typing* that breaks the test; it's the act of logging in the second session that evicts the first.
|
||||
- A different *user* account doesn't rescue it either: client Windows still permits only one connected interactive session, so the second login still disconnects the first.
|
||||
- Therefore, on client Windows, **run modules serially in one session.** True concurrent multi-session needs Windows Server + the RDS (Remote Desktop Session Host) role; unofficial multi-session patches exist but are out of scope here.
|
||||
|
||||
> **Verdict on the common assumption "I can run two modules in two RDP sessions because I have two monitors":** the *conclusion* (can't run two at once on client Windows) is correct, but the *reasoning* is wrong on two counts — two monitors is still one session, and you can't get two simultaneously-Active sessions on client Windows at all (the 2nd login disconnects the 1st). The limit is "can't open a 2nd Active session", not "the two sessions fight each other".
|
||||
|
||||
**Practical guidance:** keep a single RDP session for the whole run; don't reconnect/relogin mid-run; if you must check something elsewhere, alt-tab inside the *same* session rather than opening a new RDP connection. To detect a takeover after the fact, `qwinsta` will show your former session as `Disconnected`.
|
||||
|
||||
## Pre-run setup checklist
|
||||
|
||||
Run these BEFORE starting the verification agent.
|
||||
|
||||
### On the test machine (the one being verified)
|
||||
|
||||
```powershell
|
||||
# Snapshot current power settings so you can restore after
|
||||
$bk = "$env:TEMP\powercfg-backup-$(Get-Date -f yyyyMMdd-HHmmss).txt"
|
||||
powercfg /query SCHEME_CURRENT SUB_SLEEP > $bk
|
||||
powercfg /query SCHEME_CURRENT SUB_VIDEO >> $bk
|
||||
"# Restore later with the values from $bk" | Set-Content "$bk.note"
|
||||
|
||||
# Disable sleep + display-off + hibernate (AC and battery)
|
||||
powercfg /change standby-timeout-ac 0
|
||||
powercfg /change standby-timeout-dc 0
|
||||
powercfg /change monitor-timeout-ac 0
|
||||
powercfg /change monitor-timeout-dc 0
|
||||
powercfg /change hibernate-timeout-ac 0
|
||||
powercfg /change hibernate-timeout-dc 0
|
||||
|
||||
# Disable screensaver
|
||||
Set-ItemProperty 'HKCU:\Control Panel\Desktop' -Name ScreenSaveActive -Value '0'
|
||||
Set-ItemProperty 'HKCU:\Control Panel\Desktop' -Name ScreenSaveTimeOut -Value '0'
|
||||
|
||||
# Disable workstation lock-on-idle (requires admin)
|
||||
# 0 = never lock. Restore your original value (commonly 600 = 10 min) afterward.
|
||||
$origLock = (Get-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System' -Name InactivityTimeoutSecs -EA SilentlyContinue).InactivityTimeoutSecs
|
||||
"$origLock" | Out-File "$bk.lock"
|
||||
Set-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System' -Name InactivityTimeoutSecs -Value 0 -EA SilentlyContinue
|
||||
|
||||
# Confirm
|
||||
powercfg /query SCHEME_CURRENT SUB_SLEEP | Select-String 'Power Setting GUID|Current AC Power Setting Index'
|
||||
```
|
||||
|
||||
### On the local machine (the one with the RDP client)
|
||||
|
||||
```powershell
|
||||
# Disable local sleep so RDP TCP stays alive
|
||||
powercfg /change standby-timeout-ac 0
|
||||
|
||||
# Practical habit: put mstsc on a monitor you're NOT actively working on.
|
||||
# Don't minimize. Alt-tab is fine; minimize is not.
|
||||
```
|
||||
|
||||
## Mid-run discipline
|
||||
|
||||
While the agent is running:
|
||||
- **Don't minimize mstsc.** Visible-but-unfocused is OK; minimized is not.
|
||||
- **Don't close mstsc with the X.** If you have to step away, fine — leave it open.
|
||||
- **Don't disconnect or reconnect RDP.** Stay continuously connected for the duration of the run.
|
||||
- **Don't sign out** on either end.
|
||||
- If you do step away and the screen locks (despite the setup above), reconnect/unlock and the agent's `Test-PtSessionStillInteractive` guard (if used) will resume; otherwise items mid-execution will be BLK-ENV.
|
||||
|
||||
## Post-run cleanup (restore)
|
||||
|
||||
```powershell
|
||||
# Restore the values you captured to $bk before starting
|
||||
# (e.g. typical defaults: standby 30min, monitor 15min, screensaver 600s, lock 600s)
|
||||
powercfg /change standby-timeout-ac 30
|
||||
powercfg /change standby-timeout-dc 15
|
||||
powercfg /change monitor-timeout-ac 15
|
||||
powercfg /change monitor-timeout-dc 10
|
||||
powercfg /change hibernate-timeout-ac 0 # often default
|
||||
|
||||
Set-ItemProperty 'HKCU:\Control Panel\Desktop' -Name ScreenSaveActive -Value '1'
|
||||
Set-ItemProperty 'HKCU:\Control Panel\Desktop' -Name ScreenSaveTimeOut -Value '600'
|
||||
|
||||
$origLock = Get-Content "$bk.lock" -EA SilentlyContinue
|
||||
if ($origLock) {
|
||||
Set-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System' `
|
||||
-Name InactivityTimeoutSecs -Value ([int]$origLock) -EA SilentlyContinue
|
||||
}
|
||||
```
|
||||
|
||||
(Values above are typical; adjust to your environment policy.)
|
||||
|
||||
## Diagnostic before you start
|
||||
|
||||
Run `scripts/pt-session-diagnose.ps1` from the agent shell. Expected output for a GO:
|
||||
|
||||
```
|
||||
PASS - this shell can drive interactive PowerToys tests.
|
||||
```
|
||||
|
||||
If it prints FAIL with a `psexec -i <consoleSession> -s pwsh.exe` hint, you're in a non-console session — relaunch the agent shell as suggested before starting verification.
|
||||
|
||||
## Why this isn't in the global SKILL.md
|
||||
|
||||
These are **human prep steps**, not agent instructions. The agent needs to *detect* a bad environment (via `Test-PtInteractiveDesktop` in pre-flight + `Test-PtSessionStillInteractive` mid-run); the user needs to *prevent* one. Different audiences, different docs.
|
||||
|
||||
## Related
|
||||
|
||||
- `scripts/pt-session-diagnose.ps1` — one-shot session diagnostic
|
||||
- `scripts/pt-foreground-guard.ps1` — `Test-PtForeground` / `Force-PtForeground` / `Assert-PtForegroundOrAbort` used by agent
|
||||
- `SKILL.md` pitfall #13 — short pointer to this doc
|
||||
- `references/pre-flight.md` pre-flight check #4 — agent reads this doc when it detects a bad env
|
||||
@@ -1,99 +0,0 @@
|
||||
# Explorer context-menu flow — driving PowerToys shell-menu modules end-to-end
|
||||
|
||||
**Audience**: agents verifying any PowerToys module whose entry point is the **Windows Explorer right-click context menu** — i.e. **File Locksmith, Image Resizer, PowerRename, New+ (NewPlus)**, and similar.
|
||||
|
||||
This is the *true user flow*: open Explorer → select file(s) → right-click → click the module's menu item. Use it when an item's assertion is specifically about the **context menu** (e.g. "the entry appears / no longer appears", "right-click → X launches the module on the selection"). For the module's *internal* behavior you can still prefer a faster back-door (CLI / `last-run.log` / Named Event) — see each module profile — but the menu presence/launch itself can only be observed this way.
|
||||
|
||||
Helper: `scripts/pt-explorer-contextmenu.ps1` (`Test-PtDesktopInteractive`, `Open-PtExplorerContextMenu`, `Invoke-PtContextMenuItem`, `Get-PtContextMenuItems`).
|
||||
|
||||
## Which approach first? (CLI / back-door vs synthetic menu)
|
||||
|
||||
**Pick the tool by what the item ASSERTS — not "always synthetic" or "always CLI".**
|
||||
|
||||
| The item asserts… | First approach | Why |
|
||||
|---|---|---|
|
||||
| **The menu itself** — entry *appears / no longer appears*, "right-click → select X", caption / localization of the entry | **Synthetic Explorer menu (this doc)** — the *only* valid observer | The CLI/back-door is **blind to the menu**: it runs even when the entry is correctly hidden, so it gives a false PASS (the L652 trap). If the desktop is locked → `BLK-ENV`; do **not** substitute the CLI. |
|
||||
| **Module behavior** — engine finds the lockers, images get resized, files get renamed (the menu is just the trigger) | **CLI / back-door** (`FileLocksmithCLI.exe`, `last-run.log`, Named Event, DSC) | Instant, deterministic, foreground-free, works on a locked desktop. Synthetic adds ~10s + foreground/retry fragility without changing the assertion. |
|
||||
|
||||
**Golden-path rule (do once per module):** run **one** full synthetic right-click → invoke-the-item → confirm-launch. That proves the menu→launch wiring is actually registered *and* validates that the fast back-door is behaviorally equivalent to the real menu (e.g. File Locksmith L641 `step-04/05` did exactly this). After that one golden run, trust the back-door for the remaining behavior items.
|
||||
|
||||
Net: for a context-menu module, **most items are behavior → CLI-first**; the **menu-presence/absence/launch/localization items → synthetic-first**; plus one golden-path synthetic launch.
|
||||
|
||||
## Is it stable?
|
||||
|
||||
**Yes — with the robust variant below.** Verified repeatedly on Win11 (2026-06-08) launching File Locksmith via a genuine right-click + menu click. Two rules make it reliable; ignore them and it gets flaky:
|
||||
|
||||
1. **Invoke the menu item by UIA InvokePattern, not a coordinate left-click.** The menu item exposes `InvokePattern` (`isInvokable=True`). `winapp ui invoke <selector> -w <menuHwnd>` is robust and needs no foreground/coordinates for the *click*. A synthetic left-click at the item's pixel center also works but is the fragile part (DPI, menu repositioning near screen edges, scrolled menus).
|
||||
2. **The right-click that OPENS the menu still needs synthetic input on a foregrounded window — and occasionally a retry.** The first right-click right after Explorer opens sometimes misses (foreground not settled). `Open-PtExplorerContextMenu` retries up to 3×; that removed the flakiness in testing.
|
||||
|
||||
**Hard prerequisite — unlocked interactive desktop.** Synthetic right-click injects into the session input stream, so it requires foreground. If the workstation is locked / RDP minimized (`GetForegroundWindow()=0`), this flow is `BLK-ENV` — there is no foreground-free way to open a context menu. `Open-PtExplorerContextMenu` throws a clear BLK-ENV error in that case. (A 4-hour idle auto-lock is the common culprit — see `references/environment-setup.md`.)
|
||||
|
||||
**Other constraints:**
|
||||
- **Settings for these modules live in a module-OWNED file, not the PT-store `settings.json`** — see `SKILL.md` pitfall #18. The context-menu handler reads e.g. `power-rename-settings.json` / `file-locksmith-settings.json` / `image-resizer-settings.json` / `New\settings.json` at launch; editing the PT-store `<Module>\settings.json` (what `Get-PtModuleSettings` reads) often has **no effect** on the live handler. Drive icon/extended-menu/feature toggles via the module-owned file + relaunch (restart runner+Explorer for the menu handlers), then restore.
|
||||
- This is the **Win11 packaged** context menu (`Microsoft.UI.Content.PopupWindowSiteBridge` / "PopupHost"). The packaged module commands appear **only** here — not in classic `Shell.Application.Verbs()` and not via `CoCreate` of the command CLSID (`REGDB_E_CLASSNOTREGISTERED`). On Win10, or under "Show more options", you'd get the classic menu instead (different structure).
|
||||
- The menu exists in the UIA tree **only while open** — you must open it with real input first; you can't enumerate it cold.
|
||||
- A menu-launched module UI runs **non-elevated** (Explorer's integrity), even if your agent shell is elevated. Mind elevation-visibility (e.g. a non-elevated File Locksmith can't see higher-IL processes — match locker integrity with `scripts/pt-nonelevated.ps1`).
|
||||
|
||||
## Recipe (robust)
|
||||
|
||||
```powershell
|
||||
. "$skill\scripts\pt-explorer-contextmenu.ps1"
|
||||
|
||||
# 0) Guard: must be an unlocked desktop
|
||||
if (-not (Test-PtDesktopInteractive)) { <# mark BLK-ENV, cite references/environment-setup.md #> }
|
||||
|
||||
# 1) Open Explorer on the target folder and grab its CabinetWClass HWND
|
||||
Start-Process explorer.exe $dir; Start-Sleep 4
|
||||
$hwnd = (winapp ui list-windows --json | ConvertFrom-Json |
|
||||
Where-Object { $_.className -eq 'CabinetWClass' -and $_.title -match [regex]::Escape((Split-Path $dir -Leaf)) } |
|
||||
Select-Object -First 1).hwnd
|
||||
|
||||
# 2) Open the real context menu (synthetic right-click, auto-retry)
|
||||
$menu = Open-PtExplorerContextMenu -ExplorerHwnd $hwnd -FileName 'target.txt'
|
||||
|
||||
# 3a) ASSERT PRESENCE / ABSENCE (e.g. "entry no longer appears" when the module is disabled)
|
||||
$items = Get-PtContextMenuItems -MenuHwnd $menu # all visible MenuItem names
|
||||
$present = $items -contains 'Unlock with File Locksmith'
|
||||
|
||||
# 3b) LAUNCH the module via the real menu (UIA invoke by NAME — robust)
|
||||
$ok = Invoke-PtContextMenuItem -MenuHwnd $menu -ItemName 'Unlock with File Locksmith'
|
||||
|
||||
# 4) Verify the module launched (its process/window appears) — e.g.:
|
||||
Start-Sleep 4
|
||||
$ui = Get-Process PowerToys.FileLocksmithUI -EA SilentlyContinue # or PowerToys.ImageResizer, PowerToys.PowerRename
|
||||
```
|
||||
|
||||
To **assert absence** after disabling a module: re-open the menu and check `Get-PtContextMenuItems` no longer contains the caption (the packaged `GetState` re-reads the enabled flag live, so no Explorer restart is needed between toggles).
|
||||
|
||||
## Multi-file selection (Image Resizer, PowerRename)
|
||||
|
||||
These operate on a **selection** of files. Select first (Shell COM is reliable and foreground-free), then right-click one of the selected items:
|
||||
- Use `scripts/pt-explorer-com.ps1` → `Open-PtExplorerAtPath` + `Select-PtExplorerFiles` to establish the multi-select.
|
||||
- Then `Open-PtExplorerContextMenu` on one selected file and `Invoke-PtContextMenuItem` — the module receives the whole selection (the shell handler enumerates all selected `IShellItem`s).
|
||||
|
||||
## Module captions (match by NAME)
|
||||
|
||||
Match the **visible caption**, not the AutomationId (Explorer assigns per-session numeric IDs like `32012` whose value/order varies). Discover the exact caption at runtime with `Get-PtContextMenuItems`. Verified captions:
|
||||
|
||||
| Module | Launched process | Menu caption (verified ✓ / expected) |
|
||||
|---|---|---|
|
||||
| File Locksmith | `PowerToys.FileLocksmithUI.exe` | ✓ `Unlock with File Locksmith` (NB: **not** the checklist's "What's using this file?") |
|
||||
| PowerRename | `PowerToys.PowerRename.exe` | ✓ `Rename with PowerRename` |
|
||||
| Image Resizer | `PowerToys.ImageResizer.exe` | `Resize images` (verify via `Get-PtContextMenuItems` — caption shifted across versions) |
|
||||
| New+ | (creates from template) | `New+` (submenu) |
|
||||
|
||||
> Tip: if a module's caption is unknown, enable the module, open the menu on an applicable file, and run `Get-PtContextMenuItems` to read the exact string — then hard-match it for present/absent assertions.
|
||||
|
||||
## Common failure modes → fixes
|
||||
|
||||
| Symptom | Cause | Fix |
|
||||
|---|---|---|
|
||||
| `BLK-ENV: ... GetForegroundWindow()=0` | desktop locked / RDP minimized | unlock & keep mstsc un-minimized (`references/environment-setup.md`); mark `BLK-ENV`, not a test failure |
|
||||
| "popup not found after N attempts" | foreground not settled (esp. first right-click after Explorer opens) | the helper already retries 3×; raise `-MaxTries`, or pre-foreground the window once before calling |
|
||||
| menu item `invoke` returns but nothing launches | matched the wrong node / item disabled | match `type -eq 'MenuItem'` by exact Name; confirm the module is enabled |
|
||||
| caption not found though module enabled | wrong/old caption string, or it's under "Show more options" (classic menu) | enumerate with `Get-PtContextMenuItems`; for classic menu invoke `expandtoclassic` first |
|
||||
| launched UI shows nothing | menu-launched UI is non-elevated and can't see higher-IL targets | match target integrity (`scripts/pt-nonelevated.ps1`) |
|
||||
|
||||
## Referenced by
|
||||
- `references/modules/file-locksmith.md` (L641/L652 — real right-click launch + menu present/absent)
|
||||
- *(future)* `references/modules/image-resizer.md`, `references/modules/power-rename.md`, `references/modules/new-plus.md` — reference this doc for their context-menu items.
|
||||
@@ -1,116 +0,0 @@
|
||||
# Per-module verification profiles (`references/modules/`)
|
||||
|
||||
This folder holds **one short profile per PowerToys module**. Each profile is self-contained guidance specific to that module — paths, entry-paths, capability/control recipes, common BLOCKED traps, fixture lists, source citations.
|
||||
|
||||
## When to read
|
||||
|
||||
When this skill runs for a specific module, check whether `references/modules/<module>.md` exists here. If yes: **read it BEFORE walking the SKILL.md drive-stack** — it tells you which entry-paths actually work for this module's quirks and which BLOCKED traps to avoid.
|
||||
|
||||
If no profile exists, fall back to SKILL.md + the helper scripts.
|
||||
|
||||
## Shared cross-module flows
|
||||
|
||||
Some flows are common to several modules and live in their own top-level docs (not per-module):
|
||||
- **`../references/explorer-context-menu-flow.md`** — driving the real Win11 Explorer right-click context menu end-to-end (open + assert present/absent + launch). Referenced by File Locksmith and any future **Image Resizer / PowerRename / New+** profiles.
|
||||
|
||||
## Why per-module (not just one big SKILL.md)
|
||||
|
||||
- Each module has its own quirks (Peek's `_isFromCli` guard, CmdPal's TextChanged-broken state, PT Run's mini-popup HWND, Workspaces' snapshot-elevation rules). Bundling all of them into the global SKILL.md bloats context and forces every verification to load 25+ KB of mostly-irrelevant text.
|
||||
- A profile lets a focused verification run with only the relevant 5-10 KB.
|
||||
- New gotchas discovered during a module verification round get added to that module's profile, not the global one — keeps the global doc stable.
|
||||
|
||||
## Profile catalog
|
||||
|
||||
| Module | Profile | Status |
|
||||
|---|---|---|
|
||||
| Peek | `peek.md` | ✅ written 2026-06-08 |
|
||||
| File Locksmith | `file-locksmith.md` | ✅ written 2026-06-08 |
|
||||
| Image Resizer | `image-resizer.md` | ✅ written 2026-06-09 |
|
||||
| PowerRename | `power-rename.md` | ✅ written 2026-06-10 (first to cite `../context-menu-cookbook.md` for shared mechanics) |
|
||||
| New+ | `new-plus.md` | ✅ written 2026-06-18 (registration-gate for menu presence; Settings-UI toggle drives template auto-copy) |
|
||||
| (other modules to be added as we encounter sign-off needs) | — | — |
|
||||
|
||||
## For Explorer-context-menu modules: read the canonical flow doc first
|
||||
|
||||
If you're writing a profile for a module that registers an entry in Explorer's Win11 right-click menu (PowerRename, File Locksmith, Image Resizer, New+, Preview Pane, RegistryPreview), **read `../references/explorer-context-menu-flow.md` first**. It has the canonical synthetic-right-click + UIA-invoke recipe with:
|
||||
|
||||
- Which-approach-first decision rule (CLI back-door vs synthetic menu, with the false-positive trap warning)
|
||||
- Stability rules (UIA InvokePattern, retry on first right-click)
|
||||
- Recipe (robust 5-step flow)
|
||||
- Multi-file selection notes
|
||||
- Module captions table (per-module menu-item display names)
|
||||
- Common failure modes
|
||||
- The unlocked-desktop requirement (BLK-ENV gating)
|
||||
|
||||
The shared helper is `scripts/pt-explorer-contextmenu.ps1` (`Test-PtDesktopInteractive`, `Open-PtExplorerContextMenu`, `Invoke-PtContextMenuItem`, `Get-PtContextMenuItems`).
|
||||
|
||||
Your module profile then only documents the **module-specific** quirks: settings.json schema keys, expected verb caption regex, capability/control recipes, source citations, ceiling.
|
||||
|
||||
`power-rename.md` is the model — ~9 KB despite covering 18 items because the generic mechanics live in the canonical flow doc.
|
||||
|
||||
## Profile template
|
||||
|
||||
When writing a new profile, use this skeleton:
|
||||
|
||||
```markdown
|
||||
# <Module> — module verification profile
|
||||
|
||||
**PT module**: `<ModuleKey>` (one-line description)
|
||||
**Source**: `<PT-repo>\src\modules\<dir>\` (PT repo)
|
||||
**Settings file**: `%LOCALAPPDATA%\Microsoft\PowerToys\<dir>\settings.json`
|
||||
**Logs**: `%LOCALAPPDATA%\Microsoft\PowerToys\<dir>\Logs\v<ver>\log_<date>.log`
|
||||
**Exes**: `<full path>`
|
||||
**Default hotkey**: `<keys>` (modifiers + code, plus path to ActivationShortcut in settings)
|
||||
**Named Event**: `Local\<name>` (friendly name in pt-shared-events.ps1 catalog)
|
||||
**DSC resource**: `Microsoft.PowerToys/<Name>Settings`
|
||||
|
||||
## Entry-paths (try in order)
|
||||
|
||||
### 1. <fastest path>
|
||||
<powershell code + when to use + source citation>
|
||||
|
||||
### 2. <alternate path>
|
||||
<...>
|
||||
|
||||
### 3. <last-resort path>
|
||||
<...>
|
||||
|
||||
## Recipes — a control/observation map, NOT a per-test-case answer key
|
||||
|
||||
| # | Capability | Drive (control / settings key) | Observe (where the result shows) |
|
||||
|---|---|---|---|
|
||||
| 1 | <a module capability, e.g. "context-menu entry present when enabled"> | <which AutomationId / control / settings key drives it> | <where the result is visible: preview column, settings.json, disk, log, menu> |
|
||||
| 2 | <next capability> | <...> | <...> |
|
||||
|
||||
> **Mapping process** (agent at runtime): read the actual checklist item → identify the capability → find its row → drive the named control and **design your own inputs + assertions for that item**. If no row matches, it's a NEW capability — drive ad-hoc and add a row (capability + control + observation point; no canned inputs).
|
||||
|
||||
> **Why a map, not an answer key**: the table must carry only **durable module knowledge** — which control drives a capability and where to observe the result. Concrete Search/Replace inputs and expected-output assertions are *per-test-case answers*; baking them in turns the profile into a cheat sheet that (a) lets the agent copy answers without understanding and (b) goes stale the moment a checklist item changes its wording or values. Keep inputs + assertions OUT. Only a real UI redesign (a renamed/moved/removed control) should force an edit to this table.
|
||||
|
||||
## Common BLOCKED traps
|
||||
|
||||
<list of mistakes prior agents made + how to avoid them>
|
||||
|
||||
## Fixture files needed
|
||||
|
||||
<list of pre-canned files the verification expects>
|
||||
|
||||
## Source citations
|
||||
|
||||
<paths in PT repo that explain module behavior or guards>
|
||||
|
||||
## Ceiling
|
||||
|
||||
<observed PASS rate / total>
|
||||
|
||||
## Don'ts
|
||||
|
||||
<list of common mistakes>
|
||||
```
|
||||
|
||||
## Hygiene
|
||||
|
||||
- **Keep each profile under ~10 KB.** If it grows beyond that, the module has too many quirks — escalate to maintainer review of the upstream checklist.
|
||||
- **The recipe table is a control/observation MAP, not an answer key.** Columns are *Capability → Drive (control/key) → Observe*. **Do NOT bake in concrete Search/Replace inputs or expected-output assertions** — those are per-test-case answers that go stale when a checklist item changes and let the agent copy without understanding. The agent designs inputs + assertions at runtime from the actual checklist item.
|
||||
- **Tables are capability-keyed, NOT line-keyed.** Upstream checklist line numbers (`L<n>`) **must not appear** in the profile — they drift between releases (items added/removed/reordered) and turn the table into a silent mismatch trap. PT-source-code file:line citations (e.g. `dllmain.cpp:73`) ARE allowed; they're version-pinned and serve a different purpose.
|
||||
- **Cite source-code line numbers** where module behavior surprises (e.g. CLI guards, debounce timings, fallback chains). Reviewers can verify your claims by reading those lines.
|
||||
- **Update the profile after every verification round**; promote any new technique into the right helper script if it generalizes beyond this module.
|
||||
@@ -1,103 +0,0 @@
|
||||
# File Locksmith — module verification profile
|
||||
|
||||
**PT module**: `File Locksmith` (shows which processes are using selected files/dirs and lets you kill them)
|
||||
**Source**: `<PT-repo>\src\modules\FileLocksmith\` (PT repo)
|
||||
**Settings file (module)**: `%LOCALAPPDATA%\Microsoft\PowerToys\File Locksmith\settings.json` (`{"properties":{"bool_show_extended_menu":{...}}}`) and `file-locksmith-settings.json` (`{"showInExtendedContextMenu":bool}`)
|
||||
**Enable flag**: `%LOCALAPPDATA%\Microsoft\PowerToys\settings.json` → `enabled."File Locksmith"` (general settings; runner-owned)
|
||||
**Logs**: `%LOCALAPPDATA%\Microsoft\PowerToys\File Locksmith\FileLocksmithUI\Logs\…`
|
||||
**Exes**: UI = `%LOCALAPPDATA%\PowerToys\WinUI3Apps\PowerToys.FileLocksmithUI.exe`; CLI = `%LOCALAPPDATA%\PowerToys\FileLocksmithCLI.exe`
|
||||
**Context menu**: Win11 packaged `IExplorerCommand` CLSID `{AAF1E27D-4976-49C2-8895-AAFA743C0A7E}` (sparse pkg `Microsoft.PowerToys.FileLocksmithContextMenu`); legacy `FileLocksmithExt.dll`. Caption resource = "What's using this file?".
|
||||
**Named Event / DSC**: no Named Event. DSC resource `microsoft.powertoys.FileLocksmith.settings` exists (controls module settings, not the master enable flag).
|
||||
**No global hotkey** — entry is the Explorer context menu only.
|
||||
|
||||
## The two back-doors that make this module fully drivable (no Explorer needed)
|
||||
|
||||
### 1. `FileLocksmithCLI.exe` — deterministic engine ground-truth (PREFER for assertions)
|
||||
Accepts paths as args; `--json`, `--kill`, `--wait`, `--timeout`. Uses the **same** `find_processes_recursive` engine as the UI.
|
||||
```powershell
|
||||
$cli = "$env:LOCALAPPDATA\PowerToys\FileLocksmithCLI.exe"
|
||||
& $cli "<file|dir|drive>" --json | ConvertFrom-Json # {processes:[{pid,name,user,files[]}]}
|
||||
& $cli "<path>" --kill # terminate lockers (== End task)
|
||||
```
|
||||
Detection = open **File handles** + **loaded modules** under the path (exact file, exact dir, dir-prefix recursive). `FileLocksmith.cpp:18-113`.
|
||||
|
||||
### 2. `last-run.log` IPC + launch UI — exercises the REAL UI code path
|
||||
The context-menu handler writes selected paths to `…\File Locksmith\last-run.log` then launches the UI; the UI reads them in `MainViewModel()` ctor. Reproduce it:
|
||||
```powershell
|
||||
# UTF-16LE, each path + WCHAR \n, trailing empty-line terminator, NO BOM
|
||||
function Write-LastRun([string[]]$Paths){
|
||||
$f="$env:LOCALAPPDATA\Microsoft\PowerToys\File Locksmith\last-run.log"; $ms=[IO.MemoryStream]::new()
|
||||
foreach($p in $Paths){$b=[Text.Encoding]::Unicode.GetBytes($p);$ms.Write($b,0,$b.Length);$n=[Text.Encoding]::Unicode.GetBytes("`n");$ms.Write($n,0,$n.Length)}
|
||||
$n=[Text.Encoding]::Unicode.GetBytes("`n");$ms.Write($n,0,$n.Length);[IO.File]::WriteAllBytes($f,$ms.ToArray())
|
||||
}
|
||||
Write-LastRun @("C:\path\to\file"); Start-Process "$env:LOCALAPPDATA\PowerToys\WinUI3Apps\PowerToys.FileLocksmithUI.exe"
|
||||
```
|
||||
Source: `ExplorerCommand.cpp:182-227`, `dllmain.cpp:94-159`, `IPC.cpp`, `NativeMethods.cpp:62-97`.
|
||||
|
||||
### UI selectors (winapp ui)
|
||||
- Window title: `Administrator: File Locksmith` (elevated) vs `File Locksmith` (non-elevated).
|
||||
- Header button = the path label (`btn-<pathname>-…`); top-right `btn-…` = **Reload** (tooltip "Reload").
|
||||
- Per-row End task button = `btn-…` (parent of `lbl-endtask-…`); invoke it (`InvokePattern`).
|
||||
- `RestartAsAdminBtn` = shield icon, **visible only when non-elevated** (`MainPage.xaml:72-82`).
|
||||
- `ProcessesListView` is virtualized; use `winapp ui scroll ProcessesListView --direction down/up`.
|
||||
|
||||
## Recipes — a control/observation map, NOT a per-test-case answer key
|
||||
|
||||
> Maps each capability to **how to drive it** and **where the result shows**. No canned process counts / paths / assertions — design those at runtime from the actual checklist item.
|
||||
|
||||
| # | Capability | Drive (entry-path / control) | Observe (where the result shows) |
|
||||
|---|---|---|---|
|
||||
| 1 | A locked file lists all its locking processes | CLI + UI on one locked file (with multiple lockers) | each locker shows as a ListItem |
|
||||
| 2 | "End task" kills the locker and de-lists it | `winapp ui invoke` the End-task button | locker PID dies + row removed |
|
||||
| 3 | Reload rediscovers a locker started after the UI opened | start a new locker → invoke Reload | the new locker appears |
|
||||
| 4 | Closing a locker externally auto-removes it | external `Stop-Process` on a locker | auto-delisted via `WatchProcess`; empty state shown |
|
||||
| 5 | Directory path finds lockers recursively | CLI/UI with a directory path | lockers inside the tree are listed |
|
||||
| 6 | Drive root lists many lockers without crashing | CLI/UI with a drive root | large list renders; no crash |
|
||||
| 7 | Non-elevated FL does NOT see the elevated runner | run CLI/UI non-elevated via scheduled task `RunLevel Limited` | `PowerToys.exe` absent (medium-IL FL can't see elevated procs) |
|
||||
| 8 | "Restart as administrator" surfaces elevated-only lockers | non-elev UI shows the button; elevated run shows them | elevated run lists `PowerToys.exe` (UAC consent click NOT automatable) |
|
||||
| 9 | Scrolling a large list doesn't crash | UI on a drive root + `winapp ui scroll` | process alive + responsive after scroll |
|
||||
| 10 | Disabling FL removes the Explorer context-menu entry | Settings toggle Off (winapp ui) | `enabled."File Locksmith"`→false; `GetState→ECS_HIDDEN` (source) |
|
||||
|
||||
> **Mapping process**: read the actual checklist item → identify the capability → find its row → drive the named control and design your own inputs + assertions. If no row matches, drive ad-hoc and add a row (capability + control + observation point; no canned inputs).
|
||||
|
||||
## Common BLOCKED traps (avoid)
|
||||
- **Don't BLOCK the lock-detection / End-task / scroll-doesn't-crash items as "needs a real installer / right-click"** — both the CLI and the `last-run.log`+UI back-door fully drive them with any locked file. The context menu literally just writes `last-run.log` + launches the same exe.
|
||||
- **Launching the UI from an elevated shell makes it elevated** (title "Administrator: …") and hides the `RestartAsAdminBtn`. To test the non-elevated case (Recipes 7-8), launch via a **scheduled task with `-RunLevel Limited` / LogonType Interactive** — it lands on the user's desktop at medium IL.
|
||||
- **`set-value` does fire the Reload** here (TogglePattern/Invoke work); no TextChanged gotchas.
|
||||
|
||||
## Elevation semantics (non-elevated FL invisibility — Recipes 7-8 core)
|
||||
A medium-IL File Locksmith can't `DuplicateHandle`/read modules of higher-integrity processes, so the **elevated PowerToys.exe runner is invisible** to a non-elevated FL and **visible** to an elevated FL (which also calls `SetDebugPrivilege`, `App.xaml.cs:53-61`). Per-user installs put PowerToys under `%LOCALAPPDATA%\PowerToys`, not "Program Files" — use the PT install dir as the stand-in and note the caveat.
|
||||
|
||||
## Context-menu disable gate (Recipe 10)
|
||||
`GetEnabled()` reads general `enabled."File Locksmith"` (`Settings.cpp:53-77`). When false: Win11 `GetState→ECS_HIDDEN` (`dllmain.cpp:81-84`); legacy `QueryContextMenu→E_FAIL` (`ExplorerCommand.cpp:116-119`). Disabling does NOT unregister the sparse package (stays `Status Ok`) — the entry is hidden dynamically. The packaged `IExplorerCommand` is **not** enumerable via Shell `Verbs()` and **not** `CoCreate`-able from a non-Explorer host (`REGDB_E_CLASSNOTREGISTERED`), so the pixel-level render is the only un-automatable bit (`BLK-VISUAL-RENDER` if you need it).
|
||||
|
||||
## Fixture files needed
|
||||
None pre-canned. Create a temp file and lock it with a helper process (pwsh holding `File.Open(path, OpenOrCreate, Read, ReadWrite)` so multiple lockers coexist).
|
||||
|
||||
## Source citations
|
||||
- `FileLocksmithLibInterop\FileLocksmith.cpp:18-113` — `find_processes_recursive` (handles + modules, recursive).
|
||||
- `FileLocksmithLibInterop\NativeMethods.cpp:62-140` — `ReadPathsFromFile`, `StartAsElevated` (runas/--elevated).
|
||||
- `FileLocksmithLib\IPC.cpp`, `Constants.h` — last-run.log format/path.
|
||||
- `FileLocksmithUI\…\MainViewModel.cs:80-183` — load/EndTask/WatchProcess/RestartElevated.
|
||||
- `FileLocksmithUI\…\MainPage.xaml` — control layout + RestartAsAdminBtn visibility.
|
||||
- `FileLocksmithExt\ExplorerCommand.cpp`, `FileLocksmithContextMenu\dllmain.cpp`, `FileLocksmithLib\Settings.cpp` — enable gate.
|
||||
|
||||
## Ceiling
|
||||
10/10 PASS observed (2026-06-08). The lock-detection / End-task / refresh / drive-scroll items cleanly driven; the Restart-as-admin item PASS-with-caveat (UAC consent click not automatable; outcome verified). **The disable-removes-menu item PASS — behaviorally verified** by a real Explorer right-click: with FL enabled the Win11 menu shows `MenuItem "Unlock with File Locksmith"`; after disabling in Settings the same right-click menu no longer shows it (no Explorer restart needed — `GetState` re-reads `enabled."File Locksmith"` live). NB the **shipped caption is "Unlock with File Locksmith"**, not the checklist's "What's using this file?". The right-click test needs an **unlocked interactive desktop** (a 4-hour idle auto-lock makes `GetForegroundWindow()=0` → `BLK-ENV`).
|
||||
|
||||
## Real right-click verification (Recipe 10) — works on an unlocked desktop
|
||||
**Use the shared flow: `references/explorer-context-menu-flow.md` + `scripts/pt-explorer-contextmenu.ps1`.** FL's caption is **"Unlock with File Locksmith"**. Quick version:
|
||||
```powershell
|
||||
. "$skill\scripts\pt-explorer-contextmenu.ps1"
|
||||
$menu = Open-PtExplorerContextMenu -ExplorerHwnd $hwnd -FileName 'target.txt' # synthetic right-click (+retry)
|
||||
# present/absent assertion:
|
||||
(Get-PtContextMenuItems -MenuHwnd $menu) -contains 'Unlock with File Locksmith' # true enabled / false disabled
|
||||
# real launch (UIA invoke by name):
|
||||
Invoke-PtContextMenuItem -MenuHwnd $menu -ItemName 'Unlock with File Locksmith' # -> launches PowerToys.FileLocksmithUI.exe (non-elevated)
|
||||
# Toggle FL off in Settings, re-open menu, assert the caption is gone. No Explorer restart needed (GetState re-reads live).
|
||||
```
|
||||
|
||||
## Don'ts
|
||||
- Don't expect `Shell.Application.Verbs()` to show the FL entry — it's a Win11 packaged command, invisible to classic verbs.
|
||||
- Don't kill processes by name; use `Stop-Process -Id <pid>`.
|
||||
- Don't forget to restore `enabled."File Locksmith"=true` and close test-spawned UI/Settings after the disable-removes-menu test.
|
||||
@@ -1,87 +0,0 @@
|
||||
# Image Resizer — module verification profile
|
||||
|
||||
**PT module**: `Image Resizer` (resize images via Explorer right-click; WinUI 3 GUI + headless CLI)
|
||||
**Source**: `<PT-repo>\src\modules\imageresizer\` (PT repo)
|
||||
**Settings file**: `%LOCALAPPDATA%\Microsoft\PowerToys\Image Resizer\settings.json` (PowerToys-wrapper shape: `{ "properties": { "imageresizer_*": { "value": … } }, "name": "Image Resizer", "version": "1" }`). A legacy `sizes.json` mirrors `imageresizer_sizes`; `image-resizer-settings.json` is `{}` (unused).
|
||||
**Enable flag**: `%LOCALAPPDATA%\Microsoft\PowerToys\settings.json` → `enabled."Image Resizer"` (runner-owned; restart runner after toggling).
|
||||
**Logs**: `%LOCALAPPDATA%\Microsoft\PowerToys\Image Resizer\Logs\…`
|
||||
**Exes**: GUI = `%LOCALAPPDATA%\PowerToys\WinUI3Apps\PowerToys.ImageResizer.exe`; **CLI = `%LOCALAPPDATA%\PowerToys\WinUI3Apps\PowerToys.ImageResizerCLI.exe`**.
|
||||
**Context menu**: Win11 packaged `IExplorerCommand` (sparse pkg `ImageResizerContextMenuPackage.msix`, dllmain.cpp) + legacy classic `ImageResizerExt.dll` (`dll/ContextMenuHandler.cpp`). **Shipped caption = "Resize with Image Resizer"** (`IDS_IMAGERESIZER_CONTEXT_MENU_ENTRY`; checklist's "Resize images" is STALE).
|
||||
**No global hotkey / no Named Event / no DSC for the engine** — entry is the Explorer menu (or direct exe launch).
|
||||
|
||||
## The back-door that makes this module ~fully drivable (no Explorer needed)
|
||||
|
||||
### `PowerToys.ImageResizerCLI.exe` — the deterministic engine (PREFER for all resize-behavior items)
|
||||
Shares the exact `ResizeBatch.FromCliOptions` → `ResizeBatch.ProcessAsync` → `ResizeOperation.ExecuteAsync` engine as the GUI (`ui/Cli/ImageResizerCliExecutor.cs:76-108`, `App.xaml.cs:102`). Reads live `Image Resizer\settings.json` then applies CLI overrides (`CliSettingsApplier.cs`).
|
||||
```
|
||||
--width/-w --height/-h --unit/-u {Centimeter|Inch|Percent|Pixel} --fit/-f {Fill|Fit|Stretch}
|
||||
--size <presetIndex> --shrink-only --replace/-r --ignore-orientation --remove-metadata
|
||||
--quality/-q --keep-date-modified --filename/-n "<%1..%6>" --destination/-d <dir>
|
||||
--show-config --help <files…> (also accepts \\.\pipe\<name> and stdin file list)
|
||||
```
|
||||
`--show-config` dumps the effective settings (great pre/post check). `-d <dir>` keeps outputs isolated. Assert output dimensions with `[System.Drawing.Image]::FromFile(p)`.
|
||||
**Caveat**: `--ignore-orientation`/`--shrink-only`/`--replace`/`--keep-date-modified`/`--remove-metadata` are *flags* — they can only set the value **true**; to test the **false** case, temporarily edit `settings.json` (back up + restore).
|
||||
|
||||
### Direct GUI launch — for the two UI-only items (gif warning, size-list populated)
|
||||
`Start-Process PowerToys.ImageResizer.exe "<file>"` opens the window pre-loaded (argv/stdin via `ResizeBatch.FromCommandLine`). Behaviorally identical to the context-menu launch (`dllmain.cpp:219-245` just writes a pipe + launches the same exe). Then drive with `winapp ui`:
|
||||
- Size selector: `SizeComboBox` → `winapp ui invoke SizeComboBox -w <hwnd>` to expand, then `inspect` shows `itm-<name>-XXXX` ListItems.
|
||||
- Gif warning: `Message Text "Gif files with animations may not be correctly resized."` InfoBar, bound to `ViewModel.HasGifFiles` (set when any file ends `.gif`).
|
||||
|
||||
## Engine facts (verified from source — cite these for the resize items)
|
||||
- `ResizeFit`: **Fill=0, Fit=1, Stretch=2** (`ResizeFit.cs`). Fit=`min(scaleX,scaleY)`; Fill=`max`+centered-crop; Stretch=independent (`ResizeOperation.cs:449-498`).
|
||||
- `ResizeUnit`: **Centimeter=0, Inch=1, Percent=2, Pixel=3** (`ResizeUnit.cs`). Inch=`v*dpi`; cm=`v*dpi/2.54`; Percent=`v/100*orig`; Pixel=`v` (`ResizeSize.cs:109-123`). **Outputs depend on image DPI** — read actual DPI and compute expectations from it (a 120-DPI fixture gives 10cm→472px, 4in→480px).
|
||||
- Filename `%1..%6` → original-name, size-name, selected-W, selected-H, **output**-W, **output**-H (`Settings.cs:229-239`, `ResizeOperation.cs:593-601`).
|
||||
- ShrinkOnly: if target scale>1, returns `noTransformNeeded` (file copied unchanged) (`ResizeOperation.cs:462-475`).
|
||||
- KeepDateModified: `SetLastWriteTimeUtc(out, GetLastWriteTimeUtc(src))` (`ResizeOperation.cs:146-149`).
|
||||
- Replace: `File.Replace(out, src, backup)` then recycle backup — no copy left (`ResizeOperation.cs:151-156`).
|
||||
- IgnoreOrientation swap: gated by `IgnoreOrientation && !HasAuto && Unit != Percent` (`ResizeOperation.cs:419-444`).
|
||||
|
||||
## Recipes — a control/observation map, NOT a per-test-case answer key
|
||||
|
||||
> Maps each capability to **which control/CLI flag drives it** and **where the result shows**. CLI flag *names* and fit-mode/unit/field enumerations are stable IR knowledge and stay; concrete flag *values*, fixtures, and expected outputs are per-test-case — design those at runtime.
|
||||
|
||||
| # | Capability | Drive (control / CLI flag) | Observe (where the result shows) |
|
||||
|---|---|---|---|
|
||||
| 1 | Module disabled → context-menu entry absent | toggle `enabled` off + restart runner; synthetic menu (only valid observer) | "Resize with Image Resizer" absent. Gate: `dllmain.cpp:87-91` (ECS_HIDDEN), `ContextMenuHandler.cpp:70-71,383-385`. Locked desktop → BLK-ENV |
|
||||
| 2 | Module enabled → entry present (modern + classic), click launches the GUI | synthetic menu + invoke | `Get-PtContextMenuItems` shows "Resize with Image Resizer"; classic "Show more options" too; invoke → `PowerToys.ImageResizer.exe` launches |
|
||||
| 3 | Remove a built-in size / add a custom size | edit `imageresizer_sizes` (INTEGER Ids!) + launch GUI | `SizeComboBox` reflects the edit (removed gone, custom present) |
|
||||
| 4 | Resize one / multiple files end-to-end | CLI `--size <id> [files…]` | outputs at the size's Fit dimensions |
|
||||
| 5 | GIF animation warning on `.gif` input | GUI on a `.gif` | warning InfoBar present (`winapp ui inspect`) |
|
||||
| 6 | Fit modes (Fill / Fit / Stretch) | CLI `--width --height --fit <mode>` | output shape matches the mode (crop / letterbox / exact) |
|
||||
| 7 | Unit conversion (cm / inch / percent / pixel) | CLI `--unit <u>` | output px = unit converted at the image's DPI |
|
||||
| 8 | Custom filename format (`%1`..`%6` fields) | CLI `--filename <fmt>` | output filename follows the format fields |
|
||||
| 9 | "Keep date modified" | CLI `--keep-date-modified` | output mtime == source mtime (control: without the flag, differs) |
|
||||
| 10 | "Shrink only" | CLI `--shrink-only` | an already-small image is untouched (control: a large one still shrinks) |
|
||||
| 11 | "Replace original" | CLI `--replace` | original replaced in place; no `(name) (1)` copy |
|
||||
| 12 | "Ignore orientation" | settings (false) vs flag (true) | on a portrait target over a landscape image: false→no W/H swap, true→swap |
|
||||
|
||||
> **Mapping process**: read the actual checklist item → identify the capability → find its row → drive the named control/flag and design your own inputs + assertions. If no row matches, drive ad-hoc and add a row (capability + control + observation point; no canned inputs).
|
||||
|
||||
## Common BLOCKED traps (avoid)
|
||||
- **Don't mark the resize-behavior items BLOCKED for "needs a real right-click".** The CLI fully drives them with the identical engine; the menu is just the trigger (prove the menu→launch wiring once with the golden path in Recipe 2).
|
||||
- **PowerShell `ConvertTo-Json` writes computed numbers as doubles (`"Id": 3.0`)** → `System.Text.Json` rejects `imageresizer_sizes` and the app silently falls back to the 4 built-in default presets (Small/Medium/Large/Phone). Cast Ids to `[int]` or regex-strip `\.0`. This bit the remove-size-add-custom item (Recipe 3) the first time.
|
||||
- **cm/inch outputs depend on the fixture's DPI, not 96.** System.Drawing saves at the session display DPI (here 120). Compute expectations from the actual DPI.
|
||||
- **Caption is "Resize with Image Resizer", not the checklist's "Resize images"** (both menus). Hard-match the real caption.
|
||||
- **Idle auto-lock = BLK-ENV for the disabled-absent + enabled-present items (Recipes 1-2)** (synthetic right-click needs foreground). Disable lock/sleep before the run (`references/environment-setup.md`).
|
||||
|
||||
## Fixture files needed
|
||||
None pre-canned. Generate with `System.Drawing`: a landscape (e.g. 1200×800) and portrait (800×1200) JPEG, a small (100×100) PNG, a square (400×400) PNG, a `.gif` (single frame is fine — the warning is extension-based), and 3 identical images for the multi-file batch.
|
||||
|
||||
## Source citations
|
||||
- `ui/Cli/ImageResizerCliExecutor.cs`, `ui/Models/CliOptions.cs`, `ui/Cli/CliSettingsApplier.cs`, `ui/Cli/Commands/ImageResizerRootCommand.cs` — CLI surface + engine reuse.
|
||||
- `ui/Models/ResizeOperation.cs:419-501,572-617,146-156` — dimension math, filename, keep-date, replace.
|
||||
- `ui/Models/ResizeSize.cs:78-124`, `ResizeFit.cs`, `ResizeUnit.cs` — unit/fit math + enum order.
|
||||
- `ui/Properties/Settings.cs:65,105-111,229-239,431-552` — paths, defaults, JSON property names, FileNameFormat.
|
||||
- `ImageResizerContextMenu/dllmain.cpp:49,79-133,219-245,284` — modern menu title, enable+image gate, launch, caption.
|
||||
- `dll/ContextMenuHandler.cpp:21,46-48,70-71,383-385` — classic menu caption + enable gate.
|
||||
- `ui/ViewModels/InputViewModel.cs:76,143`, `ImageResizerXAML/Views/InputPage.xaml:293-299`, `Strings/en-us/Resources.resw:148-149` — gif warning.
|
||||
|
||||
## Ceiling
|
||||
**18/18 PASS** observed (2026-06-09). All 14 resize-behavior items + the enabled-entry-present-in-both-menus + the remove-size + the gif-warning items cleanly driven via CLI/GUI. The disabled-entry-absent case (in both modern + classic menus, with sibling entries remaining and the entry returning on re-enable) verified live once the desktop was unlocked. NB: an idle auto-lock will turn the menu-presence Recipes 1-2 into BLK-ENV — disable lock/sleep up front (`references/environment-setup.md`).
|
||||
|
||||
## Don'ts
|
||||
- Don't expect `Shell.Application.Verbs()` to list the entry — it's a Win11 packaged command (classic verbs are blind; `CoCreate` → `REGDB_E_CLASSNOTREGISTERED`).
|
||||
- Don't hardcode 96 DPI for cm/inch math.
|
||||
- Don't write preset Ids as JSON doubles.
|
||||
- Don't kill processes by name; use `Stop-Process -Id <pid>`.
|
||||
- Don't forget to restore `enabled."Image Resizer"=true` + restart runner, and revert any `settings.json`/`sizes.json` edits.
|
||||
@@ -1,77 +0,0 @@
|
||||
# New+ — module verification profile
|
||||
|
||||
**PT module**: `NewPlus` (Explorer right-click → "New+" submenu that creates files/folders from a user templates folder)
|
||||
**Source**: `<PT-repo>\src\modules\NewPlus\` (shell ext) + `<PT-repo>\src\settings-ui\Settings.UI\ViewModels\NewPlusViewModel.cs` (Settings UI)
|
||||
**Module-owned settings file**: `%LOCALAPPDATA%\Microsoft\PowerToys\NewPlus\settings.json` — **folder is `NewPlus`, NOT `New`** (matches SKILL.md pitfall #18 table). Keys: `HideFileExtension`, `HideStartingDigits`, `TemplateLocation`, `ReplaceVariables`, `BuiltInNewHidePreference`.
|
||||
**Templates folder (default)**: `%LOCALAPPDATA%\Microsoft\PowerToys\NewPlus\Templates` (per `TemplateLocation`)
|
||||
**Default-templates source**: `%LOCALAPPDATA%\PowerToys\WinUI3Apps\Assets\NewPlus\Templates` (also `%ProgramFiles%\PowerToys\...` on machine installs)
|
||||
**Logs**: `%LOCALAPPDATA%\Microsoft\PowerToys\NewPlus\NewPlus.ShellExtension\Logs\v<ver>\log_<date>.log`
|
||||
**Packaged command**: sparse MSIX `Microsoft.PowerToys.NewPlusContextMenu`; command CLSID `{FF90D477-E32A-4BE8-8CC5-A502A97F5401}`
|
||||
**Named Event**: none. **DSC**: n/a.
|
||||
|
||||
> Read **`../references/explorer-context-menu-flow.md` first** — New+ is a Win11 packaged-IExplorerCommand context-menu module; the menu can only be eyeballed via a real synthetic right-click on an **unlocked interactive desktop**. On a locked/RDP-minimized desktop (`Test-PtDesktopInteractive=False`) all "menu appears / template appears / hidden-caption" assertions are BLK-ENV / BLK-VISUAL-RENDER, not product FAILs.
|
||||
|
||||
## Entry-paths (try in order)
|
||||
|
||||
### 1. Enable/disable + registration gate (menu presence/absence) — headless-safe
|
||||
Flip `enabled.NewPlus` in master `settings.json` + `Restart-PtRunner`, **or** toggle the Settings switch (below). Observe the gate, no foreground needed:
|
||||
- CLSID registered ⇒ `Test-Path "HKCU:\Software\Classes\CLSID\{FF90D477-E32A-4BE8-8CC5-A502A97F5401}"` is `True` (enabled) / `False` (disabled).
|
||||
- Log lines `New+ context menu registered` / `... unregistered` + `Runtime registration completed for CLSID ...`.
|
||||
- Sparse package stays `Status Ok` even when disabled (hidden dynamically — SKILL.md pitfall #17).
|
||||
|
||||
### 2. Settings UI toggles via UIA invoke — headless-safe, **required for template auto-copy**
|
||||
`Start-Process …\PowerToys.exe --open-settings=NewPlus`, then `winapp ui invoke <btn> -w <settingsHwnd>`:
|
||||
- Enable toggle: `btn-new-248c` (under `NewPlusEnableToggle`) — **the enable transition runs `CopyTemplateExamples`** (Settings-UI side, `NewPlusViewModel.IsEnabled` setter). A master-`settings.json` flip + runner restart does **NOT** copy templates.
|
||||
- `btn-hidethefileexte-24a0` (Hide file extension), `btn-hideleadingdigi-24a8` (Hide leading digits). AutomationIds carry a per-session suffix — re-`inspect` to get the live id.
|
||||
|
||||
### 3. Synthetic right-click on the folder **BACKGROUND** (the menu-render observer) — needs unlocked desktop
|
||||
New+ lives in the folder-background ("New") menu, **not** a file's context menu — so `pt-explorer-contextmenu.ps1`'s `Open-PtExplorerContextMenu` (which right-clicks a *file item*) is the wrong entry. Right-click an **empty area of the file list** instead, then expand the `New+` submenu (a separate popup window one level deeper):
|
||||
```powershell
|
||||
# force-foreground the CabinetWClass window, GetWindowRect, RightClick at ~45% width / 68% height (empty list area)
|
||||
# -> main bg menu popup (PopupWindowSiteBridge). Then:
|
||||
$np = (winapp ui search 'New+' -w $mainMenuHwnd --json).matches | ? type -eq MenuItem | select -First 1
|
||||
winapp ui invoke $np.selector -w $mainMenuHwnd # expands the New+ submenu
|
||||
# the submenu is the PopupWindowSiteBridge popup that contains 'Open templates' but NOT 'Sort by'
|
||||
# enumerate its MenuItems (templates are 1:1 with the Templates-folder entries) / invoke one by name
|
||||
```
|
||||
Template items render with **caption transforms applied** (HideFileExtension strips `.txt`; HideStartingDigits strips `01. `). Selecting a template creates it in the current folder + enters rename mode. BLK-ENV only if `Test-PtDesktopInteractive` is False. **No Explorer restart needed** for setting A/B — the handler re-reads `NewPlus\settings.json` on each menu build.
|
||||
|
||||
## Recipes — a control/observation map, NOT an answer key
|
||||
|
||||
| # | Capability | Drive (control / settings key) | Observe (where the result shows) |
|
||||
|---|---|---|---|
|
||||
| 1 | Menu entry present when enabled | enable (master flag + restart, or `btn-new-248c`) | CLSID registered in `HKCU\…\CLSID`, log `context menu registered`; *visible submenu* = synthetic menu only (BLK-VISUAL-RENDER if locked) |
|
||||
| 2 | Menu entry absent when disabled | disable | CLSID absent, log `context menu unregistered`; package still `Status Ok` |
|
||||
| 3 | Templates folder created empty | shell ext `create_folder_if_not_exist(root)` on menu build (delete folder → right-click) | folder recreated **empty** — needs synthetic menu (BLK-ENV if locked) |
|
||||
| 4 | Default templates copied when empty | `CopyTemplateExamples` on Settings-UI **enable** transition (`btn-new-248c` off→on) while folder empty | Templates folder repopulated from install Assets (filesystem — headless-safe) |
|
||||
| 5 | A template (file/folder) shows + creates on select | put item in Templates folder; select it in the New+ submenu | submenu item (1:1 with dir entries) + `SHFileOperation FO_COPY` to target — synthetic menu only |
|
||||
| 6 | Hide file extension | `HideFileExtension` / `btn-hidethefileexte-24a0` | strips ext from **menu caption only** (`get_menu_title`, `show_extension=false`); created file keeps ext — caption is BLK-VISUAL-RENDER if locked |
|
||||
| 7 | Hide starting digits/spaces/dots | `HideStartingDigits` / `btn-hideleadingdigi-24a8` | strips leading digits+separator from **both** menu caption and **created filename** (`remove_starting_digits_from_filename` via `get_menu_title` + `copy_template`); needs a digit-prefixed template + render |
|
||||
|
||||
> Verify a setting actually drives behavior by editing the **module-owned** `NewPlus\settings.json` (not the PT-store mirror) and relaunching; the Settings toggles round-trip into this same file.
|
||||
|
||||
## Common BLOCKED traps
|
||||
- **Master-flip + runner restart does not copy default templates** — that's a Settings-UI action (`NewPlusViewModel.IsEnabled`). Use the UIA toggle for any template-auto-copy item.
|
||||
- **Menu render is invisible without a real right-click** — packaged command is not `CoCreate`-able (`REGDB_E_CLASSNOTREGISTERED`) and not in classic `Shell.Application.Verbs()`. Locked desktop ⇒ BLK-ENV; do not substitute a CLI/back-door (there isn't one, and it'd be a false PASS).
|
||||
- **No template-count observable** — `saved_number_of_templates` is an in-memory static (`new_utilities.cpp`), not registry/log.
|
||||
|
||||
## Fixture files needed
|
||||
- A plain file (e.g. `test.txt`) and a folder-with-files to drop into Templates (template-appears items).
|
||||
- A digit-prefixed template (e.g. `01. Test.txt`) to exercise Hide-starting-digits.
|
||||
|
||||
## Source citations
|
||||
- `src/modules/NewPlus/NewShellExtensionContextMenu/template_item.cpp` — `get_menu_title` (hide-extension), `remove_starting_digits_from_filename`, `copy_object_to`.
|
||||
- `src/modules/NewPlus/NewShellExtensionContextMenu/new_utilities.h` — `copy_template`, `create_folder_if_not_exist`, `get_newplus_setting_hide_*`, `register_msix_package`.
|
||||
- `src/modules/NewPlus/NewShellExtensionContextMenu/shell_context_sub_menu.cpp` — `create_folder_if_not_exist(root)` + template enumeration.
|
||||
- `src/settings-ui/Settings.UI/ViewModels/NewPlusViewModel.cs` — `CopyTemplateExamples` (creates dir; copies examples only when files==0 && dirs==0), called from `IsEnabled` setter / `OpenNewTemplateFolder` / `DashboardViewModel`.
|
||||
|
||||
## Ceiling
|
||||
- Unlocked interactive desktop: **9/9 PASS** (verified 2026-06-18 via background-menu synthetic right-click + submenu expansion).
|
||||
- Locked/non-interactive desktop: ~3/9 (registration-gate present/absent + template auto-copy); menu-render/select items fall to BLK-ENV/BLK-VISUAL-RENDER — re-run after unlocking.
|
||||
|
||||
## Don'ts
|
||||
- Don't edit `…\PowerToys\New\settings.json` — wrong path; the file is under `NewPlus\`.
|
||||
- Don't use `Open-PtExplorerContextMenu` (file-item right-click) for New+ — it's the folder **background** ("New") menu; right-click empty list space instead.
|
||||
- Don't forget to **expand the `New+` submenu** (invoke it) before enumerating templates — they live one popup deeper than the main menu.
|
||||
- Don't mark menu-render items as product FAIL on a locked desktop — it's BLK-ENV.
|
||||
- Don't restart Explorer to apply a setting change — the handler re-reads `NewPlus\settings.json` per menu build.
|
||||
@@ -1,117 +0,0 @@
|
||||
# Peek — module verification profile
|
||||
|
||||
**PT module**: `Peek` (file previewer activated on Ctrl+Space with Explorer file selected)
|
||||
**Source**: `<PT-repo>\src\modules\Peek\` (PT repo)
|
||||
**Settings file**: `%LOCALAPPDATA%\Microsoft\PowerToys\Peek\settings.json`
|
||||
**Logs**: `%LOCALAPPDATA%\Microsoft\PowerToys\Peek\Logs\v<ver>\log_<date>.log`
|
||||
**Exes**: `%LOCALAPPDATA%\PowerToys\WinUI3Apps\PowerToys.Peek.UI.exe`
|
||||
**Default hotkey**: `Ctrl+Space` (modifiers=`ctrl`, code=32; see `settings.json` → `ActivationShortcut`)
|
||||
**Named Event**: `Local\ShowPeekEvent` (friendly name: `Peek.Show` in `pt-shared-events.ps1` catalog)
|
||||
**DSC resource**: `Microsoft.PowerToys/PeekSettings`
|
||||
|
||||
## Three entry-paths (try in order)
|
||||
|
||||
### 1. CLI back-door — fastest, no Explorer needed
|
||||
```powershell
|
||||
Start-Process "$env:LOCALAPPDATA\PowerToys\WinUI3Apps\PowerToys.Peek.UI.exe" -ArgumentList "<file>"
|
||||
```
|
||||
**Source**: `Peek.UI\PeekXAML\App.xaml.cs:106-134` — when last arg is not int (=runner PID) and is an existing file, it sets `_launchedFromCli=true`, builds `SelectedItemByPath`, calls `OnShowPeek()`. Bypasses hotkey + Explorer foreground.
|
||||
|
||||
**Use for**: single-file previewer rendering tests (Recipes 1-2) and the CLI-accepts-path assertion (Recipe 8).
|
||||
|
||||
**Cannot use for**: navigation tests (Recipes 4-7, 10-11) — source has `if (_isFromCli) return;` guard that disables arrow navigation, and CLI mode spawns a fresh process every call (no pin-state-across-reopen).
|
||||
|
||||
### 2. Shell.Application COM + Ctrl+Space — Explorer-driven, supports navigation
|
||||
This is the canonical "do what a real user would do" path that drives all the navigation/pin tests.
|
||||
|
||||
```powershell
|
||||
# Dot-source helpers first
|
||||
. "$skill\scripts\pt-explorer-com.ps1"
|
||||
. "$skill\scripts\pt-sendinput-chord.ps1"
|
||||
|
||||
# Set up multi-file selection in Explorer + trigger Peek in one call:
|
||||
$peekHwnd = Invoke-PtPeekWithExplorerSelection `
|
||||
-FolderPath 'D:\fixtures' `
|
||||
-FileNames 'test-markdown.md','test-html.html','test-source.cs'
|
||||
|
||||
# Now Peek is open over a 3-file IShellItemArray. Test:
|
||||
winapp ui invoke 'PinButton' -w $peekHwnd # pin
|
||||
# (move window via SetWindowPos)
|
||||
Send-PtChord -Key 0x27 # Right arrow → switch file
|
||||
# verify the pinned position stuck
|
||||
```
|
||||
|
||||
**Use for**: pin behavior, multi-file navigation, file switching (Recipes 4-7, 10-11).
|
||||
|
||||
**Requires**: interactive desktop session (`Test-PtInteractiveDesktop` must show both `ForegroundOk=True` and `ShellComOk=True`).
|
||||
|
||||
### 3. Named Event signal — quick smoke
|
||||
```powershell
|
||||
Invoke-PtSharedEvent -Name 'Peek.Show'
|
||||
```
|
||||
Wakes the resident Peek process (different from CLI back-door — respects current Explorer foreground selection). Used by some framework tests for the "Peek is enabled and listening" assertion.
|
||||
|
||||
## Recipes — a control/observation map, NOT a per-test-case answer key
|
||||
|
||||
> Maps each Peek *capability* to **how to drive it** and **where the result shows**. It does NOT prescribe concrete fixtures/coords/inputs or expected values — design those at runtime from the actual checklist item. Only a real UI/behavior change should force an edit here.
|
||||
|
||||
| # | Capability | Drive (control / command) | Observe (where the result shows) |
|
||||
|---|---|---|---|
|
||||
| 1 | File-type previewer renders (image / text+code / markdown / PDF / HTML / archive / unsupported) | `Peek.UI.exe <fixture>` (entry-path 1) → `winapp ui inspect -w <hwnd> --depth 7` | the type's previewer node present (`ImagePreview Image`; `PreviewBrowser Pane` for dev/text/md/HTML; archive tree for zip; File-Type/Size/Date view for unsupported). Prefer `winapp ui search` for an in-fixture marker over OCR |
|
||||
| 2 | "Open with default app" via button | `winapp ui invoke LaunchAppButton` | a new editor process/window for `<file>` appears (PID diff) |
|
||||
| 3 | "Open with default app" via Enter | `Assert-PtForegroundOrAbort` → `Send-PtChord -Key <Enter>` | same as #2 |
|
||||
| 4 | Pin keeps window position when switching files | Shell COM + Ctrl+Space (entry-path 2) → `winapp ui invoke PinButton` → move window → navigate to next file | window stays at the pinned coordinates |
|
||||
| 5 | Pin position persists across close + reopen | pinned → Esc to close (graceful — **don't `Stop-Process`**, it bypasses the pin-save handler) → reopen via Shell COM + Ctrl+Space | new window opens at the same pinned coordinates |
|
||||
| 6 | Unpin releases the lock; switching file reverts to default | `winapp ui invoke PinButton` again (unpin) → navigate | window moves to the default position |
|
||||
| 7 | Unpinned reopen uses default position | unpinned → Esc-close → reopen | new window at default, not the stale pinned coords |
|
||||
| 8 | `Peek.UI.exe <file>` CLI opens Peek | entry-path 1 | covered by #1 across file types |
|
||||
| 9 | Concurrent Peek sessions don't crash/interfere | launch `Peek.UI.exe` several times on different files, leaving windows open | each spawns its own process/window; no error in `Peek\Logs` |
|
||||
| 10 | Arrow keys cycle between selected files | Shell COM multi-file selection → Ctrl+Space → `Send-PtChord` Right/Left | window title updates to each file in sequence, wraps at the ends |
|
||||
| 11 | Multi-file selection scopes navigation | select a subset of a folder → navigate | only the selected files cycle, not the rest |
|
||||
| 12 | Activation-hotkey reassignment takes effect | edit `Peek\settings.json` `properties.ActivationShortcut` → `Restart-PtRunner` (**not hot-reloaded** — see Gotchas) → press the new chord, then the old chord | new chord opens Peek; old chord does nothing |
|
||||
|
||||
> **Mapping process**: read the actual checklist item → identify the capability → find its row → drive the named control and design your own inputs + assertions for *that* item. If no row matches, it's a NEW capability — drive ad-hoc and add a row (capability + control + observation point; no canned inputs).
|
||||
|
||||
|
||||
|
||||
## BLOCKED triage (single source of truth)
|
||||
|
||||
If the agent only tried the CLI back-door and marked the pin / navigation tests BLOCKED → **misdiagnosis**, try entry-path #2 (Shell.Application COM + Ctrl+Space).
|
||||
|
||||
If the agent tried Shell COM + Ctrl+Space and got `GetForegroundWindow()=0` + `SendInput → ACCESS_DENIED (5)` → **environment**, not framework. The session has no attached input desktop (RDP minimized, screen locked, screensaver, etc.). See `SKILL.md` pitfall #13 and `references/environment-setup.md` for the per-scenario table + powercfg setup commands. Mark BLK-ENV with mitigation citation.
|
||||
|
||||
Both traps were observed in 2026-06-08 sign-off runs; preventing both is now the agent's pre-flight job (`pt-session-diagnose.ps1`).
|
||||
|
||||
## Fixture files needed
|
||||
|
||||
Put these in a workspace `fixtures/` folder before starting:
|
||||
- `small-image.png` (any 200x150 PNG)
|
||||
- `Program.cs` (any C# file)
|
||||
- `readme.md` (markdown with H1 + bold + bullet list)
|
||||
- `test-pdf.pdf` (PDF with embedded text "PDF_FIXTURE_OK" + "PDF_MARKER_42")
|
||||
- `page.html` (HTML with `<h1>` containing "HTMLPEEKMARKER")
|
||||
- `archive.zip` (zip containing 1 small text file)
|
||||
- `unsupported.xyz` (any small binary)
|
||||
- 3 differently-sized images for the pin-position tests (e.g. 320x240, 800x600, 1920x1080)
|
||||
|
||||
## Source citations
|
||||
|
||||
- `<PT-repo>\src\modules\Peek\Peek.UI\PeekXAML\App.xaml.cs:106-134` — CLI arg parsing, `_isFromCli` flag, OnShowPeek call.
|
||||
- `<PT-repo>\src\modules\Peek\Peek.UI\PeekXAML\Models\NavigationManager.cs` — `// TODO: implement navigation` + `if (_isFromCli) return;` guards.
|
||||
- `<PT-repo>\src\common\interop\shared_constants.h` — `ShowPeekEvent` name.
|
||||
|
||||
## Ceiling
|
||||
|
||||
**18/18 = 100%** achievable from a normal interactive admin console session (verified 2026-06-08). The change-shortcut item is PASS-able via the settings.json + runner-restart path — see Recipe 12.
|
||||
|
||||
## Peek-specific gotchas
|
||||
|
||||
- **Activation-shortcut is NOT hot-reloaded.** Editing `Peek\settings.json` `ActivationShortcut` and waiting for the file-watcher debounce does nothing — the centralized keyboard hook only re-registers the chord after `Restart-PtRunner`. Restart after the change AND again after restoring.
|
||||
- **PinButton spawns a `PopupHost` teaching-tip.** Invoking `PinButton` pops a small confirmation flyout (≈192x63) titled `PopupHost` that surfaces *first* in `winapp ui list-windows`. A naive "first HWND" regex grabs the popup, not Peek. Match by title suffix `- Peek` (regex like `HWND (\d+): "([^"]*- Peek)"`) and/or cache the original Peek HWND before invoking PinButton.
|
||||
- **Win11 Notepad tabs/session-restore** muddy the "open-with-default-app" tests (Recipes 2-3): the spawned Notepad restores prior tabs, so the foreground Notepad's title may not show your file. Enumerate all Notepad windows and match `"<file> - Notepad"` explicitly.
|
||||
|
||||
## Don'ts
|
||||
|
||||
- **Don't `Stop-Process PowerToys.Peek.UI -Force`** to close Peek between iterations — bypasses the save handler, breaks the pin-state-persistence tests (Recipes 5, 7). Use Esc / `winapp ui invoke CloseButton`.
|
||||
- **Don't assume CLI back-door supports navigation** — it doesn't (`_isFromCli` guard). For nav tests use Shell COM + Ctrl+Space.
|
||||
- **Don't OCR the previewer surface** when UIA already exposes the correct nodes (`ImagePreview`, `PreviewBrowser`, `LaunchAppButton`, `PinButton`). UIA is more reliable than OCR.
|
||||
@@ -1,114 +0,0 @@
|
||||
# PowerRename — module verification profile
|
||||
|
||||
**PT module**: `PowerRename` (bulk-rename UI launched via Explorer context menu on selected files/folders)
|
||||
**Source**: `<PT-repo>\src\modules\PowerRename\` (PT repo)
|
||||
**Settings file**: `%LOCALAPPDATA%\Microsoft\PowerToys\PowerRename\settings.json`
|
||||
**Logs**: `%LOCALAPPDATA%\Microsoft\PowerToys\PowerRename\Logs\v<ver>\log_<date>.log`
|
||||
**Exe**: `%LOCALAPPDATA%\PowerToys\WinUI3Apps\PowerToys.PowerRename.exe`
|
||||
**Activation**: Explorer right-click → "Rename with PowerRename" (Win11 Tier-1 menu; **no classic HKCR verb on Win11**); optional global hotkey if user-configured
|
||||
**DSC resource**: `Microsoft.PowerToys/PowerRenameSettings`
|
||||
|
||||
## Shared mechanics
|
||||
|
||||
For the synthetic-right-click + context-menu-invoke flow that ALL Explorer-context-menu modules use, see **`references/explorer-context-menu-flow.md`** + **`scripts/pt-explorer-contextmenu.ps1`** (`Test-PtDesktopInteractive`, `Open-PtExplorerContextMenu`, `Invoke-PtContextMenuItem`, `Get-PtContextMenuItems`). That doc covers stability rules, multi-file selection, BLK-ENV handling, and module-caption table. Don't duplicate; cite by section.
|
||||
|
||||
For the Win11 IExplorerCommand vs classic HKCR distinction, see `scripts/pt-shell-verbs.ps1` header — PR is **modern-menu-only on Win11**, so classic-verb enumeration via Shell.Application **will not find it**.
|
||||
|
||||
## Entry-paths (try in order)
|
||||
|
||||
### 1. Direct CLI launch with file args — PREFERRED for UI-driven tests (verified 2026-06-10)
|
||||
```powershell
|
||||
$tmp = New-Item -ItemType Directory -Path "$env:TEMP\pr-fixture-$(Get-Random)"
|
||||
1..3 | ForEach-Object { 'x' | Set-Content "$($tmp.FullName)\file$_.txt" }
|
||||
|
||||
Start-Process "$env:LOCALAPPDATA\PowerToys\WinUI3Apps\PowerToys.PowerRename.exe" `
|
||||
-ArgumentList "$($tmp.FullName)\file1.txt","$($tmp.FullName)\file2.txt","$($tmp.FullName)\file3.txt"
|
||||
|
||||
Start-Sleep -Milliseconds 1500
|
||||
$pr = (winapp ui list-windows -a PowerToys.PowerRename 2>$null | Out-String) -split "`r?`n" |
|
||||
ForEach-Object { if ($_ -match 'HWND (\d+):') { [int64]$matches[1] } } | Select-Object -First 1
|
||||
winapp ui inspect -w $pr --depth 5 -i 2>$null | Out-String | Select-String 'CheckBox "file\d\.txt"'
|
||||
# Expect 3 hits (file1/2/3.txt, [on] by default)
|
||||
```
|
||||
Bypasses the context menu entirely; same code path inside the exe (it parses argv as the file list). **Use for every UI-driven option/regex/preview test** (Recipes 4-12 below).
|
||||
|
||||
### 2. Synthetic right-click + Invoke-PtContextMenuItem — for "menu entry present/absent" assertions (Recipes 1-3)
|
||||
Use the canonical flow from `references/explorer-context-menu-flow.md` Recipe. The menu-presence assertion is the ONE thing the CLI back-door cannot prove (it works even if the menu entry is correctly hidden — the false-positive trap described in that doc).
|
||||
|
||||
```powershell
|
||||
. "$skill\scripts\pt-explorer-contextmenu.ps1"
|
||||
$hwnd = Open-PtExplorerContextMenu -FolderPath 'D:\fixtures' -FileNames 'a.txt'
|
||||
$items = Get-PtContextMenuItems -MenuHwnd $hwnd
|
||||
$has = $items | Where-Object Name -match 'Rename with PowerRename'
|
||||
# assert $has -> entry present
|
||||
```
|
||||
|
||||
### 3. Shell COM classic verb (does NOT work on Win11 stock install)
|
||||
```powershell
|
||||
Invoke-PtShellVerb -Path 'D:\fixtures\a.txt' -NamePattern 'PowerRename' # -> False
|
||||
```
|
||||
Returns False on Win11 because PT registers PR only via IExplorerCommand, not as a classic HKCR shell verb. **Use only for negative checks** (and prefer the synthetic-menu enumeration above, which observes the actual Tier-1 menu).
|
||||
|
||||
## Recipes — a control/observation map, NOT a per-test-case answer key
|
||||
|
||||
> **What this table is (and isn't):** it maps each PowerRename *capability* to **which control drives it** (AutomationId / settings key) and **where the result shows up**. It deliberately does **NOT** prescribe specific Search/Replace inputs or expected-output assertions — those are the agent's job to design from the actual checklist item at runtime. Keeping it input/assertion-free means the table survives checklist-wording changes; only a real UI redesign (renamed/moved control) should force an edit here (as happened to rows 5 & 12 in build 0.100.0).
|
||||
|
||||
| # | Capability | Drive (control / settings key) | Observe (where the result shows) |
|
||||
|---|---|---|---|
|
||||
| 1 | Context-menu entry present when enabled, gone when disabled | master `enabled.PowerRename` flip + `Restart-PtRunner`; synthetic menu (entry-path 2) | `Get-PtContextMenuItems` includes / excludes "Rename with PowerRename" |
|
||||
| 2 | "Show icon on context menu" | `ShowIcon` in `power-rename-settings.json` + relaunch | menu entry shows icon vs text-only (screenshot); or HKCR `Icon` |
|
||||
| 3 | "Appear only in extended menu" | `ExtendedContextMenuOnly` + relaunch | Tier-1 menu hides PR; classic "Show more options" still lists it |
|
||||
| 4 | Any search/replace option toggle (regex, match-all, case-sensitive, autocomplete, last-use) | `winapp ui invoke checkBox_regex` / `checkBox_matchAll` / `checkBox_case` (etc.); re-read `power-rename-settings.json` | the settings key flips **and** the preview behavior changes accordingly |
|
||||
| 5 | Case mode (single-select) | toggle **buttons** `toggleButton_lowerCase` / `upperCase` / `titleCase` / `capitalize` (not a dropdown) | preview column shows case-transformed names |
|
||||
| 6 | Scope: include/exclude Files / Folders / Subfolders | `toggleButton_includeFiles` / `includeFolders` / `includeSubfolders` | excluded row types appear disabled in the preview |
|
||||
| 7 | Apply-to scope: name-only / extension-only | the "Apply to" selector | replacement affects only the name vs only the extension (preview) |
|
||||
| 8 | Enumerate items | `toggleButton_enumItems`; Replace accepts `${start=,increment=,padding=}` tokens | preview shows the substituted counter |
|
||||
| 9 | Datetime tokens | Replace accepts `$DD` `$MMMM` `$YYYY` `$hh` `$mm` `$ss` `$fff` | preview value matches `(Get-Item <file>).CreationTime` formatted the same way |
|
||||
| 10 | Boost library (Perl regex beyond .NET, e.g. lookbehind) | `UseBoostLib` — **read at process start; relaunch PR after toggling** | the Perl-only pattern matches in the preview without error |
|
||||
| 11 | Per-row include/exclude in the preview | invoke a row checkbox to uncheck | the unchecked file is unchanged on disk after Rename |
|
||||
| 12 | Filter preview / select-all (NOT a column-header click — headers `TxtBlock_Original`/`TxtBlock_Renamed` are non-interactive labels) | `btn-filter-XXXX` → `button_showAll` / `button_showRenamed`; `checkBox_selectAll` | visible row set shrinks/grows; all rows toggle on/off |
|
||||
|
||||
> **Mapping process**: read the actual checklist item → identify the capability → find its row → drive the named control and design your own inputs + assertions for *that* item. If no row matches, it's a NEW capability — drive it ad-hoc and add a row (capability + control + observation point, no canned inputs).
|
||||
|
||||
|
||||
|
||||
## Fixture files needed
|
||||
|
||||
In a workspace `fixtures/` folder:
|
||||
- `a.txt`, `b.txt`, `c.txt` — multi-select
|
||||
- `IMG_001.png`, `IMG_002.png`, `IMG_003.png` — regex capture
|
||||
- subfolder `subdir/` with 2 inner files — folder/subfolder exclusion
|
||||
- `Foo_A_A_A.txt` — match-all
|
||||
- `MIXED.txt` — case-sensitive
|
||||
|
||||
Always copy fixtures to a disposable temp folder before running actual rename operations.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **TWO settings files — PR reads `power-rename-settings.json`, NOT `settings.json`** (verified 2026-06-10). `%LOCALAPPDATA%\Microsoft\PowerToys\PowerRename\` holds both: (1) `settings.json` = PT-store, keys `bool_mru_enabled`/`bool_persist_input`/`bool_show_icon_on_menu`/`bool_show_extended_menu`/`bool_use_boost_lib`/`int_max_mru_size` (what `Get-PtModuleSettings` + the Settings UI bind to); (2) `power-rename-settings.json` = the module's own store, keys `ShowIcon`/`ExtendedContextMenuOnly`/`PersistState`/`MRUEnabled`/`MaxMRUSize`/`UseBoostLib` — **this is the file the PR UI exe and the context-menu COM handlers actually read at launch** (`lib/Settings.cpp` `CSettings::Load→ParseJson`). The runner (`dll/dllmain.cpp:301-307`) syncs PT-store→module-store only on a Settings-UI *change event*; the PT-store file can sit stale for days. **To drive ShowIcon / ExtendedContextMenuOnly / MRUEnabled / PersistState / UseBoostLib deterministically, edit `power-rename-settings.json` directly + relaunch PR (or restart runner+Explorer for the menu handlers), then restore.** Map (settings.json key → user-facing toggle): ShowIcon→"Show icon on context menu", ExtendedContextMenuOnly→"Appear only in extended menu", MRUEnabled→autocomplete, PersistState→"Show values from last use", UseBoostLib→"Use Boost library". MRU values live in `search-mru.json`/`replace-mru.json`; last-used (persist) in `power-rename-last-run-data.json`.
|
||||
- **"Show icon on context menu" has no Settings-UI toggle in current builds** — drive it via `power-rename-settings.json` `ShowIcon`. Behavior is observable on the synthetic menu (icon vs text-only); source `PowerRenameContextMenu/dllmain.cpp:73` (`GetIcon→null`).
|
||||
- **The "Appear only in extended menu" classic `#32768` popup is not winapp-enumerable** — assert the Tier-1 *hide* (observed; `dllmain.cpp:108` `ECS_HIDDEN`) and cite `PowerRenameExt.cpp:84` (`E_FAIL` unless `CMF_EXTENDEDVERBS`) for the "still in extended menu" half.
|
||||
- **PR registers on the directory *background* menu too** — the synthetic right-click often lands on background (View/Sort by/Group by/...) yet still shows/hides `Rename with PowerRename`, which is a valid, stable surface for menu-entry / icon-visibility / extended-menu-only present-absent comparisons.
|
||||
- **`set-value` on search/replace DOES fire the preview** (TextChanged works, unlike CmdPal) — Apply button enabling/disabling is a reliable match/no-match signal. The search/replace Edit AutomationIds are random per launch (`txt-textbox-XXXX`); discover them each launch by name (`Edit "Search for"` / `Edit "Replace with"`).
|
||||
- **Preview-row uncheck + column-header invokes need the Preview populated first** — set Search/Replace and wait ~500 ms for the regex engine; otherwise the invokes hit an empty list.
|
||||
- **Boost library is read at PR process start** — close + relaunch PR after toggling.
|
||||
- **Icon-on-menu and extended-only checks prefer registry over screenshot** — read HKCR `Extended` / `Icon` REG_SZ; more reliable + locale-independent.
|
||||
- **Disk mutation is real** — run renames against `$env:TEMP\pr-test-<random>`, not real fixtures.
|
||||
- **COM cache staleness** when re-checking verbs after enable/disable — call `Reset-PtShellComCache` from `scripts/pt-shell-verbs.ps1`.
|
||||
|
||||
## Source citations
|
||||
|
||||
- `<PT-repo>\src\modules\PowerRename\dllmain.cpp` — IExplorerCommand registration (no classic HKCR shadow on Win11).
|
||||
- `<PT-repo>\src\modules\PowerRename\PowerRenameUILib\` — XAML for main PR window (toggle/checkbox AutomationIds).
|
||||
- `<PT-repo>\src\modules\PowerRename\PowerRenameLib\Settings.cpp` — settings.json schema canonical property names.
|
||||
|
||||
## Ceiling
|
||||
|
||||
Expected **18/18 = 100%** from an interactive admin console session. Direct-CLI (#1) covers UI-driven items; synthetic-menu (#2) covers menu-presence assertions.
|
||||
|
||||
## Don'ts
|
||||
|
||||
- **Don't** try `Invoke-PtShellVerb 'PowerRename'` — returns False on Win11 (no classic registration). Use synthetic menu via `Invoke-PtContextMenuItem` or direct-CLI.
|
||||
- **Don't** run rename operations against reusable fixtures — copy to a disposable temp folder.
|
||||
- **Don't** trust screenshot-only for icon-on-menu or extended-only checks — registry inspection is faster + locale-independent.
|
||||
- **Don't** skip the synthetic-menu test for the menu-presence assertion — CLI back-door PASSes even when the menu entry is correctly hidden (false-positive trap described in `references/explorer-context-menu-flow.md`).
|
||||
@@ -1,122 +0,0 @@
|
||||
# Pre-flight checks, bootstrap, and state hygiene
|
||||
|
||||
This doc covers the **agent-runtime** environment probing and lifecycle hooks. Read alongside `SKILL.md` (the playbook) and `references/environment-setup.md` (one-time user env prep).
|
||||
|
||||
## Pre-flight checks (do these first; abort if any fails)
|
||||
|
||||
1. **Admin check** — `Test-PtAdmin` must return the elevation level matching `[ADMIN: YES]` items in the module's checklist. If the module contains `[ADMIN: YES]` items and `Test-PtAdmin` returns `False`, **STOP** and tell the user "this module requires an elevated session". Do NOT silently mark those items BLOCKED-LACK-ADMIN — that hides a fixable env issue.
|
||||
|
||||
2. **PT runner present** — `Test-PtRunnerAdmin` should show the runner exists. If it doesn't exist, start PowerToys (`Start-Process "$env:LOCALAPPDATA\PowerToys\PowerToys.exe"`).
|
||||
|
||||
3. **Module installed** — `Get-PtModuleSettings -ModuleDir <ModuleDir>` (or `Get-CmdPalSettings` for CmdPal) returns non-null.
|
||||
|
||||
4. **Interactive-desktop availability + session attachment** — the single most common cause of false-BLOCKED reports is a session mismatch where the agent runs in an elevated **non-console session** (e.g. RDP that's been disconnected/minimized, fast user switching, run-as-different-user, or scheduled-task-with-highest-privilege). In that scenario `Test-PtAdmin=True` but `GetForegroundWindow()=0` and `SendInput` returns `ERROR_ACCESS_DENIED (5)` — input injection cannot reach the active desktop.
|
||||
|
||||
```powershell
|
||||
# Sessions
|
||||
$agentSession = [Diagnostics.Process]::GetCurrentProcess().SessionId
|
||||
$consoleSession = (Get-Process explorer -EA SilentlyContinue | Select-Object -First 1).SessionId
|
||||
"Agent session=$agentSession Console explorer session=$consoleSession"
|
||||
|
||||
# Foreground + Shell COM probe (use scripts/pt-session-diagnose.ps1 for the full version)
|
||||
Add-Type 'using System; using System.Runtime.InteropServices; public class FG4 { [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); }'
|
||||
$hasFg = $false
|
||||
for ($i = 0; $i -lt 5; $i++) { if ([FG4]::GetForegroundWindow() -ne [IntPtr]::Zero) { $hasFg=$true; break }; Start-Sleep -Milliseconds 200 }
|
||||
$shellOk = $false
|
||||
try { $shellOk = (@((New-Object -ComObject Shell.Application).Windows()).Count -ge 0) } catch {}
|
||||
"Interactive desktop: ForegroundOk=$hasFg ShellComOk=$shellOk"
|
||||
|
||||
if (-not $hasFg -and $agentSession -ne $consoleSession) {
|
||||
Write-Host "===========================================================" -ForegroundColor Red
|
||||
Write-Host "NON-INTERACTIVE SESSION DETECTED" -ForegroundColor Red
|
||||
Write-Host "Agent is in Session $agentSession but the active console is Session $consoleSession." -ForegroundColor Red
|
||||
Write-Host "SendInput, global hotkeys, and arrow-key navigation will NOT work here." -ForegroundColor Red
|
||||
Write-Host "Items requiring input injection will be marked BLK-ENV up-front." -ForegroundColor Red
|
||||
Write-Host "Mitigation: see references/environment-setup.md, or relaunch in console session:" -ForegroundColor Yellow
|
||||
Write-Host " psexec -accepteula -h -i $consoleSession -s pwsh.exe" -ForegroundColor Yellow
|
||||
Write-Host "===========================================================" -ForegroundColor Red
|
||||
# Continue verification — schema/UIA/CLI-based tests still produce real evidence
|
||||
}
|
||||
```
|
||||
|
||||
**Key distinction** (all rows assume `Admin=True`):
|
||||
- **ForegroundOk + ShellComOk** → Everything works — interactive elevated session.
|
||||
- **ShellComOk only (ForegroundOk false)** → Non-interactive (e.g. Session ≠ console, RDP minimized, screen locked, screensaver). Only schema / UIA-invoke / CLI / Named-Event tests work. Mark input-injection items as `BLK-ENV` and **cite `references/environment-setup.md` in the report** so the user can fix env and re-run.
|
||||
- **Neither (ShellComOk false)** → Session 0 / service context — even Shell COM fails. Very few tests possible.
|
||||
|
||||
5. **Discipline: try AT LEAST 2 distinct entry-paths before marking BLOCKED.** For Peek/FZ/Workspaces/Image Resizer/PowerRename/File Locksmith specifically, the obvious entry-path is the global hotkey but Shell.Application COM driving Explorer also works — see per-module profiles under `references/modules/`. Marking BLOCKED after trying only the CLI launch (a common trap) hides easily-PASS-able items in an interactive session.
|
||||
|
||||
## Bootstrap (paste at start of your verification script)
|
||||
|
||||
```powershell
|
||||
$skill = '<this skill folder>' # the folder containing SKILL.md
|
||||
Get-ChildItem "$skill\scripts" -Filter '*.ps1' | ForEach-Object { . $_.FullName }
|
||||
|
||||
$workspace = "$env:TEMP\verify-<Module>-$(Get-Date -Format yyyyMMdd-HHmmss)"
|
||||
New-Item -ItemType Directory -Path $workspace, "$workspace\artifacts" | Out-Null
|
||||
$report = "$workspace\verify-<Module>.md"
|
||||
|
||||
"# <Module> verification — $(Get-Date -Format 'yyyy-MM-dd HH:mm')" | Set-Content $report
|
||||
"" | Add-Content $report
|
||||
"## Pre-flight" | Add-Content $report
|
||||
"- IsAdmin: $(Test-PtAdmin)" | Add-Content $report
|
||||
"- PT runner: PID=$((Test-PtRunnerAdmin).Pid) Elevated=$((Test-PtRunnerAdmin).Elevated)" | Add-Content $report
|
||||
|
||||
# Then proceed with pre-flight checks #4-#6 above and write their results into the report.
|
||||
```
|
||||
|
||||
## State hygiene (CRITICAL — always restore)
|
||||
|
||||
Wrap any settings/registry mutation in try/finally:
|
||||
|
||||
```powershell
|
||||
# Per-item: settings.json edits
|
||||
$bk = Backup-PtModuleSettings -ModuleDir <ModuleDir>
|
||||
try {
|
||||
# ... mutate + assert ...
|
||||
} finally {
|
||||
Restore-PtModuleSettings -ModuleDir <ModuleDir> -BackupPath $bk
|
||||
}
|
||||
|
||||
# After GPO/admin tests
|
||||
Remove-Item HKLM:\Software\Policies\PowerToys -Recurse -Force -EA SilentlyContinue
|
||||
Remove-Item HKCU:\Software\Policies\PowerToys -Recurse -Force -EA SilentlyContinue
|
||||
Remove-Item 'C:\Windows\PolicyDefinitions\PowerToys.admx' -Force -EA SilentlyContinue
|
||||
Remove-Item 'C:\Windows\PolicyDefinitions\en-US\PowerToys.adml' -Force -EA SilentlyContinue
|
||||
|
||||
# Spawned processes (notepad, regedit, etc.) — kill by PID, not by name
|
||||
foreach ($pid in $spawnedPids) { Stop-Process -Id $pid -Force -EA SilentlyContinue }
|
||||
```
|
||||
|
||||
## Final wrap-up (run AFTER all per-item tables are written)
|
||||
|
||||
1. **Run state-hygiene cleanup** above for everything that wasn't restored per-item.
|
||||
2. **Write the top-of-report summary** per `references/reporting-format.md` §B.
|
||||
3. **Write the §G Retrospective** — reflect on the run itself: every friction (classified by source + severity + minutes/attempts cost + suggested fix), or `Everything was smooth — no friction encountered.` See `references/reporting-format.md` §G. Don't skip it; it's how the skill improves.
|
||||
4. **Verify every screenshot referenced in the report actually exists on disk** (before the move, while paths still resolve under `$workspace`):
|
||||
```powershell
|
||||
$missing = Get-Content $report | Select-String 'artifacts/L\d+/step-\d+-[^\.\s]+\.(png|txt|log|json|ps1)' -AllMatches |
|
||||
ForEach-Object { $_.Matches.Value } | Sort-Object -Unique |
|
||||
Where-Object { -not (Test-Path (Join-Path $workspace $_)) }
|
||||
if ($missing) { Write-Warning "Missing artifacts: $($missing -join ', ')" }
|
||||
```
|
||||
5. **Move the workspace to the sign-off archive** (LAST step, after the report + artifact check pass):
|
||||
```powershell
|
||||
$signoff = "$env:OneDrive\PowerToys\Module-Signoff"
|
||||
New-Item -ItemType Directory -Path $signoff -Force | Out-Null
|
||||
$final = Join-Path $signoff (Split-Path $workspace -Leaf)
|
||||
Move-Item -Path $workspace -Destination $final -Force
|
||||
$report = Join-Path $final (Split-Path $report -Leaf)
|
||||
```
|
||||
The report uses **relative** `artifacts/…` paths, so the whole tree moves intact.
|
||||
6. **Print the FINAL (moved) report path** as the very last line of your response — the `…\Module-Signoff\verify-<Module>-<timestamp>\verify-<Module>.md` path, NOT the temp path.
|
||||
|
||||
## Hard rules
|
||||
|
||||
- **Never silently send keys via SendInput** to a target window without first calling `Assert-PtForegroundOrAbort -AppId <id>`. Keys silently leak to your terminal if the target isn't foreground.
|
||||
- **Never mark BLOCKED without trying at least 2 distinct entry-paths from the drive-stack** (SKILL.md §2). If you can't drive the item, name the specific obstacle (not "I can't").
|
||||
- **Never assume any external repo is cloned locally.** The helpers under `scripts/` are self-contained. Use `Test-Path` guards before referencing any external path.
|
||||
- **Never invent test steps for a `[CLARITY: VAGUE-*]` item** — mark it **FAIL (cause: checklist-ambiguous)** and quote the original wording so the user can fix the checklist. The checklist is test code; an undefinable test is a broken test.
|
||||
- **Always restore state** before exiting (even on error). State hygiene wraps every mutation in try/finally.
|
||||
- **Separate the two FAIL causes**: *product* FAILs are bugs to file; *checklist* FAILs (stale feature or ambiguous spec) are items to rewrite/prune. If a large share of a module's items are checklist-FAILs, the checklist needs an overhaul before re-verifying — don't punt drivable items into a FAIL.
|
||||
- **Never continue past 3 consecutive errors against the same item** — mark it BLOCKED with the concrete symptom/obstacle and move on. Per-item budget is ~5 minutes; if stuck longer, it's BLOCKED (name the wall).
|
||||
@@ -1,45 +0,0 @@
|
||||
# Environment Variables — PowerToys release checklist
|
||||
|
||||
> Source: split from `release-checklist-annotated.md` (generated 2026-06-06). One module per file.
|
||||
|
||||
## Legend
|
||||
|
||||
Each item is annotated with two metadata tags:
|
||||
|
||||
**Admin requirement**:
|
||||
- `[ADMIN: NO]` - runnable from a standard (non-elevated) shell
|
||||
- `[ADMIN: YES]` - requires elevated session (writes to HKLM, %WinDir%\System32, MSI install, GPO templates, etc.)
|
||||
- `[ADMIN: COND]` - conditional - the basic case is non-admin but specific sub-cases require admin (e.g. "test with elevated target app", "Restart as admin" variants)
|
||||
|
||||
**Clarity**:
|
||||
- (no marker) - clear, has explicit assert
|
||||
- `[CLARITY: VAGUE-NO-STEPS]` - original wording is just a module/feature name without procedural steps
|
||||
- `[CLARITY: VAGUE-NO-ASSERT]` - original wording describes an action but does not state the expected outcome
|
||||
- `[CLARITY: VAGUE-AMBIGUOUS]` - original wording uses vague verbs like "works" without a measurable outcome
|
||||
- `[REWRITTEN]` - original wording was vague; this checklist has rewritten the description to be concrete. Original wording preserved in italics below the item.
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables (20 items)
|
||||
|
||||
- [ ] **[ADMIN: YES]** (L791) Launch as administrator ON - Launch Environment Variables and confirm that SYSTEM variables ARE editable and Add variable button is enabled
|
||||
- [ ] **[ADMIN: YES]** (L792) Launch as administrator OFF - Launch Environment Variables and confirm that SYSTEM variables ARE NOT editable and Add variable button is disabled
|
||||
- [ ] **[ADMIN: NO]** (L795) Add new User variable. Open OS Environment variables window and confirm that added variable is there. Also, confirm that it's added to "Applied variables" list.
|
||||
- [ ] **[ADMIN: NO]** (L796) Edit one User variable. Open OS Environment variables window and confirm that variable is changed. Also, confirm that change is applied to "Applied variables" list.
|
||||
- [ ] **[ADMIN: NO]** (L797) Remove one User variable. Open OS Environment variables window and confirm that variable is removed. Also, confirm that variable is removed from "Applied variables" list.
|
||||
- [ ] **[ADMIN: NO]** (L801) Add new profile with no variables and name it "Test_profile_1" (referenced below by name)
|
||||
- [ ] **[ADMIN: NO]** (L802) Edit "Test_profile_1": Add one new variable to profile e.g. name: "profile_1_variable_1" value: "profile_1_value_1"
|
||||
- [ ] **[ADMIN: NO]** (L803) Add new profile "Test_profile_2": From "Add profile dialog" add two new variables (profile_2_variable_1:profile_2_value_1 and profile_2_variable_2:profile_2_value_2). Set profile to enabled and click Save. Open OS Environment variables window and confirm that all variables from the profile are applied correctly. Also, confirm that "Applied variables" list contains all variables from the profile.
|
||||
- [ ] **[ADMIN: NO]** (L804) Apply "Test_profile_1" while "Test_profile_2" is still aplpied. Open OS Environment variables window and confirm that all variables from Test_profile_2 are unapplied and that all variables from Test_profile_1 are applied. Also, confirm that state of "Applied variables" list is updated correctly.
|
||||
- [ ] **[ADMIN: NO]** (L805) Unapply applied profile. Open OS Environment variables window and confirm that all variables from the profile are unapplied correctly. Also, confirm that "Applied variables" list does not contain variables from the profile.
|
||||
- [ ] **[ADMIN: NO]** (L808) To "Test_profile_1" add one existing variable from USER variables, e.g. TMP. After adding, change it's value to e.g "test_TMP" (or manually add variable named TMP with value test_TMP).
|
||||
- [ ] **[ADMIN: NO]** (L809) Apply "Test_profile_1". Open OS Environment variables window and confirm that TMP variable in USER variables has value "test_TMP". Confirm that there is backup variable "TMP_PowerToys_Test_profile_1" with original value of TMP var. Also, confirm that "Applied variables" list is updated correctly - there is TMP profile variable, and backup User variable..
|
||||
- [ ] **[ADMIN: NO]** (L810) Unapply "Test_profile_1". Open OS Environment variables window and confirm that TMP variable in USER variable has original value and that there is no backup variable. Also, confirm that "Applied variables" list is updated correctly.
|
||||
- [ ] **[ADMIN: NO]** (L813) In "Applied variables" list confirm that PATH variable is shown properly: value of USER Path concatenated to the end of SYSTEM Path.
|
||||
- [ ] **[ADMIN: NO]** (L814) To "Test_profile_1" add variable named PATH with value "path1;path2;path3" and click Save. Confirm that PATH variable in profile is shown as list (list of 3 values and not as path1;path2;path3).
|
||||
- [ ] **[ADMIN: NO]** (L815) Edit PATH variable from "Test_profile_1". Try different options from ... menu (Delete, Move up, Move down, etc...). Click Save.
|
||||
- [ ] **[ADMIN: NO]** (L816) Apply "Test_profile_1". Open OS Environment variables window and confirm that profile is applied correctly - Path value and backup variable. Also, in "Applied variables" list check that Path variable has correct value: value of profile PATH concatenated to the end of SYSTEM Path.
|
||||
- [ ] **[ADMIN: NO]** (L819) Close the app and reopen it. Confirm that the state of the app is the same as before closing.
|
||||
- [ ] **[ADMIN: NO]** (L821) "Test_profile_1" should still be applied (if not apply it). Delete "Test_profile_1". Confirm that profile is unapplied (both in OS Environment variables window and "Applied variables" list).
|
||||
- [ ] **[ADMIN: NO]** (L822) Delete "Test_profile_2". Check profiles.json file and confirm that both profiles are gone.
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
# File Locksmith — PowerToys release checklist
|
||||
|
||||
> Source: split from `release-checklist-annotated.md` (generated 2026-06-06). One module per file.
|
||||
|
||||
## Legend
|
||||
|
||||
Each item is annotated with two metadata tags:
|
||||
|
||||
**Admin requirement**:
|
||||
- `[ADMIN: NO]` - runnable from a standard (non-elevated) shell
|
||||
- `[ADMIN: YES]` - requires elevated session (writes to HKLM, %WinDir%\System32, MSI install, GPO templates, etc.)
|
||||
- `[ADMIN: COND]` - conditional - the basic case is non-admin but specific sub-cases require admin (e.g. "test with elevated target app", "Restart as admin" variants)
|
||||
|
||||
**Clarity**:
|
||||
- (no marker) - clear, has explicit assert
|
||||
- `[CLARITY: VAGUE-NO-STEPS]` - original wording is just a module/feature name without procedural steps
|
||||
- `[CLARITY: VAGUE-NO-ASSERT]` - original wording describes an action but does not state the expected outcome
|
||||
- `[CLARITY: VAGUE-AMBIGUOUS]` - original wording uses vague verbs like "works" without a measurable outcome
|
||||
- `[REWRITTEN]` - original wording was vague; this checklist has rewritten the description to be concrete. Original wording preserved in italics below the item.
|
||||
|
||||
---
|
||||
|
||||
## File Locksmith (10 items)
|
||||
|
||||
- [ ] **[ADMIN: COND]** (L641) Right-click the executable file, select "Unlock with File Locksmith" and verify it shows up. (2 entries will show, since the installer starts two processes)
|
||||
- [ ] **[ADMIN: COND]** (L642) End the tasks in File Locksmith UI and verify that closes the installer.
|
||||
- [ ] **[ADMIN: COND]** (L643) Start the installer executable again and press the Refresh button in File Locksmith UI. It should find new processes using the files.
|
||||
- [ ] **[ADMIN: COND]** (L644) Close the installer window and verify the processes are delisted from the File Locksmith UI. Close the window
|
||||
- [ ] **[ADMIN: COND]** (L646) Right click the directory where the executable is located, select "Unlock with File Locksmith" and verify it shows up.
|
||||
- [ ] **[ADMIN: COND]** (L647) Right click the drive where the executable is located, select "Unlock with File Locksmith" and verify it shows up. You can close the PowerToys installer now.
|
||||
- [ ] **[ADMIN: COND]** (L649) Right click "Program Files", select "Unlock with File Locksmith" and verify "PowerToys.exe" doesn't show up.
|
||||
- [ ] **[ADMIN: YES]** (L650) Press the File Locksmith "Restart as an administrator" button and verify "PowerToys.exe" shows up.
|
||||
- [ ] **[ADMIN: YES]** (L651) Right-click the drive where Windows is installed, select "Unlock with File Locksmith" and scroll down and up, verify File Locksmith doesn't crash with all those entries being shown. Repeat after clicking the File Locksmith "Restart as an administrator" button.
|
||||
- [ ] **[ADMIN: COND]** (L652) Disable File Locksmith in Settings and verify the context menu entry no longer appears.
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
# Image Resizer — PowerToys release checklist
|
||||
|
||||
> Source: split from `release-checklist-annotated.md` (generated 2026-06-06). One module per file.
|
||||
|
||||
## Legend
|
||||
|
||||
Each item is annotated with two metadata tags:
|
||||
|
||||
**Admin requirement**:
|
||||
- `[ADMIN: NO]` - runnable from a standard (non-elevated) shell
|
||||
- `[ADMIN: YES]` - requires elevated session (writes to HKLM, %WinDir%\System32, MSI install, GPO templates, etc.)
|
||||
- `[ADMIN: COND]` - conditional - the basic case is non-admin but specific sub-cases require admin (e.g. "test with elevated target app", "Restart as admin" variants)
|
||||
|
||||
**Clarity**:
|
||||
- (no marker) - clear, has explicit assert
|
||||
- `[CLARITY: VAGUE-NO-STEPS]` - original wording is just a module/feature name without procedural steps
|
||||
- `[CLARITY: VAGUE-NO-ASSERT]` - original wording describes an action but does not state the expected outcome
|
||||
- `[CLARITY: VAGUE-AMBIGUOUS]` - original wording uses vague verbs like "works" without a measurable outcome
|
||||
- `[REWRITTEN]` - original wording was vague; this checklist has rewritten the description to be concrete. Original wording preserved in italics below the item.
|
||||
|
||||
---
|
||||
|
||||
## Image Resizer (18 items)
|
||||
|
||||
- [ ] **[ADMIN: NO]** (L309) Disable the Image Resizer and check that `Resize with Image Resizer` is absent in the context menu
|
||||
- [ ] **[ADMIN: NO]** (L310) Enable the Image Resizer and check that `Resize with Image Resizer` is present in the context menu (both Win11 modern and old menus)
|
||||
- [ ] **[ADMIN: NO]** (L311) Remove one image size and add a custom image size. Open the Image Resize window from the context menu and verify changes are populated
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L312) Resize one image
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L313) Resize multiple images
|
||||
- [ ] **[ADMIN: NO]** (L314) Open image resizer to resize a .gif and verify "Gif files with animations may not be correctly resized." warning appears
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L316) Resize images with Fill option
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L317) Resize images with Fit option
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L318) Resize images with Stretch option
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L320) Resize using dimension Centimeters
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L321) Resize using dimension Inches
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L322) Resize using dimension Percents
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L323) Resize using dimension Pixels
|
||||
- [ ] **[ADMIN: NO]** (L325) Change Filename format to %1 - %2 - %3 - %4 - %5 - %6 and verify applied
|
||||
- [ ] **[ADMIN: NO]** (L326) Check Use original date modified and verify modified date not changed for resized
|
||||
- [ ] **[ADMIN: NO]** (L327) Check Make pictures smaller but not larger and verify smaller pictures not resized
|
||||
- [ ] **[ADMIN: NO]** (L328) Check Resize the original pictures (don't create copies) and verify original is resized
|
||||
- [ ] **[ADMIN: NO]** (L329) Uncheck Ignore the orientation and verify swapped W/H actually resizes if W!=H
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
# Release checklist — per-module index
|
||||
|
||||
One file per module; a verification run loads only its module's file.
|
||||
|
||||
> **Scope:** only modules that have been verified end-to-end (with a sign-off report) are checked in here so far. The remaining modules' checklists will be added as each is verified.
|
||||
|
||||
| Module | Items | File |
|
||||
|---|---:|---|
|
||||
| Environment Variables | 20 | `environment-variables.md` |
|
||||
| File Locksmith | 10 | `file-locksmith.md` |
|
||||
| Image Resizer | 18 | `image-resizer.md` |
|
||||
| New+ | 9 | `new-plus.md` |
|
||||
| Peek | 18 | `peek.md` |
|
||||
| PowerRename | 18 | `power-rename.md` |
|
||||
@@ -1,34 +0,0 @@
|
||||
# New+ — PowerToys release checklist
|
||||
|
||||
> Source: split from `release-checklist-annotated.md` (generated 2026-06-06). One module per file.
|
||||
|
||||
## Legend
|
||||
|
||||
Each item is annotated with two metadata tags:
|
||||
|
||||
**Admin requirement**:
|
||||
- `[ADMIN: NO]` - runnable from a standard (non-elevated) shell
|
||||
- `[ADMIN: YES]` - requires elevated session (writes to HKLM, %WinDir%\System32, MSI install, GPO templates, etc.)
|
||||
- `[ADMIN: COND]` - conditional - the basic case is non-admin but specific sub-cases require admin (e.g. "test with elevated target app", "Restart as admin" variants)
|
||||
|
||||
**Clarity**:
|
||||
- (no marker) - clear, has explicit assert
|
||||
- `[CLARITY: VAGUE-NO-STEPS]` - original wording is just a module/feature name without procedural steps
|
||||
- `[CLARITY: VAGUE-NO-ASSERT]` - original wording describes an action but does not state the expected outcome
|
||||
- `[CLARITY: VAGUE-AMBIGUOUS]` - original wording uses vague verbs like "works" without a measurable outcome
|
||||
- `[REWRITTEN]` - original wording was vague; this checklist has rewritten the description to be concrete. Original wording preserved in italics below the item.
|
||||
|
||||
---
|
||||
|
||||
## New+ (9 items)
|
||||
|
||||
- [ ] **[ADMIN: NO]** (L969) Verify NewPlus menu is in Explorer context menu. (Windows 11 tier 1 context menu only. May need Explorer restart.)
|
||||
- [ ] **[ADMIN: NO]** (L971) Verify NewPlus menu is not in Explorer context menu.
|
||||
- [ ] **[ADMIN: NO]** (L973) Verify the folder is created and empty.
|
||||
- [ ] **[ADMIN: NO]** (L974) Copy a file to the templates folder, verify it's added to the New+ context menu and that if you select it the file is created.
|
||||
- [ ] **[ADMIN: NO]** (L975) Copy a folder with files inside to the templates folder, verify it's added to the New+ context menu and that if you select it the folder and files inside are created.
|
||||
- [ ] **[ADMIN: NO]** (L976) Delete all files and folders from inside the templates folder. Verify that no templates are available in the context menu.
|
||||
- [ ] **[ADMIN: NO]** (L977) Disable and re-Enable New+ while the templates folder is still empty. Verify the default templates were copied over and are available in the context menu.
|
||||
- [ ] **[ADMIN: NO]** (L979) Test the "Hide template filename extension" option in Settings.
|
||||
- [ ] **[ADMIN: NO]** (L980) Test the "Hide template filename starting digits, spaces and dots" option in Settings.
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
# Peek — PowerToys release checklist
|
||||
|
||||
> Source: split from `release-checklist-annotated.md` (generated 2026-06-06). One module per file.
|
||||
|
||||
## Legend
|
||||
|
||||
Each item is annotated with two metadata tags:
|
||||
|
||||
**Admin requirement**:
|
||||
- `[ADMIN: NO]` - runnable from a standard (non-elevated) shell
|
||||
- `[ADMIN: YES]` - requires elevated session (writes to HKLM, %WinDir%\System32, MSI install, GPO templates, etc.)
|
||||
- `[ADMIN: COND]` - conditional - the basic case is non-admin but specific sub-cases require admin (e.g. "test with elevated target app", "Restart as admin" variants)
|
||||
|
||||
**Clarity**:
|
||||
- (no marker) - clear, has explicit assert
|
||||
- `[CLARITY: VAGUE-NO-STEPS]` - original wording is just a module/feature name without procedural steps
|
||||
- `[CLARITY: VAGUE-NO-ASSERT]` - original wording describes an action but does not state the expected outcome
|
||||
- `[CLARITY: VAGUE-AMBIGUOUS]` - original wording uses vague verbs like "works" without a measurable outcome
|
||||
- `[REWRITTEN]` - original wording was vague; this checklist has rewritten the description to be concrete. Original wording preserved in italics below the item.
|
||||
|
||||
---
|
||||
|
||||
## Peek (18 items)
|
||||
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L697) Image
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L698) Text or dev file
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L699) Markdown file
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L700) PDF
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L701) HTML
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L702) Archive files (.zip, .tar, .rar)
|
||||
- [ ] **[ADMIN: NO]** (L703) Any other not mentioned file (.exe for example) to verify the unsupported file view is shown
|
||||
- [ ] **[ADMIN: NO]** (L706) Pin the window, switch between images of different size, verify the window stays at the same place and the same size.
|
||||
- [ ] **[ADMIN: NO]** (L707) Pin the window, close and reopen Peek, verify the new window is opened at the same place and the same size as before.
|
||||
- [ ] **[ADMIN: NO]** (L708) Unpin the window, switch to a different file, verify the window is moved to the default place.
|
||||
- [ ] **[ADMIN: NO]** (L709) Unpin the window, close and reopen Peek, verify the new window is opened on the default place.
|
||||
- [ ] **[ADMIN: NO]** (L712) By clicking a button.
|
||||
- [ ] **[ADMIN: NO]** (L713) By pressing enter.
|
||||
- [ ] **[ADMIN: NO]** (L716) Can use peek command to peek files
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L717) Peek can work without problem when a peek session is on
|
||||
- [ ] **[ADMIN: NO]** (L719) Switch between files in the folder using `LeftArrow` and `RightArrow`, verify you can switch between all files in the folder.
|
||||
- [ ] **[ADMIN: NO]** (L720) Open multiple files, verify you can switch only between selected files.
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-AMBIGUOUS]** (L721) Change the shortcut, verify the new one works.
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
# PowerRename — PowerToys release checklist
|
||||
|
||||
> Source: split from `release-checklist-annotated.md` (generated 2026-06-06). One module per file.
|
||||
|
||||
## Legend
|
||||
|
||||
Each item is annotated with two metadata tags:
|
||||
|
||||
**Admin requirement**:
|
||||
- `[ADMIN: NO]` - runnable from a standard (non-elevated) shell
|
||||
- `[ADMIN: YES]` - requires elevated session (writes to HKLM, %WinDir%\System32, MSI install, GPO templates, etc.)
|
||||
- `[ADMIN: COND]` - conditional - the basic case is non-admin but specific sub-cases require admin (e.g. "test with elevated target app", "Restart as admin" variants)
|
||||
|
||||
**Clarity**:
|
||||
- (no marker) - clear, has explicit assert
|
||||
- `[CLARITY: VAGUE-NO-STEPS]` - original wording is just a module/feature name without procedural steps
|
||||
- `[CLARITY: VAGUE-NO-ASSERT]` - original wording describes an action but does not state the expected outcome
|
||||
- `[CLARITY: VAGUE-AMBIGUOUS]` - original wording uses vague verbs like "works" without a measurable outcome
|
||||
- `[REWRITTEN]` - original wording was vague; this checklist has rewritten the description to be concrete. Original wording preserved in italics below the item.
|
||||
|
||||
---
|
||||
|
||||
## PowerRename (18 items)
|
||||
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-AMBIGUOUS]** (L393) Check if disable and enable of the module works. (On Win11) Check if both old context menu and Win11 tier1 context menu items are present when module is enabled.
|
||||
- [ ] **[ADMIN: NO]** (L394) Check that with the `Show icon on context menu` icon is shown and vice versa.
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-AMBIGUOUS]** (L395) Check if `Appear only in extended context menu` works.
|
||||
- [ ] **[ADMIN: NO]** (L396) Enable/disable autocomplete.
|
||||
- [ ] **[ADMIN: NO]** (L397) Enable/disable `Show values from last use`.
|
||||
- [ ] **[ADMIN: NO]** (L399) Make Uppercase/Lowercase/Titlecase (could be selected only one at the time)
|
||||
- [ ] **[ADMIN: NO]** (L400) Exclude Folders/Files/Subfolder Items (could be selected several)
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L401) Item Name/Extension Only (one at the time)
|
||||
- [ ] **[ADMIN: NO]** (L402) Enumerate Items. Test advanced enumeration using different values for every field ${start=10,increment=2,padding=4}.
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L403) Case Sensitive
|
||||
- [ ] **[ADMIN: NO]** (L404) Match All Occurrences. If checked, all matches of text in the `Search` field will be replaced with the Replace text. Otherwise, only the first instance of the `Search` for text in the file name will be replaced (left to right).
|
||||
- [ ] **[ADMIN: NO]** (L406) Search with an expression (e.g. `(.*).png`)
|
||||
- [ ] **[ADMIN: NO]** (L407) Replace with an expression (e.g. `foo_$1.png`)
|
||||
- [ ] **[ADMIN: NO] [CLARITY: VAGUE-NO-STEPS]** (L408) Replace using file creation date and time (e.g. `$hh-$mm-$ss-$fff` `$DD_$MMMM_$YYYY`)
|
||||
- [ ] **[ADMIN: NO]** (L409) Turn on `Use Boost library` and test with Perl Regular Expression Syntax (e.g. `(?<=t)est`)
|
||||
- [ ] **[ADMIN: NO]** (L411) In the `preview` window uncheck some items to exclude them from renaming.
|
||||
- [ ] **[ADMIN: NO]** (L412) Use the **Filter** (funnel) button above the file list → choose "Only show files that will be renamed" / "Show all files" to filter the preview.
|
||||
- [ ] **[ADMIN: NO]** (L413) Use the **Select/deselect all** checkbox above the file list to toggle all rows checked/unchecked.
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
# Reporting format
|
||||
|
||||
This doc defines the **required** report shape for every per-module verification run. Modeled on `PR-validation\Round1\PR-47211-validation\report.md` style — table-driven, reproducible, no prose narratives.
|
||||
|
||||
## §A — Per-item table (one per checklist item)
|
||||
|
||||
```markdown
|
||||
## Item L<line_num> — <verbatim description from the module's checklist> — **<PASS|FAIL|BLOCKED>** <emoji>
|
||||
|
||||
**Admin**: <NO|COND|YES> | **Clarity**: <CLEAR|VAGUE-*|REWRITTEN> | **Category**: <PASS: verification method (free text) · FAIL: cause = product | checklist-stale | checklist-ambiguous · BLOCKED: a BLK-* reason>
|
||||
|
||||
### Verification steps performed
|
||||
|
||||
| # | Step | winapp / probe commands | Evidence / result |
|
||||
|---|---|---|---|
|
||||
| 1 | <what step 1 does> | `<exact command>`<br>`<another command if multiple>` | <what you observed; reference artifact filename> |
|
||||
| 2 | <what step 2 does> | `<command>` | <evidence>; screenshot: `artifacts/L<line>/step-02-<name>.png` |
|
||||
| 3 | ... | ... | ... |
|
||||
|
||||
### Artifacts produced
|
||||
- `artifacts/L<line>/step-01-<name>.png` — <one-line description>
|
||||
- `artifacts/L<line>/step-02-<name>.txt` — full inspect dump
|
||||
- ...
|
||||
|
||||
### Verdict reasoning
|
||||
- ✅ <assertion 1 that PASSed, with reference to the line of code / settings key / log line that proves it>
|
||||
- ✅ <assertion 2>
|
||||
- ❌ <if BLOCKED, the specific obstacle: "BLK-HARDWARE because MWB needs 2 physical PCs; this session has 1 ([System.Windows.Forms.Screen]::AllScreens.Count = 1)">
|
||||
|
||||
### Caveats (optional)
|
||||
- <Any deviation from the user-documented flow, e.g. "Tested via settings.json write rather than UI checkbox because SelectionItemPattern.Select clobbers other selections in ListView.">
|
||||
```
|
||||
|
||||
## §B — Top-of-report summary (write LAST, after all per-item tables)
|
||||
|
||||
```markdown
|
||||
# <Module> verification report — <YYYY-MM-DD HH:MM>
|
||||
|
||||
## Summary
|
||||
- **PASS**: <n> · **FAIL (product)**: <n> · **FAIL (checklist)**: <n> · **BLOCKED**: <n> · **Total**: <n> · **PASS%**: <n>
|
||||
- **Top blocker categories**: <category>: <count>, <category>: <count>, ...
|
||||
- **Items needing follow-up**: L<line> (<reason>), L<line> (<reason>), ...
|
||||
- **State mutations performed + restored**: <count> settings.json edits restored, <count> registry keys removed, <count> fixture files deleted
|
||||
|
||||
## Pre-flight
|
||||
- IsAdmin: <true|false>
|
||||
- PT runner: PID=<n> Elevated=<true|false>
|
||||
- <Module> settings file: <path> (exists=<true|false>)
|
||||
- Interactive desktop: ForegroundOk=<true|false> ShellComOk=<true|false>
|
||||
|
||||
## Items
|
||||
<all per-item tables here, in line_num order>
|
||||
|
||||
## Cleanup performed
|
||||
- <list of every restore action taken>
|
||||
|
||||
## Retrospective (self-reflection on the run — write LAST)
|
||||
<Per §G. If the whole run was frictionless, write exactly: **Everything was smooth — no friction encountered.**>
|
||||
```
|
||||
|
||||
## §C — Required rules for step tables
|
||||
|
||||
1. **Every `winapp ui ...` command goes in the "winapp / probe commands" cell, verbatim, in backticks**, including `-w <hwnd>` / `-a <appId>` arguments and full selector strings. Reviewers will paste these into their own shell to reproduce.
|
||||
2. **Every screenshot path goes in the "Evidence" cell** of the step that produced it, formatted as `screenshot: artifacts/L<line>/step-NN-<name>.png`. Never embed screenshots as `` in the table body (breaks GitHub markdown rendering inside cells); just give the path.
|
||||
3. **If a step has multiple commands**, separate them in the same cell with `<br>` so they render as one cell with multiple lines.
|
||||
4. **PowerShell scriptlets > 3 lines**: write them to a separate `.ps1` in the artifacts folder and reference as ``script: `artifacts/L<line>/step-NN.ps1` `` in the cell. Keep the table cell to 1-3 lines.
|
||||
5. **`—` (em dash) is allowed for non-CLI steps** like "Read sign-off entry + diff", "Create validation folder", "Cleanup notepad". Don't fabricate a command for steps that were purely cognitive or file-system level.
|
||||
6. **Numbered steps must be contiguous** (1, 2, 3, ...). Don't skip numbers.
|
||||
7. **At least one screenshot per PASS item if the item is a user-visible behavioral test**. Schema-only assertions (settings.json key check) don't need screenshots; behavioral tests (popup shown, dialog appeared, theme switched) do.
|
||||
|
||||
## §D — Reporting style
|
||||
|
||||
- Be specific. "Verified via UIA inspect returned `itm-calculator-XXXX`" beats "verified UIA".
|
||||
- Include exact UIA selectors, log line text, settings.json keys, and screenshot filenames so the user can audit.
|
||||
- For BLOCKED items, the 1-sentence reason should name **what specifically blocks**, e.g.:
|
||||
- "BLK-HARDWARE: requires 2nd monitor; session has 1 (verified via `[System.Windows.Forms.Screen]::AllScreens.Count`)."
|
||||
- "BLK-DRAG-REQUIRED: synthetic mouse drag insufficient for FZ snap-and-drag; needs real cursor motion."
|
||||
- "BLK-ENV: SendInput returned ACCESS_DENIED (5) because Session $agentSession ≠ console Session $consoleSession. See `references/environment-setup.md`."
|
||||
- "BLK-EXTERNAL-APP: requires real OpenAI API key; no key provisioned in test env."
|
||||
|
||||
## §E — Reporting anti-patterns (extra strict)
|
||||
|
||||
- Do NOT collapse multiple probe commands into a single English sentence like "verified via UIA". List every `winapp ui ...` command verbatim in a step row.
|
||||
- Do NOT skip the step table for "trivial" items. Even a 1-step item (e.g. "Get-CmdPalSettings shows EnableDock=true") gets a 1-row table.
|
||||
- Do NOT write screenshot references as `` inside table cells (GitHub renders markdown images poorly in cells). Write them as plain text path: `screenshot: artifacts/L<line>/step-NN-<name>.png`.
|
||||
- Do NOT use "the test passed" as a screenshot caption — describe what's visible (e.g. "Settings page with FZ template grid showing 7 templates").
|
||||
- Do NOT reference screenshots that you didn't actually capture. The final wrap-up `Test-Path` loop (see `references/pre-flight.md` §Final wrap-up step 3) will catch missing files; failing that check means the report is invalid.
|
||||
- Do NOT cite source code line numbers (e.g. `CharacterMappings.cs:273`) without having actually read that line. If you cite source, the path must be real and the line number must contain what you claim.
|
||||
|
||||
## §F — Example item (reference: PR-47211 validation report style)
|
||||
|
||||
```markdown
|
||||
## Item L455 — Activate Quick Accent (left Alt + arrow key) on a character, verify accents popup — **PASS** ✅
|
||||
|
||||
**Admin**: NO | **Clarity**: CLEAR | **Category**: drove full UIA flow + asserted accents popup
|
||||
|
||||
### Verification steps performed
|
||||
|
||||
| # | Step | winapp / probe commands | Evidence / result |
|
||||
|---|---|---|---|
|
||||
| 1 | Locate Settings window | `winapp ui list-windows --json` | `hwnd=263304`, `PowerToys.Settings` PID 31740 |
|
||||
| 2 | Navigate to Quick Accent + expand language flyout | `winapp ui invoke QuickAccentNavItem -w 263304`<br>`winapp ui invoke btn-choosecharacter-1c4d -w 263304` | Page loaded; flyout expanded |
|
||||
| 3 | Enumerate language list + screenshot | `winapp ui inspect btn-choosecharacter-1c4d -w 263304 --depth 5`<br>`winapp ui screenshot -w 263304 -o "artifacts/L455/step-03-language-list.png"` | 38 spoken + 6 special languages, alphabetic. screenshot: `artifacts/L455/step-03-language-list.png` |
|
||||
| 4 | Single-language (French) popup test | `winapp ui invoke itm-french-1cac -w 263304`<br>`winapp ui inspect characters -w <popupHwnd> --depth 3`<br>`winapp ui screenshot -w <popupHwnd> -o "artifacts/L455/step-04-popup-FR-E.png"` | Popup chars for **E** = `é è ê ë €` (5), matches `FR.VK_E` in `CharacterMappings.cs:273`. screenshot: `artifacts/L455/step-04-popup-FR-E.png` |
|
||||
| 5 | Restore baseline | — | settings.json reverted to `selected_lang="ALL"` |
|
||||
|
||||
### Artifacts produced
|
||||
- `artifacts/L455/step-03-language-list.png` — Settings page with expanded language flyout
|
||||
- `artifacts/L455/step-03-language-list.txt` — full UIA inspect dump of the list
|
||||
- `artifacts/L455/step-04-popup-FR-E.png` — Popup with French only: `é è ê ë €`
|
||||
|
||||
### Verdict reasoning
|
||||
- ✅ Popup characters match `CharacterMappings.cs` entries exactly (5/5 for FR.VK_E)
|
||||
- ✅ Popup appeared within 500ms of hold-A; no crash
|
||||
- ✅ Language list ordering is alphabetic by localized name
|
||||
```
|
||||
|
||||
## §G — Retrospective (self-reflection)
|
||||
|
||||
After the run, reflect on the **process** (not the product) so the skill itself gets better over time. **If nothing slowed you down, write exactly one line: `Everything was smooth — no friction encountered.`** Otherwise, list each friction as a row and assign a source + severity.
|
||||
|
||||
```markdown
|
||||
## Retrospective
|
||||
|
||||
| # | Friction (what slowed you / what was wrong) | Source | Severity | Cost | Suggested fix |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | <concrete description — what you expected vs what happened> | <one source tag below> | <HIGH/MED/LOW> | <~min wasted · N attempts> | <the doc line / helper function / tool behavior to change> |
|
||||
```
|
||||
|
||||
**Source** — classify each friction into exactly one bucket so the right owner can fix it:
|
||||
|
||||
| Source tag | Meaning |
|
||||
|---|---|
|
||||
| `SKILL-UNCLEAR` | This skill's `SKILL.md` / `references/pre-flight.md` / module profile guidance was missing, ambiguous, or wrong. |
|
||||
| `WINAPP-TOOL-BUG` | The `winapp` CLI itself misbehaved (crash, wrong output, flag not honored) — a product defect in the tool. |
|
||||
| `WINAPP-DOC-UNCLEAR` | `references/winapp-ui-testing.md` was unclear/incorrect about how to use the tool (the tool worked; the docs misled you). |
|
||||
| `HELPER-FLAW` | A shipped `scripts/*.ps1` had a logic bug, bad default, or wrong assumption. Name the function. |
|
||||
| `PT-PRODUCT` | A PowerToys behavior/quirk made driving hard (distinct from a product **FAIL** — this is friction, not a checklist failure). |
|
||||
| `CHECKLIST` | The checklist item itself was wrong/stale/ambiguous (e.g. describes a renamed or removed control). Note: this usually *also* produces a `FAIL (cause: checklist-*)` verdict on the item; log it here too so the checklist owner sees it as a process-improvement signal. |
|
||||
| `ENVIRONMENT` | RDP/session/desktop/elevation friction not already covered by `references/environment-setup.md`. |
|
||||
|
||||
**Severity** — judge by *impact on future agents*, not just yourself:
|
||||
- **HIGH** — most agents will hit it; blocks progress or wastes >10 min, or you needed a non-obvious workaround.
|
||||
- **MED** — many agents may hit it; cost a few minutes or 2-3 retries; workaround exists once known.
|
||||
- **LOW** — edge case or cosmetic; <1 min; noted for completeness.
|
||||
|
||||
**Cost** — be concrete: approximate minutes wasted **and** number of attempts (e.g. `~8 min · 3 attempts`). This is the raw signal for prioritizing skill fixes.
|
||||
|
||||
**Suggested fix** — point at the specific artifact to change: a doc line/section, a helper function name, or a `winapp` behavior to file. Vague reflections ("docs could be clearer") are not actionable — cite the line.
|
||||
|
||||
Example:
|
||||
```markdown
|
||||
## Retrospective
|
||||
|
||||
| # | Friction | Source | Severity | Cost | Suggested fix |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | `winapp ui inspect --depth 7 -w $hwnd` threw "Cannot bind argument" until I moved `-w` after `--depth`. | `WINAPP-TOOL-BUG` | MED | ~6 min · 3 attempts | Already noted in pitfall #14, but the tool should parse flag order — file against winapp. |
|
||||
| 2 | SKILL.md §2.A says "wait 4s debounce" but PowerRename needed a full `Restart-PtRunner`; the module-owned-file note (pitfall #18) wasn't cross-linked from §2.A. | `SKILL-UNCLEAR` | HIGH | ~12 min · 4 attempts | Add an explicit "shell-ext modules → see pitfall #18" pointer inside §2.A. |
|
||||
```
|
||||
@@ -1,531 +0,0 @@
|
||||
# WinUI UI-testing mechanics (winapp ui)
|
||||
|
||||
> **Provenance:** Adapted from the `winui-ui-testing` skill in [microsoft/win-dev-skills](https://github.com/microsoft/win-dev-skills) (MIT, © Microsoft Corporation and Contributors), with PowerToys-specific edits. This is a **reference doc** for the `powertoys-module-verification` skill — it is intentionally not a standalone skill (no frontmatter), so it is not separately discovered.
|
||||
|
||||
Automated UI testing for WinUI 3 apps — generate a batch test script, run all tests in one pass, read results. Covers element assertions, interactions, value checking (TextBox, ComboBox, ToggleSwitch), file pickers, flyouts, dialogs, persistence, and accessibility audits.
|
||||
|
||||
### Approach
|
||||
|
||||
The goal of this skill is to validate UI and app functionality automatically, without manual interaction, by exercising the app's UI elements, verifying their state, and asserting that the app behaves as expected under test conditions.
|
||||
|
||||
There are two main approaches:
|
||||
1. Interactive exploration — manually run the app, use `winapp ui <command>` to explore the UI tree, find AutomationIds, verify element properties, and test functionality interactively. This is useful for discovery, but slow and expensive if repeated for every test iteration.
|
||||
2. Scripted batch testing — generate a `ui-tests.ps1` script that exercises all UI elements and asserts expected behavior in one pass. This allows you to run the tests automatically, capture results, and iterate quickly without manually interacting with the app each time.
|
||||
|
||||
Unless the user asked for interactive exploration, or you are unfamiliar with the code/app or need to explore the UI tree to discover AutomationIds for hidden or dynamically generated elements (flyouts, dialogs, lazy-loaded content), **prefer scripted batch testing** — it is faster, repeatable, and produces a record of pass/fail results that can be reviewed and acted on.
|
||||
|
||||
### `winapp ui` Verbs
|
||||
|
||||
`status`, `inspect`, `search`, `get-property`, `get-value`, `screenshot`, `invoke`, `click`, `set-value`, `focus`, `scroll`, `scroll-into-view`, `wait-for`, `list-windows`, `get-focused`. Run `winapp ui --cli-schema` for the complete command structure as JSON, or `winapp ui <verb> --help` for any single verb.
|
||||
|
||||
### Step 1: Use the Running App
|
||||
|
||||
If the app is already running, use its PID. **Do NOT relaunch** — use the PID already captured from the build step. If the app is not running, build and launch it using the guidance in the winui-dev-workflow skill.
|
||||
|
||||
### Step 2: Write the Test Script
|
||||
|
||||
**If you wrote the code:** Skip inspect — you already know all the AutomationIds and control structure from the XAML and code-behind. Write tests directly from that knowledge. Inspect misses popups, flyouts, dialogs, and lazy-loaded content anyway.
|
||||
|
||||
**If you're verifying code you didn't write:** Run inspect first to discover the UI:
|
||||
```powershell
|
||||
winapp ui inspect -a <PID> --interactive
|
||||
```
|
||||
Then read the XAML files to find AutomationIds that aren't currently visible (flyout items, dialog buttons, secondary pages).
|
||||
|
||||
Create a `ui-tests.ps1` file that tests all the app's requirements in one pass:
|
||||
|
||||
```powershell
|
||||
# ui-tests.ps1
|
||||
param([Parameter(Mandatory)][int]$AppPid)
|
||||
# NOTE: Do NOT name the parameter $Pid — it's read-only in PowerShell
|
||||
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$pass = 0; $fail = 0; $results = @()
|
||||
|
||||
# Get main window HWND (avoids PopupHost interference with JSON parsing)
|
||||
$windows = winapp ui list-windows -a $AppPid --json 2>$null | ConvertFrom-Json
|
||||
$hwnd = ($windows | Where-Object { $_.title -ne "PopupHost" } | Select-Object -First 1).hwnd
|
||||
|
||||
function Test-UI {
|
||||
param([string]$Name, [scriptblock]$Script)
|
||||
# IMPORTANT: Inside $Script, use 'throw' to signal failure — NOT 'exit 1'
|
||||
# (exit terminates the entire script, not just the test)
|
||||
try {
|
||||
$output = & $Script 2>&1
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
$script:pass++; $script:results += @{ name = $Name; status = "PASS" }
|
||||
} else {
|
||||
$script:fail++; $script:results += @{ name = $Name; status = "FAIL"; detail = "$output" }
|
||||
}
|
||||
} catch {
|
||||
$script:fail++; $script:results += @{ name = $Name; status = "FAIL"; detail = "$_" }
|
||||
}
|
||||
}
|
||||
|
||||
# ─── Element Existence ───
|
||||
Test-UI "NavHome exists" { winapp ui wait-for "NavHome" -a $AppPid -t 3000 }
|
||||
Test-UI "NavSettings exists" { winapp ui wait-for "NavSettings" -a $AppPid -t 3000 }
|
||||
|
||||
# ─── Navigation ───
|
||||
Test-UI "Navigate to Settings" { winapp ui invoke "NavSettings" -a $AppPid }
|
||||
Test-UI "Settings page loaded" { winapp ui wait-for "TxtUserName" -a $AppPid -t 3000 }
|
||||
|
||||
# ─── Interactions ───
|
||||
Test-UI "Set username" { winapp ui set-value "TxtUserName" "TestUser" -a $AppPid }
|
||||
Test-UI "Click Save" { winapp ui invoke "BtnSave" -a $AppPid } # commits the TextBox binding
|
||||
Test-UI "Username value set" {
|
||||
winapp ui wait-for "TxtUserName" -a $AppPid --value "TestUser" -t 2000
|
||||
}
|
||||
|
||||
# ─── Value assertions for different control types ───
|
||||
Test-UI "Theme is System default" {
|
||||
winapp ui wait-for "CmbTheme" -a $AppPid --value "System default" -t 2000
|
||||
}
|
||||
Test-UI "Logging is off" {
|
||||
winapp ui wait-for "TglLogging" -a $AppPid --value "Off" -t 2000
|
||||
}
|
||||
|
||||
# ─── Accessibility Audit ───
|
||||
# Only audit controls in the app's main window (exclude OS picker/popup controls)
|
||||
$allElements = (winapp ui inspect -a $AppPid --interactive --json 2>$null | ConvertFrom-Json).elements
|
||||
$appElements = @($allElements | Where-Object {
|
||||
$_.type -match 'Button|TextBox|ComboBox|CheckBox|ToggleSwitch|TabItem|Edit' -and
|
||||
$_.name -notmatch 'Minimize|Maximize|Close|System' -and # window chrome
|
||||
$_.className -notmatch 'PickerHost|#32770|CabinetWClass' # OS dialogs
|
||||
})
|
||||
$missingId = @($appElements | Where-Object { -not $_.automationId })
|
||||
if ($missingId.Count -eq 0) {
|
||||
$pass++; $results += @{ name = "All app controls have AutomationId"; status = "PASS" }
|
||||
} else {
|
||||
$fail++
|
||||
$names = ($missingId | ForEach-Object { "$($_.type) '$($_.name)'" }) -join ", "
|
||||
$results += @{ name = "AutomationId coverage"; status = "FAIL"; detail = "Missing: $names" }
|
||||
}
|
||||
|
||||
# ─── State Screenshots (capture each meaningful state for visual review) ───
|
||||
New-Item -ItemType Directory -Force -Path "screenshots" | Out-Null
|
||||
winapp ui screenshot -a $AppPid -o "screenshots/01-initial.png" 2>$null
|
||||
# ...take more screenshots after key interactions above (mode switches, dialogs opened, etc.)
|
||||
|
||||
# ─── Final Screenshot ───
|
||||
winapp ui screenshot -a $AppPid -o "test-screenshot.png" 2>$null
|
||||
|
||||
# ─── Results ───
|
||||
Write-Host "`nPassed: $pass | Failed: $fail"
|
||||
$results | Where-Object { $_.status -eq "FAIL" } | ForEach-Object {
|
||||
Write-Host " FAIL: $($_.name) — $($_.detail)" -ForegroundColor Red
|
||||
}
|
||||
$results | ConvertTo-Json | Out-File "test-results.json"
|
||||
if ($fail -gt 0) { exit 1 } else { exit 0 }
|
||||
```
|
||||
|
||||
### What to Test
|
||||
|
||||
Write tests for **every requirement** from the user's prompt:
|
||||
|
||||
| Requirement type | Test approach |
|
||||
|---|---|
|
||||
| "Has a button that does X" | `search` to verify exists, `invoke` to click, `wait-for --value` to check result |
|
||||
| "Text field shows value" | `wait-for "TxtName" --value "expected"` — works for TextBox, TextBlock, labels |
|
||||
| "Status bar contains text" | `wait-for "StatusBar" --value "words" --contains` — substring match for dynamic content |
|
||||
| "Dropdown is set to X" | `wait-for "CmbTheme" --value "Dark"` — reads the selected item automatically |
|
||||
| "Toggle is on/off" | `wait-for "TglFeature" --value "On"` — reads the toggle state |
|
||||
| "Navigation between pages" | `invoke` nav item, `wait-for` a page-specific element to appear |
|
||||
| "Open file dialog" | `invoke` trigger, `list-windows` to find picker HWND, interact with `-w` |
|
||||
| "Save file dialog" | Same as open — find picker with `list-windows`, `set-value` filename, `invoke` Save |
|
||||
| "Right-click context menu" | `click --right` on element, `invoke` the flyout MenuItem |
|
||||
| "Confirmation dialog" | `invoke` trigger, `search` for dialog buttons, `invoke` Primary/Secondary/Close |
|
||||
| "Data persists" | Set values, `invoke` a button (to commit bindings), verify data file on disk (`Get-Content` + `ConvertFrom-Json`) |
|
||||
| "All controls accessible" | `inspect --interactive --json` + check all have AutomationId |
|
||||
|
||||
### Step 3: Run and Read Results
|
||||
|
||||
```powershell
|
||||
.\ui-tests.ps1 -AppPid <PID>
|
||||
```
|
||||
|
||||
Read `test-results.json` for structured pass/fail. Only fix code if tests fail.
|
||||
|
||||
### Step 3.5: Look at the Screenshots
|
||||
|
||||
UIA assertions don't see clipping, overlap, wrong theming, or controls bleeding past their container — UIA returns `PASS` while the app is visually broken. **Capture screenshots with `winapp ui screenshot` and view each PNG.**
|
||||
|
||||
Capture the initial state and any state after a major interaction (the State Screenshots block in the script template above handles this).
|
||||
|
||||
**Visual checklist — fail the run if any item is `no`:**
|
||||
- [ ] No unintended scrollbars
|
||||
- [ ] No text ending in `…` that shouldn't be
|
||||
- [ ] Hero elements fully visible (not sliced)
|
||||
- [ ] Right-edge controls fully visible
|
||||
- [ ] No overlapping rows
|
||||
- [ ] Content uses the available width — no asymmetric dead zones (e.g. content pinned to one edge leaving empty space on the other)
|
||||
- [ ] Spacing intentional — not cramped, not unintentionally vast
|
||||
- [ ] Theming matches the user's ask (Light/Dark/HighContrast if relevant)
|
||||
- [ ] Focus/hover/error states render if tested
|
||||
|
||||
If the checklist fails, it's a bug — fix before declaring done. Window too small → grow per `winui-design` Step 4.
|
||||
|
||||
### Step 4: Fix and Rerun (if the user asked for it)
|
||||
|
||||
If tests fail:
|
||||
1. Read the failure details from `test-results.json`
|
||||
2. Batch-fix all issues in one pass
|
||||
3. Rebuild with `.\BuildAndRun.ps1` (blocking mode — shows crash info if the fix broke something)
|
||||
4. Rerun `.\ui-tests.ps1 -AppPid <PID>` (parse PID from the `launched (PID: XXXXX)` output)
|
||||
|
||||
**Maximum 2 fix-and-rerun cycles.** If the same tests keep failing after 2 cycles, report them as known issues and move on — do not keep iterating.
|
||||
|
||||
### Assertion Reference
|
||||
|
||||
Use `wait-for --value` as the primary assertion — it uses a smart fallback chain that reads the right value for any control type:
|
||||
|
||||
| Control type | `--value` reads from | Example |
|
||||
|---|---|---|
|
||||
| TextBlock / Label | Name property | `wait-for "LblTitle" --value "Home"` |
|
||||
| TextBox / NumberBox | ValuePattern | `wait-for "TxtName" --value "John"` |
|
||||
| RichEditBox | TextPattern | `wait-for "Editor" --value "Hello"` |
|
||||
| ComboBox | Selected item (SelectionPattern) | `wait-for "CmbTheme" --value "Dark"` |
|
||||
| ToggleSwitch | Toggle state (On/Off) | `wait-for "TglDark" --value "On"` |
|
||||
| CheckBox | Toggle state (On/Off) | `wait-for "ChkAgree" --value "On"` |
|
||||
|
||||
**Full assertion commands:**
|
||||
|
||||
| Assertion | Command |
|
||||
|---|---|
|
||||
| Element exists | `winapp ui wait-for "Id" -a PID -t 3000` |
|
||||
| Element has exact value | `winapp ui wait-for "Id" -a PID --value "expected" -t 3000` |
|
||||
| Value contains text | `winapp ui wait-for "Id" -a PID --value "words" --contains -t 3000` |
|
||||
| Element gone | `winapp ui wait-for "Id" -a PID --gone -t 3000` |
|
||||
| Specific property | `winapp ui wait-for "Id" -a PID -p IsEnabled --value "True" -t 3000` |
|
||||
| Button clickable | `winapp ui invoke "Id" -a PID` (exit code 0) |
|
||||
| Set then verify | `winapp ui set-value "Id" "text" -a PID` then `wait-for --value` |
|
||||
| Screenshot | `winapp ui screenshot -a PID -o path.png` |
|
||||
| Dialog appeared | `winapp ui list-windows -a PID --json` (check window count) |
|
||||
| Right-click menu | `winapp ui click "Id" -a PID --right` then `wait-for` menu item |
|
||||
| Read raw property | `winapp ui get-property "Id" -a PID -p IsEnabled --json` |
|
||||
| Read current value (no wait) | `(winapp ui get-value "Id" -a PID --json \| ConvertFrom-Json).text` — always pass `--json` when capturing into a variable (plain stdout can include advisory text like "Auto-selected HWND … from N windows"); otherwise prefer `wait-for --value` |
|
||||
| Scroll item into view | `winapp ui scroll-into-view "Id" -a PID` — call before `wait-for` on virtualized ListView/repeater items below the fold |
|
||||
| Set keyboard focus | `winapp ui focus "Id" -a PID` — cleaner than clicking another control to trigger a TextBox `LostFocus` commit |
|
||||
|
||||
### Testing File Pickers
|
||||
|
||||
File/folder pickers (FileOpenPicker, FileSavePicker, FolderPicker) run in a separate `PickerHost` process but are fully interactable. The picker appears as an owned dialog window.
|
||||
|
||||
```powershell
|
||||
# 1. Trigger the picker
|
||||
winapp ui invoke "BtnOpenFile" -a $AppPid
|
||||
|
||||
# 2. Find the picker window (it's a dialog owned by the app window)
|
||||
Start-Sleep 1
|
||||
$allWindows = winapp ui list-windows -a $AppPid --json 2>$null | ConvertFrom-Json
|
||||
$picker = $allWindows | Where-Object { $_.title -match "Open|Save" }
|
||||
$pickerHwnd = $picker.hwnd
|
||||
|
||||
# 3. Interact with the picker using -w <HWND>
|
||||
# Type a filename:
|
||||
winapp ui set-value "FileNameControlHost" "test.txt" -w $pickerHwnd
|
||||
# Click Open/Save:
|
||||
winapp ui invoke "Open" -w $pickerHwnd # or "Save", "Cancel"
|
||||
# Or cancel:
|
||||
winapp ui invoke "Cancel" -w $pickerHwnd
|
||||
|
||||
# 4. Verify the app processed the file
|
||||
winapp ui wait-for "StatusBar" -a $AppPid -p Name --value "opened" -t 3000
|
||||
```
|
||||
|
||||
**Tip:** Use `winapp ui inspect -w <pickerHwnd> --interactive` to discover the picker's controls — they include the folder tree, file list, filename textbox, and Open/Cancel buttons.
|
||||
|
||||
### Testing Context Menus and Flyouts
|
||||
|
||||
MenuFlyouts and ContextFlyouts are fully testable. They appear in the UI automation tree when open.
|
||||
|
||||
```powershell
|
||||
# 1. Right-click to open a ContextFlyout
|
||||
winapp ui click "LstItems" -a $AppPid --right
|
||||
Start-Sleep 0.5
|
||||
|
||||
# 2. The flyout MenuItems appear in the tree immediately
|
||||
# Find them with inspect or search:
|
||||
winapp ui inspect -a $AppPid --interactive # shows MnuCopy, MnuDelete, etc.
|
||||
|
||||
# 3. Click a flyout item
|
||||
winapp ui invoke "MnuCopy" -a $AppPid
|
||||
|
||||
# 4. Verify the action
|
||||
winapp ui wait-for "StatusText" -a $AppPid -p Name --value "Copied" -t 2000
|
||||
```
|
||||
|
||||
**For MenuBar flyouts** (File, Edit, View menus):
|
||||
```powershell
|
||||
# Click the menu header to open
|
||||
winapp ui invoke "FileMenu" -a $AppPid
|
||||
Start-Sleep 0.5
|
||||
# Click the sub-item
|
||||
winapp ui invoke "MenuSaveAs" -a $AppPid
|
||||
```
|
||||
|
||||
### Testing ContentDialogs
|
||||
|
||||
ContentDialogs are in-app controls (same window) — they appear directly in the UI tree when shown.
|
||||
|
||||
```powershell
|
||||
# 1. Trigger the dialog
|
||||
winapp ui invoke "BtnDelete" -a $AppPid
|
||||
Start-Sleep 0.5
|
||||
|
||||
# 2. The dialog buttons appear in the tree
|
||||
# For a standard confirmation dialog:
|
||||
winapp ui search "Primary" -a $AppPid --json # finds the primary button
|
||||
winapp ui invoke "Primary" -a $AppPid # click "Yes"/"Delete"/"Save"
|
||||
# Or:
|
||||
winapp ui invoke "Secondary" -a $AppPid # click "No"/"Don't Save"
|
||||
winapp ui invoke "Close" -a $AppPid # click "Cancel"
|
||||
|
||||
# 3. Wait for dialog to dismiss
|
||||
winapp ui wait-for "Primary" -a $AppPid --gone -t 3000
|
||||
```
|
||||
|
||||
**Tip:** ContentDialog buttons often don't have custom AutomationIds — use `inspect` to find the actual selector (slug or text match).
|
||||
|
||||
### Key Gotchas
|
||||
|
||||
- **`set-value` does NOT commit default TextBox bindings** — WinUI 3 `x:Bind TwoWay` on TextBox.Text updates the ViewModel on `LostFocus` by default. UIA `set-value` changes the text but doesn't trigger focus events. **Fix:** apps should use `UpdateSourceTrigger=PropertyChanged` on TextBox bindings (see design skill). If the app doesn't, `invoke` a button or `click` another element after `set-value` to trigger `LostFocus`.
|
||||
- **Verify persistence via the data file, not UI relaunch** — killing and relaunching a packaged app from a test script is fragile (MSIX registration timing, PID issues). Instead, check the data file on disk: `Get-Content $dataFile | ConvertFrom-Json` and verify expected values.
|
||||
- **Use `$AppPid` not `$Pid`** — `$Pid` is a read-only automatic variable in PowerShell
|
||||
- **Use `--value` without `-p`** — it auto-detects the right UIA pattern (TextPattern → ValuePattern → TogglePattern → SelectionPattern → Name). Only use `-p PropertyName --value` when you need a specific property like `IsEnabled`
|
||||
- **File pickers need `-w <HWND>`** — they run in a separate PickerHost process, so `-a PID` won't find them. Use `list-windows` to discover the picker HWND first
|
||||
- **Flyouts need a short `Start-Sleep`** after triggering — the menu items appear in the tree asynchronously
|
||||
|
||||
### CRITICAL — `invoke` vs `click`: choose the right verb
|
||||
|
||||
**`winapp ui invoke <sel>`** dispatches through UIA's **`InvokePattern` via COM IPC**:
|
||||
- ✅ Bypasses Windows UIPI (User Interface Privilege Isolation)
|
||||
- ✅ Works even when your test runs elevated and the target is non-elevated AppX
|
||||
- ✅ Does NOT steal foreground / does NOT trigger focus-loss handlers
|
||||
- ✅ Works on Buttons, ListItems, ToggleSwitches, CheckBoxes — anything that exposes `InvokePattern` or `TogglePattern`
|
||||
- ❌ Does NOT work on elements without an UIA action pattern (plain Grid, Text, Pane) — error message says "does not support any invoke pattern"
|
||||
|
||||
**`winapp ui click <sel>`** uses Win32 **`SendInput`** under the hood:
|
||||
- ❌ **BLOCKED by UIPI** when source is elevated and target is non-elevated (or any AppX) — error: `SendInput failed — the target window may be elevated`
|
||||
- ❌ Triggers foreground change → can dismiss popups, dialogs, AppX windows that hide on deactivation
|
||||
- ✅ Only use when you genuinely need a synthetic mouse click (e.g. testing mouse hover/right-click flyouts where InvokePattern is unavailable)
|
||||
- ✅ Subject to your process having interactive desktop access
|
||||
|
||||
**Rule of thumb**: try `invoke` first; only fall back to `click` if the target lacks InvokePattern AND you have a non-elevated test runner.
|
||||
|
||||
### CRITICAL — DataTemplate AutomationId vs ListItem InvokePattern
|
||||
|
||||
When XAML binds `AutomationProperties.AutomationId="{x:Bind <DataProperty>}"` inside a `ListView.ItemTemplate`'s `<DataTemplate>`, the AutomationId lives on the **inner Grid (Group)** the template produces — NOT on the outer ListItem the ListView wraps around it. The outer ListItem is what carries `InvokePattern`.
|
||||
|
||||
Concrete example (CmdPal PR #48033 binds Command.Id this way):
|
||||
|
||||
```powershell
|
||||
# This FAILS with "does not support any invoke pattern":
|
||||
winapp ui invoke 'com.microsoft.cmdpal.calculator' -w $hwnd
|
||||
# Element grp-commicrosoftcmd-XXXX (Group) does not support any invoke pattern.
|
||||
# No invokable ancestor was found.
|
||||
|
||||
# This WORKS — find by Name (matches all 3 siblings), pick the ListItem child:
|
||||
$r = winapp ui search 'Calculator' -w $hwnd --json | ConvertFrom-Json
|
||||
$li = $r.matches | Where-Object type -eq 'ListItem' | Select-Object -First 1
|
||||
winapp ui invoke $li.selector -w $hwnd # selector like 'itm-calculator-7e3f'
|
||||
```
|
||||
|
||||
If you encounter "does not support any invoke pattern" while trying to use a data-bound AutomationId, this is almost always the cause. The fix is to search by Name and invoke the sibling ListItem.
|
||||
|
||||
### CRITICAL — Keystroke input that bypasses UIPI (PostMessage)
|
||||
|
||||
`winapp ui` has no `send-keys` verb. For keystroke input into elevated/AppX targets where SendInput fails, use **inline Win32 `PostMessage WM_KEYDOWN/WM_KEYUP`** which goes through the target's message queue without UIPI checks:
|
||||
|
||||
```powershell
|
||||
Add-Type @"
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class K {
|
||||
[DllImport("user32.dll", CharSet=CharSet.Auto)]
|
||||
public static extern bool PostMessage(IntPtr h, uint msg, IntPtr wp, IntPtr lp);
|
||||
public const uint WM_KEYDOWN = 0x0100;
|
||||
public const uint WM_KEYUP = 0x0101;
|
||||
}
|
||||
"@
|
||||
|
||||
function Send-KeyToHwnd {
|
||||
param([IntPtr]$Hwnd, [byte]$Vk)
|
||||
[void][K]::PostMessage($Hwnd, [K]::WM_KEYDOWN, [IntPtr]$Vk, [IntPtr]0)
|
||||
Start-Sleep -Milliseconds 30
|
||||
[void][K]::PostMessage($Hwnd, [K]::WM_KEYUP, [IntPtr]$Vk, [IntPtr]0)
|
||||
}
|
||||
|
||||
# Common VK codes:
|
||||
# 0x08 Backspace 0x09 Tab 0x0D Enter 0x1B Escape
|
||||
# 0x25 Left 0x26 Up 0x27 Right 0x28 Down
|
||||
Send-KeyToHwnd -Hwnd $h -Vk 0x28 # Down arrow
|
||||
Send-KeyToHwnd -Hwnd $h -Vk 0x0D # Enter
|
||||
```
|
||||
|
||||
**Caveats**:
|
||||
- WinUI3 apps' raw-input hooks may NOT process some keys via WM_KEYDOWN — `Esc` in particular often goes ignored (use BackButton invoke instead). Arrow keys + Enter typically work for ListView navigation.
|
||||
- PostMessage returns immediately; allow 50-200 ms before reading state.
|
||||
- Repeat `Send-KeyToHwnd` calls work for multi-step navigation (Down × 5 to scroll, then Enter).
|
||||
|
||||
### CRITICAL — Global hotkeys / PowerToys activation chords (SendInput, verified working)
|
||||
|
||||
`PostMessage` above targets a specific window's queue. To fire a **global hotkey** (e.g. a PowerToys activation chord like `Win+Shift+C`) you must inject into the **system input stream** with `SendInput` so the low-level keyboard hook (`WH_KEYBOARD_LL`) sees it. This **works for Win+ chords** — the common belief that "Win+ chords can't be injected" is false; it's almost always a **marshaling bug** (`SendInput` returns `0`, `GetLastError()==87`) from building the `INPUT[]` array in PowerShell. Build the array in C#:
|
||||
|
||||
```powershell
|
||||
Add-Type @"
|
||||
using System; using System.Runtime.InteropServices; using System.Collections.Generic;
|
||||
public static class Inj {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct INPUT { public uint type; public KEYBDINPUT ki; public int p1; public int p2; } // p1/p2 pad the union -> cb=40 on x64
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
||||
[DllImport("user32.dll", SetLastError=true)] static extern uint SendInput(uint n, INPUT[] p, int cb);
|
||||
const uint KEYUP = 0x0002;
|
||||
static INPUT K(ushort vk, bool up){ INPUT i=new INPUT(); i.type=1; i.ki.wVk=vk; i.ki.dwFlags=up?KEYUP:0; return i; }
|
||||
public static uint Chord(ushort[] mods, ushort key){ // mods down -> key tap -> mods up (reverse)
|
||||
var l=new List<INPUT>();
|
||||
foreach(var m in mods) l.Add(K(m,false));
|
||||
l.Add(K(key,false)); l.Add(K(key,true));
|
||||
for(int i=mods.Length-1;i>=0;i--) l.Add(K(mods[i],true));
|
||||
var a=l.ToArray(); return SendInput((uint)a.Length,a,Marshal.SizeOf(typeof(INPUT)));
|
||||
}
|
||||
}
|
||||
"@
|
||||
# LWIN=0x5B CTRL=0x11 SHIFT=0x10 ALT=0x12 ; main key VK from the module's settings.json "code"
|
||||
$sent = [Inj]::Chord([uint16[]]@(0x5B,0x10), [uint16]0x43) # Win+Shift+C (Color Picker)
|
||||
if ($sent -eq 0) { throw "SendInput failed err=$([Runtime.InteropServices.Marshal]::GetLastWin32Error())" }
|
||||
```
|
||||
|
||||
**Caveats**:
|
||||
- The injector must run at the **same or higher integrity level** as the hook owner (PowerToys runner). Default per-user installs run the runner at Medium IL, so a normal shell works; if the runner is elevated, run the injector elevated too (otherwise UIPI silently drops the injection).
|
||||
- Must run in the interactive desktop session.
|
||||
- OS-reserved chords (Win+L, Win+Tab) are consumed by Windows before any hook and cannot be injected this way.
|
||||
- Verify the result via the runner trace log line `… hotkey is invoked from Centralized keyboard hook` (`%LOCALAPPDATA%\Microsoft\PowerToys\RunnerLogs\runner-log_<date>.log`) and/or the module's observable side-effect (overlay window, spawned editor process).
|
||||
|
||||
### CRITICAL — Verify foreground BEFORE every SendInput targeting a specific window
|
||||
|
||||
`SendInput` injects into the **session-wide** input stream — it goes to whatever IS foreground at the moment. If your target window has lost foreground (very common with AppX windows), the keys silently land in another window (often your own terminal) with no error returned.
|
||||
|
||||
Always check the foreground state immediately before calling `SendInput`. For winapp ui's output, the literal substring `foreground` appears in the line for the foreground window:
|
||||
|
||||
```powershell
|
||||
function Test-AppForeground {
|
||||
param([Parameter(Mandatory)][string]$AppId)
|
||||
$r = winapp ui list-windows -a $AppId 2>$null | Out-String
|
||||
return ($r -match 'foreground')
|
||||
}
|
||||
|
||||
# Force foreground (works ONCE per session reliably; subsequent attempts may be blocked by
|
||||
# Windows foreground-lock):
|
||||
function Force-AppForeground {
|
||||
param([Parameter(Mandatory)][IntPtr]$Hwnd, [int]$ProcessId)
|
||||
Add-Type -TypeDefinition @'
|
||||
using System; using System.Runtime.InteropServices;
|
||||
public static class Fg {
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
||||
[DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
|
||||
[DllImport("user32.dll")] public static extern bool AttachThreadInput(uint a, uint b, bool f);
|
||||
[DllImport("user32.dll")] public static extern bool AllowSetForegroundWindow(int pid);
|
||||
}
|
||||
'@ -EA SilentlyContinue
|
||||
[Fg]::AllowSetForegroundWindow($ProcessId) | Out-Null
|
||||
[Fg]::ShowWindow($Hwnd, 9) | Out-Null # SW_RESTORE
|
||||
$fg = [Fg]::GetForegroundWindow(); $fgPid = 0
|
||||
$fgThread = [Fg]::GetWindowThreadProcessId($fg, [ref]$fgPid)
|
||||
$curThread = [Fg]::GetCurrentThreadId()
|
||||
if ($fgThread -ne 0 -and $fgThread -ne $curThread) { [Fg]::AttachThreadInput($curThread, $fgThread, $true) | Out-Null }
|
||||
[Fg]::BringWindowToTop($Hwnd) | Out-Null
|
||||
[Fg]::SetForegroundWindow($Hwnd) | Out-Null
|
||||
if ($fgThread -ne 0 -and $fgThread -ne $curThread) { [Fg]::AttachThreadInput($curThread, $fgThread, $false) | Out-Null }
|
||||
Start-Sleep -Milliseconds 400
|
||||
}
|
||||
|
||||
# Guard pattern: abort instead of silently sending keys to wrong window
|
||||
if (-not (Test-AppForeground -AppId 'Microsoft.CmdPal.UI')) {
|
||||
Force-AppForeground -Hwnd $h -ProcessId $pid
|
||||
if (-not (Test-AppForeground -AppId 'Microsoft.CmdPal.UI')) {
|
||||
throw 'Cannot force CmdPal foreground; aborting SendInput batch'
|
||||
}
|
||||
}
|
||||
# ... now safe to SendInput ...
|
||||
```
|
||||
|
||||
**Tip**: when foreground cannot be reliably maintained, prefer `winapp ui set-value` (UIA-IPC, no foreground required) or `winapp ui invoke` (UIA InvokePattern, no foreground required) instead of SendInput.
|
||||
|
||||
### CRITICAL — `set-value` bypasses TextChanged for some apps (CmdPal alias detection)
|
||||
|
||||
`winapp ui set-value` writes the value through UIA's ValuePattern, which fires a programmatic value-change event. **It does NOT raise the `TextBox.TextChanged` event** the way real keystrokes do. For apps whose logic listens to `TextChanged` rather than to property changes — most notably CmdPal's alias detection (typing `=`, `<`, `>`, `:`, `$`, `??`, `)` in MainSearchBox triggers navigation to a provider sub-page) — `set-value` will set the text but the alias will NOT activate.
|
||||
|
||||
Workarounds:
|
||||
- For plain queries: `winapp ui set-value` works fine (CmdPal still re-runs all providers on value change).
|
||||
- For alias-triggered navigation: use **real keystrokes** via Force-AppForeground + SendInput, typing one character at a time with ~60-100ms delay so the alias detector sees the TextChanged sequence.
|
||||
- Alternative: invoke the provider tile directly by its stable AutomationId (e.g. `winapp ui invoke 'com.microsoft.cmdpal.calculator' -w $hwnd`) when you only need the destination page, not the alias path.
|
||||
|
||||
### CRITICAL — Stunted UIA tree recovery
|
||||
|
||||
After ~30+ rapid `set-value` calls or after AppX has been interactive too long, an AppX window's UIA tree can degrade to a "stunted" state where `winapp ui inspect -w $h --depth 6` returns only ~5 elements (TitleBar / Close / Min / Max / RootPane) — even though the app looks fine visually.
|
||||
|
||||
Probe + recover pattern:
|
||||
|
||||
```powershell
|
||||
# Probe: any healthy ListView-based AppX has >50 UIA nodes at depth 6
|
||||
$probe = winapp ui inspect -w $h --depth 6 --json | ConvertFrom-Json
|
||||
$nodes = 0
|
||||
$stack = [System.Collections.Stack]::new()
|
||||
if ($probe.windows[0].elements) { foreach ($e in $probe.windows[0].elements) { $stack.Push($e) } }
|
||||
while ($stack.Count -gt 0) {
|
||||
$n = $stack.Pop(); $nodes++
|
||||
if ($n.PSObject.Properties['children']) { foreach ($c in $n.children) { $stack.Push($c) } }
|
||||
}
|
||||
|
||||
if ($nodes -lt 6) {
|
||||
Write-Warning "UIA tree stunted ($nodes nodes); restarting AppX"
|
||||
Get-Process Microsoft.CmdPal.UI -EA SilentlyContinue | ForEach-Object {
|
||||
Stop-Process -Id $_.Id -Force
|
||||
Wait-Process -Id $_.Id -Timeout 5 -EA SilentlyContinue
|
||||
}
|
||||
Start-Process 'shell:AppsFolder\Microsoft.CommandPalette_8wekyb3d8bbwe!App'
|
||||
Start-Sleep 5
|
||||
# Re-resolve HWND with list-windows
|
||||
}
|
||||
```
|
||||
|
||||
### Settings.json mutation safety contract
|
||||
|
||||
When the only realistic way to reach a needed test state is editing the app's persistent settings (e.g. multi-select that the UI's `SelectionItemPattern.Select` clobbers), wrap mutations with **byte-identical backup + restore-on-exit**:
|
||||
|
||||
```powershell
|
||||
$settings = "$env:LOCALAPPDATA\Packages\Microsoft.CommandPalette_8wekyb3d8bbwe\LocalState\settings.json"
|
||||
$backup = "$env:TEMP\settings-backup-$(Get-Random).json"
|
||||
$origBytes = [System.IO.File]::ReadAllBytes($settings)
|
||||
[System.IO.File]::WriteAllBytes($backup, $origBytes)
|
||||
try {
|
||||
# 1. Stop the AppX so we can write the file (apps usually hold it open)
|
||||
Get-Process Microsoft.CmdPal.UI -EA SilentlyContinue | Stop-Process -Force
|
||||
Start-Sleep 1
|
||||
# 2. Mutate
|
||||
$j = $origBytes | ForEach-Object { [char]$_ } | Join-String | ConvertFrom-Json
|
||||
$j.SomeKey = 'TestValue'
|
||||
[System.IO.File]::WriteAllBytes($settings, [System.Text.Encoding]::UTF8.GetBytes(($j | ConvertTo-Json -Depth 10)))
|
||||
# 3. Restart AppX so it re-reads the mutated settings
|
||||
Start-Process 'shell:AppsFolder\Microsoft.CommandPalette_8wekyb3d8bbwe!App'
|
||||
Start-Sleep 5
|
||||
# 4. ... run your test ...
|
||||
} finally {
|
||||
# ALWAYS restore — verify byte-identical via length + SHA256
|
||||
Get-Process Microsoft.CmdPal.UI -EA SilentlyContinue | Stop-Process -Force -EA SilentlyContinue
|
||||
Start-Sleep 1
|
||||
[System.IO.File]::WriteAllBytes($settings, $origBytes)
|
||||
$check = [System.IO.File]::ReadAllBytes($settings)
|
||||
if ($check.Length -ne $origBytes.Length) { Write-Error "Restore length mismatch!" }
|
||||
Start-Process 'shell:AppsFolder\Microsoft.CommandPalette_8wekyb3d8bbwe!App'
|
||||
}
|
||||
```
|
||||
|
||||
**Important**: this should be used ONLY when the UI route is unreachable. Any setting flippable through the AppX Settings UI should be flipped that way instead (it's the documented user flow and tests real binding code).
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
# scripts/pt-admin-probe.ps1
|
||||
# Verify the current session is elevated AND that PT runner inherits the admin token.
|
||||
|
||||
if (-not ('PtTok' -as [type])) {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class PtTok {
|
||||
[DllImport("advapi32.dll", SetLastError=true)]
|
||||
public static extern bool OpenProcessToken(IntPtr h, uint da, out IntPtr t);
|
||||
[DllImport("advapi32.dll", SetLastError=true)]
|
||||
public static extern bool GetTokenInformation(IntPtr t, uint c, IntPtr ti, uint l, out uint rl);
|
||||
[DllImport("kernel32.dll")] public static extern IntPtr GetCurrentProcess();
|
||||
[DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(uint da, bool inh, int pid);
|
||||
[DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr h);
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
function Test-PtAdmin {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Check whether the current session is elevated by reading the process token's TokenElevation
|
||||
information class (20). Returns $true if elevated.
|
||||
#>
|
||||
[CmdletBinding()] param()
|
||||
$t = [IntPtr]::Zero
|
||||
[PtTok]::OpenProcessToken([PtTok]::GetCurrentProcess(), 8, [ref]$t) | Out-Null
|
||||
$ti = [Runtime.InteropServices.Marshal]::AllocHGlobal(4)
|
||||
$rl = 0
|
||||
try {
|
||||
[PtTok]::GetTokenInformation($t, 20, $ti, 4, [ref]$rl) | Out-Null
|
||||
return ([Runtime.InteropServices.Marshal]::ReadInt32($ti) -eq 1)
|
||||
} finally {
|
||||
[Runtime.InteropServices.Marshal]::FreeHGlobal($ti)
|
||||
[PtTok]::CloseHandle($t) | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
function Test-ProcessElevated {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Check whether a specific PID is elevated (TokenElevation = 1).
|
||||
#>
|
||||
[CmdletBinding()] param([Parameter(Mandatory)][int]$ProcessId)
|
||||
$proc = [PtTok]::OpenProcess(0x1000, $false, $ProcessId) # PROCESS_QUERY_LIMITED_INFORMATION
|
||||
if ($proc -eq [IntPtr]::Zero) { return $null }
|
||||
try {
|
||||
$t = [IntPtr]::Zero
|
||||
if (-not [PtTok]::OpenProcessToken($proc, 8, [ref]$t)) { return $null }
|
||||
try {
|
||||
$ti = [Runtime.InteropServices.Marshal]::AllocHGlobal(4)
|
||||
$rl = 0
|
||||
try {
|
||||
[PtTok]::GetTokenInformation($t, 20, $ti, 4, [ref]$rl) | Out-Null
|
||||
return ([Runtime.InteropServices.Marshal]::ReadInt32($ti) -eq 1)
|
||||
} finally { [Runtime.InteropServices.Marshal]::FreeHGlobal($ti) }
|
||||
} finally { [PtTok]::CloseHandle($t) | Out-Null }
|
||||
} finally { [PtTok]::CloseHandle($proc) | Out-Null }
|
||||
}
|
||||
|
||||
function Test-PtRunnerAdmin {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Check whether the PT runner (PowerToys.exe) is currently running elevated.
|
||||
.OUTPUTS
|
||||
PSCustomObject with .Found (bool), .Pid (int), .Elevated (bool|$null)
|
||||
#>
|
||||
$pt = Get-Process PowerToys -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if (-not $pt) { return [pscustomobject]@{ Found=$false; Pid=$null; Elevated=$null } }
|
||||
[pscustomobject]@{
|
||||
Found = $true
|
||||
Pid = $pt.Id
|
||||
Elevated = (Test-ProcessElevated -ProcessId $pt.Id)
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
# scripts/pt-clipboard-diff.ps1
|
||||
# Multi-format clipboard inspection. Used to assert that AdvancedPaste plain-paste actually strips
|
||||
# rich formats while preserving UnicodeText (and similar before/after assertions).
|
||||
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
|
||||
function Get-PtClipboardFormats {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Return the list of format names currently on the clipboard (e.g. UnicodeText, HTML Format,
|
||||
Rich Text Format, FileDrop, DeviceIndependentBitmap, etc.).
|
||||
#>
|
||||
$obj = [System.Windows.Forms.Clipboard]::GetDataObject()
|
||||
if (-not $obj) { return @() }
|
||||
return $obj.GetFormats()
|
||||
}
|
||||
|
||||
function Get-PtClipboardText {
|
||||
[System.Windows.Forms.Clipboard]::GetText()
|
||||
}
|
||||
|
||||
function Compare-PtClipboardFormatDiff {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Diff helper. Given a 'before' formats list (from Get-PtClipboardFormats), return:
|
||||
- Added: formats present in current clipboard but not in before
|
||||
- Removed: formats present in before but not in current
|
||||
- Common: formats present in both
|
||||
.EXAMPLE
|
||||
$before = Get-PtClipboardFormats # e.g. UnicodeText + HTML Format + RTF
|
||||
# ... user/script triggers AP plain-paste ...
|
||||
$diff = Compare-PtClipboardFormatDiff -Before $before
|
||||
# $diff.Removed should contain 'HTML Format' and 'Rich Text Format'
|
||||
# $diff.Common should still contain 'UnicodeText'
|
||||
#>
|
||||
param([Parameter(Mandatory)][string[]]$Before)
|
||||
$current = Get-PtClipboardFormats
|
||||
[pscustomobject]@{
|
||||
Before = $Before
|
||||
Current = $current
|
||||
Added = @($current | Where-Object { $_ -notin $Before })
|
||||
Removed = @($Before | Where-Object { $_ -notin $current })
|
||||
Common = @($current | Where-Object { $_ -in $Before })
|
||||
}
|
||||
}
|
||||
|
||||
function Set-PtClipboardRich {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Put HTML + UnicodeText on the clipboard so plain-paste detection has something to strip.
|
||||
Useful as test fixture before invoking AdvancedPaste.PasteAsPlainText.
|
||||
#>
|
||||
param(
|
||||
[string]$Text = 'Hello world',
|
||||
[string]$Html = '<html><body><b>Hello</b> <i>world</i></body></html>'
|
||||
)
|
||||
$obj = New-Object System.Windows.Forms.DataObject
|
||||
$obj.SetText($Text, [System.Windows.Forms.TextDataFormat]::UnicodeText)
|
||||
$obj.SetText($Html, [System.Windows.Forms.TextDataFormat]::Html)
|
||||
[System.Windows.Forms.Clipboard]::SetDataObject($obj, $true)
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
# scripts/pt-cmdpal-recycle.ps1
|
||||
# Recover CmdPal AppX from "stuck" states (TextChanged-broken, sub-page hang, foreground-lock).
|
||||
# The helper Microsoft.CmdPal.Ext.PowerToys is kept alive so the CmdPal.Show event listener wiring
|
||||
# is not lost on recycle.
|
||||
|
||||
function Reset-CmdPalAppX {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Kill the Microsoft.CmdPal.UI process and relaunch the AppX. Returns the new HWND or 0 on failure.
|
||||
.NOTES
|
||||
Symptoms requiring this:
|
||||
- set-value MainSearchBox echoes the text but ZERO ListItems appear within 1.5s
|
||||
- winapp ui invoke <button> hangs subsequent inspect calls
|
||||
- Force-PtForeground returns false repeatedly
|
||||
#>
|
||||
$cp = Get-Process Microsoft.CmdPal.UI -ErrorAction SilentlyContinue
|
||||
if ($cp) {
|
||||
Stop-Process -Id $cp.Id -Force
|
||||
$deadline = (Get-Date).AddSeconds(5)
|
||||
while ((Get-Process -Id $cp.Id -ErrorAction SilentlyContinue) -and (Get-Date) -lt $deadline) {
|
||||
Start-Sleep -Milliseconds 200
|
||||
}
|
||||
}
|
||||
Start-Process 'shell:AppsFolder\Microsoft.CommandPalette_8wekyb3d8bbwe!App'
|
||||
$deadline = (Get-Date).AddSeconds(10)
|
||||
do {
|
||||
Start-Sleep -Milliseconds 300
|
||||
$r = winapp ui list-windows -a Microsoft.CmdPal.UI 2>$null | Out-String
|
||||
if ($r -match 'HWND (\d+):') { return [IntPtr][int64]$matches[1] }
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
return [IntPtr]::Zero
|
||||
}
|
||||
|
||||
function Reset-CmdPalToHome {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Navigate CmdPal back to the home page from any sub-page by invoking BackButton via UIA.
|
||||
CmdPal's Esc handler is unreachable via SendInput from elevated sessions (UIPI), and Esc-via-
|
||||
PostMessage is filtered by the WinUI 3 raw-input hook. BackButton invoke via UIA InvokePattern
|
||||
works regardless.
|
||||
#>
|
||||
$homePlaceholder = 'Search for apps, files and commands'
|
||||
for ($i = 0; $i -lt 6; $i++) {
|
||||
$cur = winapp ui get-value 'MainSearchBox' -a Microsoft.CmdPal.UI 2>$null
|
||||
if ($cur -and ($cur -match [regex]::Escape($homePlaceholder))) { break }
|
||||
winapp ui invoke 'BackButton' -a Microsoft.CmdPal.UI 2>$null | Out-Null
|
||||
Start-Sleep -Milliseconds 200
|
||||
}
|
||||
# Re-signal Show in case BackButton dismissed the window
|
||||
if (Get-Command Invoke-PtSharedEvent -ErrorAction SilentlyContinue) {
|
||||
try { Invoke-PtSharedEvent -Name 'CmdPal.Show' | Out-Null } catch {}
|
||||
}
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
|
||||
function Test-CmdPalDegraded {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Probe the AppX with a known-good query ('notepad') and verify >=1 ListItem appears within
|
||||
1500ms. Returns $true if degraded (TextChanged-broken).
|
||||
#>
|
||||
Reset-CmdPalToHome
|
||||
winapp ui set-value 'MainSearchBox' 'notepad' -a Microsoft.CmdPal.UI 2>$null | Out-Null
|
||||
$deadline = (Get-Date).AddMilliseconds(1500)
|
||||
do {
|
||||
$insLines = (winapp ui inspect -a Microsoft.CmdPal.UI --depth 7 -i 2>$null) -split "`n"
|
||||
$items = $insLines | Where-Object { $_ -match 'itm-' -and $_ -match 'ListItem' }
|
||||
if ($items.Count -gt 0) {
|
||||
winapp ui set-value 'MainSearchBox' '' -a Microsoft.CmdPal.UI 2>$null | Out-Null
|
||||
return $false
|
||||
}
|
||||
Start-Sleep -Milliseconds 150
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
return $true
|
||||
}
|
||||
|
||||
function Invoke-CmdPalQuery {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Type a query into MainSearchBox after returning to home. Auto-recovers if AppX is degraded.
|
||||
Returns the result items as an array of strings (text lines starting with itm-).
|
||||
.EXAMPLE
|
||||
$items = Invoke-CmdPalQuery -Query 'notepad'
|
||||
if ($items | Where-Object { $_ -match 'Notepad' }) { 'PASS' } else { 'FAIL' }
|
||||
#>
|
||||
param([Parameter(Mandatory)][string]$Query, [int]$WaitMs = 800)
|
||||
Reset-CmdPalToHome
|
||||
winapp ui set-value 'MainSearchBox' $Query -a Microsoft.CmdPal.UI 2>$null | Out-Null
|
||||
Start-Sleep -Milliseconds $WaitMs
|
||||
$out = winapp ui inspect -a Microsoft.CmdPal.UI --depth 7 -i 2>$null | Out-String
|
||||
$items = ($out -split "`r?`n" | Where-Object { $_ -match 'itm-' -and $_ -match 'ListItem' })
|
||||
if ($items.Count -eq 0) {
|
||||
if (Test-CmdPalDegraded) {
|
||||
Reset-CmdPalAppX | Out-Null
|
||||
return (Invoke-CmdPalQuery -Query $Query -WaitMs $WaitMs)
|
||||
}
|
||||
}
|
||||
return $items
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
# scripts/pt-explorer-com.ps1
|
||||
# Drive Explorer windows via Shell.Application COM to set up file selections, then trigger
|
||||
# PT modules that read IShellItemArray from the foreground Explorer window (Peek, Image Resizer,
|
||||
# PowerRename, File Locksmith, Workspaces).
|
||||
#
|
||||
# This bypasses needing a real mouse / interactive selection — Shell COM does the selection
|
||||
# programmatically, then the PT hotkey (e.g. Ctrl+Space for Peek) fires the centralized hook
|
||||
# which reads Explorer's selection at the moment of activation.
|
||||
#
|
||||
# Requires an interactive desktop session. If GetForegroundWindow() returns 0 or no Explorer
|
||||
# windows are open, the functions return $null/$false instead of throwing — callers should
|
||||
# treat that as a BLK-ENV signal (an environment block, not a product FAIL).
|
||||
|
||||
function Get-PtExplorerWindows {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Return all open Explorer windows as Shell COM objects (with .LocationName, .Document.Folder, etc.).
|
||||
Returns @() if no Explorer windows are open.
|
||||
#>
|
||||
try {
|
||||
$shell = New-Object -ComObject Shell.Application
|
||||
return @($shell.Windows() | Where-Object { $_.Name -eq 'File Explorer' -or $_.FullName -match 'explorer\.exe$' })
|
||||
} catch { return @() }
|
||||
}
|
||||
|
||||
function Open-PtExplorerAtPath {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Open a fresh Explorer window at the given path. Returns the Shell COM window object.
|
||||
Useful when no Explorer is open yet.
|
||||
#>
|
||||
[CmdletBinding()] param([Parameter(Mandatory)][string]$Path)
|
||||
if (-not (Test-Path $Path)) { throw "Path not found: $Path" }
|
||||
Start-Process explorer.exe -ArgumentList $Path
|
||||
Start-Sleep -Milliseconds 1500
|
||||
$wins = Get-PtExplorerWindows
|
||||
# Note: the -replace must be wrapped in its own parens, otherwise the ',' in -replace '\\','/'
|
||||
# is parsed as a second argument to [regex]::Escape() (overload error: "argument count: 2").
|
||||
$needle = [regex]::Escape(((Resolve-Path $Path).Path -replace '\\','/'))
|
||||
return ($wins | Where-Object { $_.LocationURL -match $needle } | Select-Object -First 1)
|
||||
}
|
||||
|
||||
function Select-PtExplorerFiles {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Select 1+ files in an open Explorer window via Shell COM. The window comes to foreground.
|
||||
.DESCRIPTION
|
||||
Uses Shell.Application's SelectItem(item, flags) API. Flags:
|
||||
0x01 = SVSI_SELECT
|
||||
0x04 = SVSI_DESELECTOTHERS (apply to the first item only when selecting multiple)
|
||||
0x08 = SVSI_ENSUREVISIBLE
|
||||
0x20 = SVSI_FOCUSED
|
||||
Returns $true on success, $false if any file wasn't found in the folder.
|
||||
.EXAMPLE
|
||||
$win = Get-PtExplorerWindows | Select-Object -First 1
|
||||
Select-PtExplorerFiles -ExplorerWindow $win -FileNames 'test-markdown.md','test-html.html','test-source.cs'
|
||||
Send-PtChord -Mods 0x11 -Key 0x20 # Ctrl+Space → Peek opens on 3 selected files
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)]$ExplorerWindow,
|
||||
[Parameter(Mandatory)][string[]]$FileNames
|
||||
)
|
||||
if (-not $ExplorerWindow.Document) { return $false }
|
||||
$folder = $ExplorerWindow.Document.Folder
|
||||
$first = $true
|
||||
foreach ($name in $FileNames) {
|
||||
$item = $folder.ParseName($name)
|
||||
if (-not $item) { Write-Warning "File not found in folder: $name"; return $false }
|
||||
# First item: SELECT + DESELECTOTHERS + ENSUREVISIBLE + FOCUSED = 0x2D
|
||||
# Subsequent items: SELECT + ENSUREVISIBLE = 0x09
|
||||
$flags = if ($first) { 0x2D } else { 0x09 }
|
||||
$ExplorerWindow.Document.SelectItem($item, $flags)
|
||||
$first = $false
|
||||
}
|
||||
Start-Sleep -Milliseconds 300
|
||||
return $true
|
||||
}
|
||||
|
||||
function Invoke-PtPeekWithExplorerSelection {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Set up an Explorer multi-file selection and trigger Peek via Ctrl+Space.
|
||||
Returns the new Peek window HWND, or $null on failure.
|
||||
.EXAMPLE
|
||||
$h = Invoke-PtPeekWithExplorerSelection -FolderPath D:\fixtures -FileNames 'a.png','b.md','c.cs'
|
||||
winapp ui invoke PinButton -w $h
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$FolderPath,
|
||||
[Parameter(Mandatory)][string[]]$FileNames
|
||||
)
|
||||
$win = Get-PtExplorerWindows | Where-Object { $_.LocationURL -match [regex]::Escape(($FolderPath -replace '\\','/')) } | Select-Object -First 1
|
||||
if (-not $win) { $win = Open-PtExplorerAtPath -Path $FolderPath }
|
||||
if (-not $win) { return $null }
|
||||
if (-not (Select-PtExplorerFiles -ExplorerWindow $win -FileNames $FileNames)) { return $null }
|
||||
|
||||
# Capture pre-state Peek HWND list to detect the new window
|
||||
$beforeHwnds = @(Get-Process PowerToys.Peek.UI -EA SilentlyContinue | ForEach-Object MainWindowHandle)
|
||||
|
||||
# Fire Ctrl+Space (Peek default). Requires pt-sendinput-chord.ps1 to be dot-sourced first.
|
||||
if (-not (Get-Command Send-PtChord -EA SilentlyContinue)) {
|
||||
throw "Send-PtChord not loaded. Dot-source scripts/pt-sendinput-chord.ps1 first."
|
||||
}
|
||||
Send-PtChord -Mods 0x11 -Key 0x20 | Out-Null # Ctrl+Space
|
||||
Start-Sleep -Milliseconds 1200
|
||||
|
||||
# Find the new Peek window HWND
|
||||
$afterHwnds = @(Get-Process PowerToys.Peek.UI -EA SilentlyContinue | ForEach-Object MainWindowHandle)
|
||||
$new = $afterHwnds | Where-Object { $_ -ne 0 -and $_ -notin $beforeHwnds } | Select-Object -First 1
|
||||
if (-not $new) { $new = $afterHwnds | Where-Object { $_ -ne 0 } | Select-Object -First 1 }
|
||||
return $new
|
||||
}
|
||||
|
||||
function Test-PtInteractiveDesktop {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Probe whether the current session is interactive (foreground + Shell COM both working).
|
||||
Returns a PSCustomObject with .ForegroundOk and .ShellComOk.
|
||||
.EXAMPLE
|
||||
$env = Test-PtInteractiveDesktop
|
||||
if (-not $env.ForegroundOk -or -not $env.ShellComOk) {
|
||||
Write-Warning "Non-interactive session — Explorer-driven techniques will fail."
|
||||
}
|
||||
#>
|
||||
Add-Type 'using System; using System.Runtime.InteropServices; public class FG3 { [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); }' -EA SilentlyContinue
|
||||
$hasFg = $false
|
||||
for ($i = 0; $i -lt 5; $i++) {
|
||||
if ([FG3]::GetForegroundWindow() -ne [IntPtr]::Zero) { $hasFg = $true; break }
|
||||
Start-Sleep -Milliseconds 200
|
||||
}
|
||||
$shellOk = $false
|
||||
try { @((New-Object -ComObject Shell.Application).Windows()).Count | Out-Null; $shellOk = $true } catch {}
|
||||
[pscustomobject]@{ ForegroundOk = $hasFg; ShellComOk = $shellOk }
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
# pt-explorer-contextmenu.ps1 — drive any Explorer (Win11) context-menu PowerToys module
|
||||
# end-to-end the way a real user does: open Explorer, select file(s), synthetic right-click
|
||||
# to OPEN the menu, then UIA-invoke the module's menu item by NAME (robust — no coordinate
|
||||
# click). Used by File Locksmith, Image Resizer, PowerRename, New+, etc.
|
||||
#
|
||||
# See explorer-context-menu-flow.md for the full write-up, stability notes, and per-module captions.
|
||||
#
|
||||
# Requires an UNLOCKED interactive desktop (synthetic right-click needs foreground). Check first:
|
||||
# if ([PtFg]::GetForegroundWindow() -eq [IntPtr]::Zero) -> desktop locked -> BLK-ENV.
|
||||
|
||||
Add-Type -TypeDefinition @'
|
||||
using System; using System.Runtime.InteropServices;
|
||||
public static class PtCtx {
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int c);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
||||
[DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
|
||||
[DllImport("user32.dll")] public static extern bool AttachThreadInput(uint a, uint b, bool f);
|
||||
[DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
|
||||
[DllImport("user32.dll")] public static extern void mouse_event(uint f, uint dx, uint dy, uint d, IntPtr e);
|
||||
public const uint RIGHTDOWN=0x0008, RIGHTUP=0x0010, LEFTDOWN=0x0002, LEFTUP=0x0004;
|
||||
public static void ForceForeground(IntPtr h) {
|
||||
IntPtr fg = GetForegroundWindow(); uint fp;
|
||||
uint ft = GetWindowThreadProcessId(fg, out fp); uint ct = GetCurrentThreadId();
|
||||
ShowWindow(h, 9);
|
||||
if (ft != 0 && ft != ct) AttachThreadInput(ct, ft, true);
|
||||
BringWindowToTop(h); SetForegroundWindow(h);
|
||||
if (ft != 0 && ft != ct) AttachThreadInput(ct, ft, false);
|
||||
}
|
||||
public static void RightClick(int x, int y) {
|
||||
SetCursorPos(x, y); System.Threading.Thread.Sleep(250);
|
||||
mouse_event(RIGHTDOWN,0,0,0,IntPtr.Zero); System.Threading.Thread.Sleep(70); mouse_event(RIGHTUP,0,0,0,IntPtr.Zero);
|
||||
}
|
||||
}
|
||||
'@ -ErrorAction SilentlyContinue
|
||||
|
||||
function Test-PtDesktopInteractive {
|
||||
# Polls up to $TimeoutSec for a foreground window. A momentary 0 is common for a few seconds
|
||||
# right after Restart-PtRunner / Explorer restart — without the poll that blip is misclassified
|
||||
# as a locked desktop (false BLK-ENV). A genuinely locked/non-interactive desktop stays 0 for
|
||||
# the whole window and still returns $false.
|
||||
param([int]$TimeoutSec = 5)
|
||||
$deadline = (Get-Date).AddSeconds($TimeoutSec)
|
||||
do {
|
||||
if ([PtCtx]::GetForegroundWindow() -ne [IntPtr]::Zero) { return $true }
|
||||
Start-Sleep -Milliseconds 250
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
return $false
|
||||
}
|
||||
|
||||
# Opens the Win11 context menu for a file in an already-open Explorer window and returns the
|
||||
# menu popup HWND. $ExplorerHwnd = the CabinetWClass window; $FileName = item to right-click.
|
||||
function Open-PtExplorerContextMenu {
|
||||
param([Parameter(Mandatory)][int]$ExplorerHwnd, [Parameter(Mandatory)][string]$FileName, [int]$MaxTries = 3)
|
||||
if (-not (Test-PtDesktopInteractive)) { throw 'BLK-ENV: desktop is locked / no foreground (GetForegroundWindow()=0). Unlock and retry.' }
|
||||
for ($try = 1; $try -le $MaxTries; $try++) {
|
||||
[PtCtx]::ForceForeground([IntPtr]$ExplorerHwnd); Start-Sleep -Milliseconds 500
|
||||
$item = (winapp ui search $FileName -w $ExplorerHwnd --json 2>$null | ConvertFrom-Json).matches |
|
||||
Where-Object { $_.type -eq 'ListItem' } | Select-Object -First 1
|
||||
if (-not $item) { throw "File item '$FileName' not found in Explorer window $ExplorerHwnd" }
|
||||
# Right-click near the row's LEFT edge (on the filename), not the geometric center:
|
||||
# in Details view the ListItem rect spans ~full row width (measured 71% of window), so
|
||||
# x+width/2 lands far right over other columns / empty canvas → background menu or missed
|
||||
# click. x + min(80, width/2) is on the filename in Details AND on the tile in Icons view.
|
||||
[PtCtx]::RightClick([int]($item.x + [Math]::Min(80, $item.width/2)), [int]($item.y + $item.height/2))
|
||||
Start-Sleep -Seconds 2
|
||||
# The Win11 menu is its own top-level popup window:
|
||||
$menu = winapp ui list-windows --json 2>$null | ConvertFrom-Json |
|
||||
Where-Object { $_.className -match 'PopupWindowSiteBridge' } | Sort-Object height -Descending | Select-Object -First 1
|
||||
if ($menu) { return $menu.hwnd }
|
||||
Start-Sleep -Milliseconds 500 # retry: foreground/menu wasn't ready (common on the first attempt right after Explorer opens)
|
||||
}
|
||||
throw "Context-menu popup window not found after $MaxTries right-click attempts"
|
||||
}
|
||||
|
||||
# Invokes a context-menu item by its visible NAME (robust — UIA InvokePattern, no coord click).
|
||||
# Returns $true if invoked. Match the module caption, e.g.:
|
||||
# File Locksmith -> 'Unlock with File Locksmith' PowerRename -> 'Rename with PowerRename'
|
||||
# Image Resizer -> 'Resize images' (verify by enumerating) New+ -> 'New+'
|
||||
function Invoke-PtContextMenuItem {
|
||||
param([Parameter(Mandatory)][int]$MenuHwnd, [Parameter(Mandatory)][string]$ItemName)
|
||||
$m = (winapp ui search $ItemName -w $MenuHwnd --json 2>$null | ConvertFrom-Json).matches |
|
||||
Where-Object { $_.type -eq 'MenuItem' } | Select-Object -First 1
|
||||
if (-not $m) { return $false } # caller can treat $false as "entry absent" (e.g. module disabled)
|
||||
winapp ui invoke $m.selector -w $MenuHwnd 2>$null | Out-Null
|
||||
return $true
|
||||
}
|
||||
|
||||
# Lists all context-menu item names (for discovering a module's caption or asserting absence).
|
||||
function Get-PtContextMenuItems {
|
||||
param([Parameter(Mandatory)][int]$MenuHwnd)
|
||||
winapp ui inspect -w $MenuHwnd --depth 8 2>$null | Out-String |
|
||||
Select-String 'MenuItem "([^"]+)"' -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Groups[1].Value }
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
# scripts/pt-foreground-guard.ps1
|
||||
# Verify and force a window to foreground BEFORE sending SendInput.
|
||||
# Without this guard, SendInput keys silently leak to the caller's terminal when
|
||||
# the target window has lost foreground (common with CmdPal AppX where Windows
|
||||
# foreground-lock blocks SetForegroundWindow after the first attempt).
|
||||
#
|
||||
# Use winapp ui set-value for UIA-friendly inputs (no foreground required).
|
||||
# Use this guard ONLY when you need real keystrokes (e.g. CmdPal alias detection).
|
||||
|
||||
if (-not ('PtFg' -as [type])) {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class PtFg {
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
||||
[DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
|
||||
[DllImport("user32.dll")] public static extern bool AttachThreadInput(uint a, uint b, bool f);
|
||||
[DllImport("user32.dll")] public static extern bool AllowSetForegroundWindow(int pid);
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
function Test-PtForeground {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Check whether the target AppX is currently foreground by parsing winapp ui list-windows output
|
||||
for the literal substring 'foreground'.
|
||||
#>
|
||||
param([Parameter(Mandatory)][string]$AppId)
|
||||
$r = winapp ui list-windows -a $AppId 2>$null | Out-String
|
||||
return ($r -match 'foreground')
|
||||
}
|
||||
|
||||
function Get-PtHwnd {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Return the first HWND for the given AppX/exe. Returns [IntPtr]::Zero if none.
|
||||
#>
|
||||
param([Parameter(Mandatory)][string]$AppId)
|
||||
$r = winapp ui list-windows -a $AppId 2>$null | Out-String
|
||||
if ($r -match 'HWND (\d+):') { return [IntPtr][int64]$matches[1] }
|
||||
return [IntPtr]::Zero
|
||||
}
|
||||
|
||||
function Force-PtForeground {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Force the target AppX window to foreground using the AttachThreadInput + AllowSetForegroundWindow
|
||||
trick. Returns $true if window is foreground after this attempt; $false otherwise.
|
||||
.NOTES
|
||||
Windows foreground-lock will block subsequent SetForegroundWindow calls in the same session if
|
||||
a real interactive event hasn't fired recently. If this returns $false repeatedly, the only
|
||||
reliable recovery is to recycle the AppX (kill + relaunch via shell:AppsFolder URI).
|
||||
#>
|
||||
param([Parameter(Mandatory)][string]$AppId)
|
||||
$h = Get-PtHwnd -AppId $AppId
|
||||
if ($h -eq [IntPtr]::Zero) { return $false }
|
||||
|
||||
# Permission grant
|
||||
$proc = Get-Process | Where-Object { $_.MainWindowHandle -eq $h } | Select-Object -First 1
|
||||
if ($proc) { [PtFg]::AllowSetForegroundWindow($proc.Id) | Out-Null }
|
||||
|
||||
[PtFg]::ShowWindow($h, 9) | Out-Null # SW_RESTORE
|
||||
Start-Sleep -Milliseconds 150
|
||||
|
||||
# AttachThreadInput trick
|
||||
$fg = [PtFg]::GetForegroundWindow()
|
||||
$fgPid = 0
|
||||
$fgThread = [PtFg]::GetWindowThreadProcessId($fg, [ref]$fgPid)
|
||||
$curThread = [PtFg]::GetCurrentThreadId()
|
||||
if ($fgThread -ne 0 -and $fgThread -ne $curThread) {
|
||||
[PtFg]::AttachThreadInput($curThread, $fgThread, $true) | Out-Null
|
||||
}
|
||||
[PtFg]::BringWindowToTop($h) | Out-Null
|
||||
[PtFg]::SetForegroundWindow($h) | Out-Null
|
||||
[PtFg]::ShowWindow($h, 5) | Out-Null # SW_SHOW
|
||||
if ($fgThread -ne 0 -and $fgThread -ne $curThread) {
|
||||
[PtFg]::AttachThreadInput($curThread, $fgThread, $false) | Out-Null
|
||||
}
|
||||
Start-Sleep -Milliseconds 400
|
||||
return (Test-PtForeground -AppId $AppId)
|
||||
}
|
||||
|
||||
function Assert-PtForegroundOrAbort {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Guard helper. Throws if the target AppX is NOT foreground. Use this immediately before any
|
||||
SendInput call to ensure keys don't leak to the wrong window.
|
||||
#>
|
||||
param([Parameter(Mandatory)][string]$AppId)
|
||||
if (-not (Test-PtForeground -AppId $AppId)) {
|
||||
if (-not (Force-PtForeground -AppId $AppId)) {
|
||||
throw "ABORT: $AppId is not foreground and cannot be forced foreground. SendInput would leak to wrong window."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
# pt-nonelevated.ps1 — launch a process at MEDIUM integrity (non-elevated) from an
|
||||
# already-elevated agent shell. Needed for tests that assert elevation-dependent
|
||||
# visibility (e.g. File Locksmith L649/L650: a non-elevated module must NOT see
|
||||
# higher-integrity processes; an elevated one must).
|
||||
#
|
||||
# The drive-stack in SKILL.md only covers gaining MORE privilege. De-elevation is the
|
||||
# opposite problem: from a High-IL shell you cannot simply CreateProcess a Medium-IL
|
||||
# child. The robust, dependency-free way is a one-shot Scheduled Task registered with
|
||||
# RunLevel=Limited + LogonType=Interactive, which lands on the logged-on user's desktop
|
||||
# at their filtered (medium) token. (The classic explorer-shell-injection trick is more
|
||||
# fragile across sessions.)
|
||||
#
|
||||
# Functions:
|
||||
# Start-PtNonElevated -Exe <path> [-Arguments <str>] -> launches a GUI/console exe non-elevated, returns the spawned PID(s)
|
||||
# Invoke-PtNonElevatedCapture -Exe <path> -Arguments <str> -OutFile <path> -> runs a console exe non-elevated, redirects stdout/err to a file, waits, returns the file path
|
||||
#
|
||||
# Verify elevation of the result with Test-ProcessElevated (scripts/pt-admin-probe.ps1).
|
||||
|
||||
function Start-PtNonElevated {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Exe,
|
||||
[string]$Arguments = '',
|
||||
[int]$WaitSeconds = 5,
|
||||
[string]$MatchProcessName # optional: base name to enumerate spawned PIDs (e.g. 'PowerToys.FileLocksmithUI')
|
||||
)
|
||||
if (-not (Test-Path $Exe)) { throw "Exe not found: $Exe" }
|
||||
$taskName = "PtNonElev_$([guid]::NewGuid().ToString('N').Substring(0,8))"
|
||||
$before = @()
|
||||
if ($MatchProcessName) { $before = @(Get-Process -Name $MatchProcessName -EA SilentlyContinue | Select-Object -Expand Id) }
|
||||
try {
|
||||
$action = New-ScheduledTaskAction -Execute $Exe -Argument $Arguments
|
||||
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -RunLevel Limited -LogonType Interactive
|
||||
Register-ScheduledTask -TaskName $taskName -Action $action -Principal $principal -Force | Out-Null
|
||||
Start-ScheduledTask -TaskName $taskName
|
||||
Start-Sleep -Seconds $WaitSeconds
|
||||
if ($MatchProcessName) {
|
||||
$after = @(Get-Process -Name $MatchProcessName -EA SilentlyContinue | Select-Object -Expand Id)
|
||||
return ($after | Where-Object { $_ -notin $before })
|
||||
}
|
||||
return $null
|
||||
}
|
||||
finally {
|
||||
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -EA SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-PtNonElevatedCapture {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Exe,
|
||||
[string]$Arguments = '',
|
||||
[Parameter(Mandatory)][string]$OutFile,
|
||||
[int]$TimeoutSeconds = 30
|
||||
)
|
||||
if (-not (Test-Path $Exe)) { throw "Exe not found: $Exe" }
|
||||
Remove-Item $OutFile -EA SilentlyContinue
|
||||
$wrap = [IO.Path]::ChangeExtension($OutFile, '.cmd')
|
||||
"`"$Exe`" $Arguments > `"$OutFile`" 2>&1" | Set-Content -Encoding ascii $wrap
|
||||
$taskName = "PtNonElev_$([guid]::NewGuid().ToString('N').Substring(0,8))"
|
||||
try {
|
||||
$action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument "/c `"$wrap`""
|
||||
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -RunLevel Limited -LogonType Interactive
|
||||
Register-ScheduledTask -TaskName $taskName -Action $action -Principal $principal -Force | Out-Null
|
||||
Start-ScheduledTask -TaskName $taskName
|
||||
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
|
||||
do { Start-Sleep 1; $info = Get-ScheduledTaskInfo -TaskName $taskName }
|
||||
while ($info.LastTaskResult -eq 267009 -and (Get-Date) -lt $deadline) # 267009 = task still running
|
||||
Start-Sleep 1
|
||||
return $OutFile
|
||||
}
|
||||
finally {
|
||||
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -EA SilentlyContinue
|
||||
Remove-Item $wrap -EA SilentlyContinue
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
# scripts/pt-sendinput-chord.ps1
|
||||
# Inject a global hotkey chord (e.g. Win+Shift+/) into the system input stream.
|
||||
# Critical: INPUT struct MUST be cb=40 on x64 (with padding for the MOUSEINPUT union member).
|
||||
# The common bug "Win+ hotkeys can't be injected" is a marshaling error producing 32-byte struct
|
||||
# and SendInput returns 0 with GetLastError()==87 (ERROR_INVALID_PARAMETER).
|
||||
#
|
||||
# This SHOULD be a last resort. Prefer Named Events (Invoke-PtSharedEvent) when the module exposes one.
|
||||
# Use this only for: (a) explicit hotkey-trigger verification tests, (b) modules without Named Events,
|
||||
# (c) UI keystrokes inside an already-foreground window (use Send-KeyToHwnd via PostMessage instead
|
||||
# for elevated -> non-elevated AppX, see references/winapp-ui-testing.md).
|
||||
|
||||
if (-not ('PtChord' -as [type])) {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Collections.Generic;
|
||||
public static class PtChord {
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct INPUT { public uint type; public KEYBDINPUT ki; public int pad1; public int pad2; } // pad to 40 bytes
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
||||
[DllImport("user32.dll", SetLastError=true)]
|
||||
static extern uint SendInput(uint n, INPUT[] p, int cb);
|
||||
const uint KEYUP = 0x0002;
|
||||
static INPUT K(ushort vk, bool up) { INPUT i=new INPUT(); i.type=1; i.ki.wVk=vk; i.ki.dwFlags=up?KEYUP:0; return i; }
|
||||
public static uint Chord(ushort[] mods, ushort key) {
|
||||
var l=new List<INPUT>();
|
||||
foreach(var m in mods) l.Add(K(m,false));
|
||||
l.Add(K(key,false)); l.Add(K(key,true));
|
||||
for(int i=mods.Length-1;i>=0;i--) l.Add(K(mods[i],true));
|
||||
var a=l.ToArray();
|
||||
return SendInput((uint)a.Length, a, Marshal.SizeOf(typeof(INPUT)));
|
||||
}
|
||||
public static uint Tap(ushort key) { return Chord(new ushort[0], key); }
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
# Common VK codes for chord mods:
|
||||
# LWIN=0x5B RWIN=0x5C CTRL=0x11 SHIFT=0x10 ALT=0x12
|
||||
# Main key VKs:
|
||||
# 0x08 Backspace 0x09 Tab 0x0D Enter 0x1B Escape 0x20 Space
|
||||
# 0x25 Left 0x26 Up 0x27 Right 0x28 Down
|
||||
# 0x30..0x39 0..9 0x41..0x5A A..Z
|
||||
|
||||
function Send-PtChord {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Inject a hotkey chord. Returns number of inputs Windows accepted (0 = failed; check GetLastError).
|
||||
.EXAMPLE
|
||||
Send-PtChord -Mods 0x5B,0x10 -Key 0x43 # Win+Shift+C (Color Picker)
|
||||
Send-PtChord -Mods 0x5B,0x11 -Key 0x52 # Win+Ctrl+R (PowerOcr)
|
||||
Send-PtChord -Mods 0x5B,0xA4 -Key 0x20 # Win+Alt+Space (CmdPal default)
|
||||
Send-PtChord -Key 0x0D # plain Enter (no mods)
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[uint16[]]$Mods = @(),
|
||||
[Parameter(Mandatory)][uint16]$Key
|
||||
)
|
||||
$sent = [PtChord]::Chord($Mods, $Key)
|
||||
if ($sent -eq 0) {
|
||||
$err = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
|
||||
throw "SendInput failed (returned 0, GetLastError=$err). Likely caller is at lower integrity than PT runner, or chord is OS-reserved (Win+L, Win+Tab)."
|
||||
}
|
||||
return $sent
|
||||
}
|
||||
|
||||
function Wait-PtHotkeyAccepted {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
After Send-PtChord, verify the PT runner saw it by tailing its log for the centralized-hook line.
|
||||
Returns the matching log line (if any) within $TimeoutSec.
|
||||
.EXAMPLE
|
||||
Send-PtChord -Mods 0x5B,0x10 -Key 0x43
|
||||
$line = Wait-PtHotkeyAccepted -ModuleHint 'Color' -TimeoutSec 3
|
||||
if (-not $line) { throw "Runner did not log hotkey invocation" }
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param([string]$ModuleHint = '', [int]$TimeoutSec = 3)
|
||||
$log = Get-ChildItem "$env:LOCALAPPDATA\Microsoft\PowerToys\RunnerLogs" -Filter 'runner-log_*.log' -EA SilentlyContinue |
|
||||
Sort-Object LastWriteTime -Descending | Select-Object -First 1
|
||||
if (-not $log) { return $null }
|
||||
$start = (Get-Date).AddSeconds(-2)
|
||||
$deadline = (Get-Date).AddSeconds($TimeoutSec)
|
||||
do {
|
||||
$line = Get-Content $log.FullName -Tail 50 -EA SilentlyContinue |
|
||||
Where-Object { $_ -match 'hotkey is invoked from Centralized keyboard hook' -and ($ModuleHint -eq '' -or $_ -match $ModuleHint) } |
|
||||
Select-Object -Last 1
|
||||
if ($line) { return $line }
|
||||
Start-Sleep -Milliseconds 200
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
return $null
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
# pt-session-diagnose.ps1
|
||||
# Diagnose whether the current shell can drive interactive PowerToys tests.
|
||||
# Tells you in one go: am I on the active console session, can I see foreground windows,
|
||||
# and can I use Shell COM. If not, prints the exact psexec mitigation command.
|
||||
|
||||
Add-Type 'using System; using System.Runtime.InteropServices;
|
||||
public class WTS { [DllImport("kernel32.dll")] public static extern uint WTSGetActiveConsoleSessionId(); }
|
||||
public class FG { [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); }'
|
||||
|
||||
Write-Host "--- Logged-on users + sessions ---" -ForegroundColor Cyan
|
||||
quser 2>&1
|
||||
|
||||
Write-Host "`n--- This shell's session ---" -ForegroundColor Cyan
|
||||
$me = [Diagnostics.Process]::GetCurrentProcess()
|
||||
" PID: $($me.Id)"
|
||||
" Session: $($me.SessionId)"
|
||||
|
||||
Write-Host "`n--- Console Explorer session(s) ---" -ForegroundColor Cyan
|
||||
$exps = Get-Process explorer -ErrorAction SilentlyContinue
|
||||
if ($exps) {
|
||||
$exps | Select-Object Id, SessionId, @{N='StartTime';E={$_.StartTime}} | Format-Table -AutoSize
|
||||
} else {
|
||||
Write-Host " (no explorer.exe running)" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
Write-Host "`n--- Windows active console + foreground + Shell COM ---" -ForegroundColor Cyan
|
||||
$activeConsole = [WTS]::WTSGetActiveConsoleSessionId()
|
||||
$fg = [FG]::GetForegroundWindow()
|
||||
$shellOk = $false
|
||||
try { @((New-Object -ComObject Shell.Application).Windows()).Count | Out-Null; $shellOk = $true } catch {}
|
||||
" WTSGetActiveConsoleSessionId() = $activeConsole"
|
||||
" GetForegroundWindow() = $fg"
|
||||
" Shell.Application available = $shellOk"
|
||||
|
||||
Write-Host "`n--- Verdict ---" -ForegroundColor Cyan
|
||||
$consoleSession = ($exps | Select-Object -First 1).SessionId
|
||||
if ($me.SessionId -eq $consoleSession -and $fg -ne 0 -and $shellOk) {
|
||||
Write-Host " PASS - this shell can drive interactive PowerToys tests." -ForegroundColor Green
|
||||
} elseif ($me.SessionId -eq $consoleSession -and $fg -eq 0) {
|
||||
Write-Host " WARN - same session as explorer but no foreground (workstation locked?). Unlock and re-run." -ForegroundColor Yellow
|
||||
} elseif (-not $shellOk) {
|
||||
Write-Host " FAIL - Shell COM unavailable (likely Session 0 / service context). Very few tests possible." -ForegroundColor Red
|
||||
} else {
|
||||
Write-Host " FAIL - shell in Session $($me.SessionId), console explorer in Session $consoleSession. Input injection denied." -ForegroundColor Red
|
||||
Write-Host " Mitigation: relaunch in the console session with:" -ForegroundColor Yellow
|
||||
Write-Host " psexec -accepteula -h -i $consoleSession -s pwsh.exe" -ForegroundColor Yellow
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
# scripts/pt-shared-events.ps1
|
||||
# Signal PowerToys modules via Win32 named events.
|
||||
# Catalog source: PowerToys repo src/common/interop/shared_constants.h
|
||||
# (Friendly-name mapping was originally surfaced by community frameworks; the values themselves
|
||||
# are stable PT public IPC names. This file is self-contained — no external repo required.)
|
||||
# Reason: instead of pressing a hotkey (which is racey, foreground-sensitive, and UIPI-fragile),
|
||||
# directly SetEvent on the kernel event the module is waiting on. Same code path as the hotkey.
|
||||
|
||||
if (-not ('PtEv' -as [type])) {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class PtEv {
|
||||
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
|
||||
private static extern IntPtr OpenEventW(uint dwAccess, bool bInherit, string lpName);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
private static extern bool SetEvent(IntPtr h);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
private static extern bool CloseHandle(IntPtr h);
|
||||
private const uint EVENT_MODIFY_STATE = 0x0002;
|
||||
private const uint SYNCHRONIZE = 0x00100000;
|
||||
|
||||
public static bool Signal(string fullName) {
|
||||
IntPtr h = OpenEventW(EVENT_MODIFY_STATE | SYNCHRONIZE, false, fullName);
|
||||
if (h == IntPtr.Zero) {
|
||||
int err = Marshal.GetLastWin32Error();
|
||||
throw new System.ComponentModel.Win32Exception(err,
|
||||
"OpenEvent failed for '" + fullName + "' (err=" + err + "). Owning module process may not be running.");
|
||||
}
|
||||
try { return SetEvent(h); } finally { CloseHandle(h); }
|
||||
}
|
||||
|
||||
public static bool Exists(string fullName) {
|
||||
IntPtr h = OpenEventW(SYNCHRONIZE, false, fullName);
|
||||
if (h == IntPtr.Zero) return false;
|
||||
CloseHandle(h); return true;
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
# Friendly-name -> full event name map (per Local\ namespace).
|
||||
# Source: <PT-repo>\src\common\interop\shared_constants.h
|
||||
$script:PtSharedEvents = @{
|
||||
# ── Hotkey-activated module triggers ──
|
||||
'AOT.Pin' = 'Local\AlwaysOnTopPinEvent-892e0aa2-cfa8-4cc4-b196-ddeb32314ce8'
|
||||
'AOT.IncreaseOpacity' = 'Local\AlwaysOnTopIncreaseOpacityEvent-a1b2c3d4-e5f6-7890-abcd-ef1234567890'
|
||||
'AOT.DecreaseOpacity' = 'Local\AlwaysOnTopDecreaseOpacityEvent-b2c3d4e5-f6a7-8901-bcde-f12345678901'
|
||||
'AdvancedPaste.ShowUI' = 'Local\PowerToys_AdvancedPaste_ShowUI'
|
||||
'CmdPal.Show' = 'Local\PowerToysCmdPal-ShowEvent-62336fcd-8611-4023-9b30-091a6af4cc5a'
|
||||
'ColorPicker.Show' = 'Local\ShowColorPickerEvent-8c46be2a-3e05-4186-b56b-4ae986ef2525'
|
||||
'CropAndLock.Reparent' = 'Local\PowerToysCropAndLockReparentEvent-6060860a-76a1-44e8-8d0e-6355785e9c36'
|
||||
'CropAndLock.Thumbnail' = 'Local\PowerToysCropAndLockThumbnailEvent-1637be50-da72-46b2-9220-b32b206b2434'
|
||||
'CursorWrap.Trigger' = 'Local\CursorWrapTriggerEvent-1f8452b5-4e6e-45b3-8b09-13f14a5900c9'
|
||||
'EnvVars.Show' = 'Local\PowerToysEnvironmentVariables-ShowEnvironmentVariablesEvent-1021f616-e951-4d64-b231-a8f972159978'
|
||||
'EnvVars.ShowAdmin' = 'Local\PowerToysEnvironmentVariables-EnvironmentVariablesAdminEvent-8c95d2ad-047c-49a2-9e8b-b4656326cfb2'
|
||||
'FancyZones.ToggleEditor' = 'Local\FancyZones-ToggleEditorEvent-1e174338-06a3-472b-874d-073b21c62f14'
|
||||
'FindMyMouse.Trigger' = 'Local\FindMyMouseTriggerEvent-5a9dc5f4-1c74-4f2f-a66f-1b9b6a2f9b23'
|
||||
'Hosts.Show' = 'Local\Hosts-ShowHostsEvent-5a0c0aae-5ff5-40f5-95c2-20e37ed671f0'
|
||||
'Hosts.ShowAdmin' = 'Local\Hosts-ShowHostsAdminEvent-60ff44e2-efd3-43bf-928a-f4d269f98bec'
|
||||
'LightSwitch.Toggle' = 'Local\PowerToys-LightSwitch-ToggleEvent-d8dc2f29-8c94-4ca1-8c5f-3e2b1e3c4f5a'
|
||||
'LightSwitch.Light' = 'Local\PowerToysLightSwitch-LightThemeEvent-50077121-2ffc-4841-9c86-ab1bd3f9baca'
|
||||
'LightSwitch.Dark' = 'Local\PowerToysLightSwitch-DarkThemeEvent-b3a835c0-eaa2-49b0-b8eb-f793e3df3368'
|
||||
'MeasureTool.Trigger' = 'Local\MeasureToolEvent-3d46745f-09b3-4671-a577-236be7abd199'
|
||||
'MouseCrosshairs.Trigger' = 'Local\MouseCrosshairsTriggerEvent-0d4c7f92-0a5c-4f5c-b64b-8a2a2f7e0b21'
|
||||
'MouseHighlighter.Trigger' = 'Local\MouseHighlighterTriggerEvent-1e3c9c3d-3fdf-4f9a-9a52-31c9b3c3a8f4'
|
||||
'MouseJump.Show' = 'Local\MouseJumpEvent-aa0be051-3396-4976-b7ba-1a9cc7d236a5'
|
||||
'NewKeyboardManager.Open' = 'Local\PowerToysOpenNewKeyboardManagerEvent-9c1d2e3f-4b5a-6c7d-8e9f-0a1b2c3d4e5f'
|
||||
'Peek.Show' = 'Local\ShowPeekEvent'
|
||||
'PowerDisplay.Toggle' = 'Local\PowerToysPowerDisplay-ToggleEvent-5f1a9c3e-7d2b-4e8f-9a6c-3b5d7e9f1a2c'
|
||||
'PowerLauncher.Invoke' = 'Local\PowerToysRunInvokeEvent-30f26ad7-d36d-4c0e-ab02-68bb5ff3c4ab'
|
||||
'PowerOcr.Show' = 'Local\PowerOCREvent-dc864e06-e1af-4ecc-9078-f98bee745e3a'
|
||||
'RegistryPreview.Trigger' = 'Local\RegistryPreviewEvent-4C559468-F75A-4E7F-BC4F-9C9688316687'
|
||||
'ShortcutGuide.Trigger' = 'Local\ShortcutGuide-TriggerEvent-d4275ad3-2531-4d19-9252-c0becbd9b496'
|
||||
'TextExtractor.Show' = 'Local\PowerOCREvent-dc864e06-e1af-4ecc-9078-f98bee745e3a'
|
||||
'Workspaces.Hotkey' = 'Local\PowerToys-Workspaces-HotkeyEvent-2625C3C8-BAC9-4DB3-BCD6-3B4391A26FD0'
|
||||
'Workspaces.LaunchEditor' = 'Local\Workspaces-LaunchEditorEvent-a55ff427-cf62-4994-a2cd-9f72139296bf'
|
||||
'ZoomIt.Zoom' = 'Local\PowerToysZoomIt-ZoomEvent-1e4190d7-94bc-4ad5-adc0-9a8fd07cb393'
|
||||
'ZoomIt.Draw' = 'Local\PowerToysZoomIt-DrawEvent-56338997-404d-4549-bd9a-d132b6766975'
|
||||
'ZoomIt.Break' = 'Local\PowerToysZoomIt-BreakEvent-17f2e63c-4c56-41dd-90a0-2d12f9f50c6b'
|
||||
'ZoomIt.LiveZoom' = 'Local\PowerToysZoomIt-LiveZoomEvent-390bf0c7-616f-47dc-bafe-a2d228add20d'
|
||||
'ZoomIt.Snip' = 'Local\PowerToysZoomIt-SnipEvent-2fd9c211-436d-4f17-a902-2528aaae3e30'
|
||||
'ZoomIt.SnipOcr' = 'Local\PowerToysZoomIt-SnipOcrEvent-a7c3b1d2-9e4f-4a6b-8d5c-1f2e3a4b5c6d'
|
||||
'ZoomIt.Record' = 'Local\PowerToysZoomIt-RecordEvent-74539344-eaad-4711-8e83-23946e424512'
|
||||
|
||||
# ── Termination triggers (clean shutdown without process kill) ──
|
||||
'AOT.Terminate' = 'Local\AlwaysOnTopTerminateEvent-cfdf1eae-791f-4953-8021-2f18f3837eae'
|
||||
'Awake.Exit' = 'Local\PowerToysAwakeExitEvent-c0d5e305-35fc-4fb5-83ec-f6070cfaf7fe'
|
||||
'CmdPal.Exit' = 'Local\PowerToysCmdPal-ExitEvent-eb73f6be-3f22-4b36-aee3-62924ba40bfd'
|
||||
'ColorPicker.Terminate' = 'Local\TerminateColorPickerEvent-3d676258-c4d5-424e-a87a-4be22020e813'
|
||||
'CropAndLock.Exit' = 'Local\PowerToysCropAndLockExitEvent-d995d409-7b70-482b-bad6-e7c8666f375a'
|
||||
'FZE.Exit' = 'Local\PowerToys-FZE-ExitEvent-ca8c73de-a52c-4274-b691-46e9592d3b43'
|
||||
'Hosts.Terminate' = 'Local\Hosts-TerminateHostsEvent-d5410d5e-45a6-4d11-bbf0-a4ec2d064888'
|
||||
'KBM.Terminate' = 'Local\TerminateKBMSharedEvent-a787c967-55b6-47de-94d9-56f39fed839e'
|
||||
'MouseJump.Terminate' = 'Local\TerminateMouseJumpEvent-252fa337-317f-4c37-a61f-99464c3f9728'
|
||||
'Peek.Terminate' = 'Local\TerminatePeekEvent-267149fe-7ed2-427d-a3ad-9e18203c037c'
|
||||
'PowerAccent.Exit' = 'Local\PowerToysPowerAccentExitEvent-53e93389-d19a-4fbb-9b36-1981c8965e17'
|
||||
'PowerOcr.Terminate' = 'Local\TerminatePowerOCREvent-08e5de9d-15df-4ea8-8840-487c13435a67'
|
||||
'PowerDisplay.Terminate' = 'Local\PowerToysPowerDisplay-TerminateEvent-7b9c2e1f-8a5d-4c3e-9f6b-2a1d8c5e3b7a'
|
||||
'Run.Exit' = 'Local\PowerToysRunExitEvent-3e38e49d-a762-4ef1-88f2-fd4bc7481516'
|
||||
'ShortcutGuide.Exit' = 'Local\ShortcutGuide-ExitEvent-35697cdd-a3d2-47d6-a246-34efcc73eac0'
|
||||
'Settings.Terminate' = 'Local\PowerToysRunnerTerminateSettingsEvent-c34cb661-2e69-4613-a1f8-4e39c25d7ef6'
|
||||
'ZoomIt.Exit' = 'Local\PowerToysZoomIt-ExitEvent-36641ce6-df02-4eac-abea-a3fbf9138220'
|
||||
'GrabAndMove.Exit' = 'Local\PowerToysGrabAndMove-ExitEvent-b8c4d2e3-5f6a-7b8c-9d0e-1f2a3b4c5d6e'
|
||||
}
|
||||
|
||||
function Invoke-PtSharedEvent {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Signal a PowerToys named kernel event by friendly name (e.g. 'CmdPal.Show')
|
||||
or by full event path (e.g. 'Local\PowerToys_AdvancedPaste_ShowUI').
|
||||
Returns $true on success; throws if event doesn't exist or owner not running.
|
||||
.EXAMPLE
|
||||
Invoke-PtSharedEvent -Name 'CmdPal.Show'
|
||||
Invoke-PtSharedEvent -Name 'PowerLauncher.Invoke'
|
||||
Invoke-PtSharedEvent -Name 'AOT.Pin'
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory)][string]$Name)
|
||||
$eventName = if ($script:PtSharedEvents.ContainsKey($Name)) { $script:PtSharedEvents[$Name] } else { $Name }
|
||||
return [PtEv]::Signal($eventName)
|
||||
}
|
||||
|
||||
function Test-PtSharedEvent {
|
||||
[CmdletBinding()] param([Parameter(Mandatory)][string]$Name)
|
||||
$eventName = if ($script:PtSharedEvents.ContainsKey($Name)) { $script:PtSharedEvents[$Name] } else { $Name }
|
||||
return [PtEv]::Exists($eventName)
|
||||
}
|
||||
|
||||
function Get-PtSharedEventCatalog {
|
||||
$script:PtSharedEvents.GetEnumerator() | Sort-Object Name |
|
||||
ForEach-Object { [pscustomobject]@{ Name = $_.Key; Event = $_.Value } }
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
# scripts/pt-shell-verbs.ps1
|
||||
# Enumerate Windows classic shell verbs (HKCR-registered) via Shell.Application COM.
|
||||
#
|
||||
# SCOPE WARNING: this does NOT find PowerToys context-menu items on Win11. PT registers
|
||||
# PowerRename, Image Resizer, File Locksmith, New+ etc. via IExplorerCommand (Tier-1 modern
|
||||
# menu), which is invisible to Shell.Application.Verbs(). For PT-context-menu drives, use
|
||||
# `pt-explorer-contextmenu.ps1` (synthetic right-click + UIA invoke). See
|
||||
# `explorer-context-menu-flow.md` for the canonical pattern.
|
||||
#
|
||||
# Useful for: enumerating non-PT classic verbs (Open, Edit, Send-to, third-party shell extensions),
|
||||
# and as a negative check that PT verbs are NOT classic-shadowed.
|
||||
|
||||
function Get-PtShellVerbs {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Enumerate classic HKCR shell verbs on a file or folder. Returns Name + the underlying Verb COM object.
|
||||
.EXAMPLE
|
||||
Get-PtShellVerbs -Path 'D:\fixtures\image.png' | Format-Table Name
|
||||
#>
|
||||
[CmdletBinding()] param([Parameter(Mandatory)][string]$Path)
|
||||
if (-not (Test-Path $Path)) { throw "Path not found: $Path" }
|
||||
$abs = (Resolve-Path $Path).Path
|
||||
$folder = Split-Path -Parent $abs
|
||||
$leaf = Split-Path -Leaf $abs
|
||||
$shell = New-Object -ComObject Shell.Application
|
||||
$ns = $shell.NameSpace($folder)
|
||||
if (-not $ns) { throw "Cannot open folder namespace: $folder" }
|
||||
$item = $ns.ParseName($leaf)
|
||||
if (-not $item) { throw "File not in folder: $leaf" }
|
||||
return @($item.Verbs()) | ForEach-Object {
|
||||
[pscustomobject]@{ Name = $_.Name; Verb = $_ }
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-PtShellVerb {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Invoke a classic shell verb on a file by name-regex match. Returns $true on success.
|
||||
Does NOT work for PT Win11 modern-menu items — see SCOPE WARNING at top.
|
||||
.EXAMPLE
|
||||
Invoke-PtShellVerb -Path 'D:\fixtures\img.png' -NamePattern '^Edit$'
|
||||
#>
|
||||
[CmdletBinding()] param(
|
||||
[Parameter(Mandatory)][string]$Path,
|
||||
[Parameter(Mandatory)][string]$NamePattern
|
||||
)
|
||||
$verb = Get-PtShellVerbs -Path $Path | Where-Object { $_.Name -match $NamePattern } | Select-Object -First 1
|
||||
if (-not $verb) {
|
||||
Write-Warning "No classic shell verb matching '$NamePattern' on '$Path'. (Win11 PT modern-menu items are NOT visible here — use pt-explorer-contextmenu.ps1 instead.)"
|
||||
return $false
|
||||
}
|
||||
$verb.Verb.DoIt()
|
||||
return $true
|
||||
}
|
||||
|
||||
function Reset-PtShellComCache {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Release current Shell.Application COM instance + force a fresh one on next call.
|
||||
Use when you've installed/registered a shell handler mid-test and the cached verb list
|
||||
still reflects the old state.
|
||||
#>
|
||||
[System.Runtime.InteropServices.Marshal]::CleanupUnusedObjectsInCurrentContext()
|
||||
[System.GC]::Collect()
|
||||
[System.GC]::WaitForPendingFinalizers()
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
# scripts/pt-state.ps1
|
||||
# Common state-verification helpers: settings.json diff, runner log grep, GPO log check,
|
||||
# process spawn detection, AppX probe.
|
||||
|
||||
function Get-PtSettings {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Read the master PT settings.json (enabled.<Module> flags + run_elevated + theme + language).
|
||||
#>
|
||||
$f = "$env:LOCALAPPDATA\Microsoft\PowerToys\settings.json"
|
||||
if (-not (Test-Path $f)) { return $null }
|
||||
Get-Content $f -Raw | ConvertFrom-Json
|
||||
}
|
||||
|
||||
function Get-PtModuleSettings {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Read a single module's settings.json (e.g. AdvancedPaste, FancyZones, etc.).
|
||||
These ARE auto-reloaded by the per-module file watcher (~3s debounce).
|
||||
#>
|
||||
param([Parameter(Mandatory)][string]$ModuleDir)
|
||||
$f = "$env:LOCALAPPDATA\Microsoft\PowerToys\$ModuleDir\settings.json"
|
||||
if (-not (Test-Path $f)) { return $null }
|
||||
Get-Content $f -Raw | ConvertFrom-Json
|
||||
}
|
||||
|
||||
function Get-CmdPalSettings {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Read CmdPal AppX settings.json (sandboxed path). Contains 19 ProviderSettings, DockSettings,
|
||||
GalleryFeedUrl, EscapeKeyBehaviorSetting, AutoGoHomeInterval, Hotkey, Aliases, etc.
|
||||
#>
|
||||
$f = "$env:LOCALAPPDATA\Packages\Microsoft.CommandPalette_8wekyb3d8bbwe\LocalState\settings.json"
|
||||
if (-not (Test-Path $f)) { return $null }
|
||||
Get-Content $f -Raw | ConvertFrom-Json
|
||||
}
|
||||
|
||||
function Get-PtRunnerLogTail {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Tail the latest runner-log_<date>.log file for matching lines.
|
||||
.EXAMPLE
|
||||
Get-PtRunnerLogTail -Pattern 'hotkey is invoked' -TailLines 100
|
||||
Get-PtRunnerLogTail -Pattern 'GPO sets' -TailLines 50
|
||||
#>
|
||||
param([string]$Pattern = '.*', [int]$TailLines = 50)
|
||||
$log = Get-ChildItem "$env:LOCALAPPDATA\Microsoft\PowerToys\RunnerLogs" -Filter 'runner-log_*.log' -EA SilentlyContinue |
|
||||
Sort-Object LastWriteTime -Descending | Select-Object -First 1
|
||||
if (-not $log) { return @() }
|
||||
Get-Content $log.FullName -Tail $TailLines -EA SilentlyContinue | Where-Object { $_ -match $Pattern }
|
||||
}
|
||||
|
||||
function Test-PtModuleEnabled {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Check whether a specific module is enabled in master settings.json.
|
||||
Note: PT Run uses the key "PowerToys Run" (with space).
|
||||
#>
|
||||
param([Parameter(Mandatory)][string]$ModuleKey)
|
||||
$s = Get-PtSettings
|
||||
if (-not $s) { return $false }
|
||||
return [bool]$s.enabled.$ModuleKey
|
||||
}
|
||||
|
||||
function Test-PtModuleProcess {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Return the process(es) for a module exe name (e.g. 'PowerToys.AdvancedPaste').
|
||||
Returns empty array if not running.
|
||||
#>
|
||||
param([Parameter(Mandatory)][string]$ExeName)
|
||||
@(Get-Process $ExeName -EA SilentlyContinue)
|
||||
}
|
||||
|
||||
function Restart-PtRunner {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Kill the runner and relaunch to force fresh load of master settings.json.
|
||||
The runner does NOT auto-pickup edits to the top-level enabled.<Module> flags.
|
||||
#>
|
||||
$pt = Get-Process PowerToys -EA SilentlyContinue | Select-Object -First 1
|
||||
if ($pt) { Stop-Process -Id $pt.Id -Force; Start-Sleep -Milliseconds 800 }
|
||||
Start-Process "$env:LOCALAPPDATA\PowerToys\PowerToys.exe"
|
||||
Start-Sleep -Seconds 3
|
||||
}
|
||||
|
||||
function Backup-PtModuleSettings {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Snapshot a module's settings.json to TEMP for restore-on-exit. Returns the backup path.
|
||||
.EXAMPLE
|
||||
$bk = Backup-PtModuleSettings -ModuleDir AdvancedPaste
|
||||
try { ... mutate ... } finally { Restore-PtModuleSettings -ModuleDir AdvancedPaste -BackupPath $bk }
|
||||
#>
|
||||
param([Parameter(Mandatory)][string]$ModuleDir)
|
||||
$src = "$env:LOCALAPPDATA\Microsoft\PowerToys\$ModuleDir\settings.json"
|
||||
if (-not (Test-Path $src)) { return $null }
|
||||
$bk = Join-Path $env:TEMP ("ptbk-$ModuleDir-$(Get-Random -Maximum 9999).json")
|
||||
Copy-Item -Path $src -Destination $bk -Force
|
||||
return $bk
|
||||
}
|
||||
|
||||
function Restore-PtModuleSettings {
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$ModuleDir,
|
||||
[Parameter(Mandatory)][string]$BackupPath
|
||||
)
|
||||
$dst = "$env:LOCALAPPDATA\Microsoft\PowerToys\$ModuleDir\settings.json"
|
||||
Copy-Item -Path $BackupPath -Destination $dst -Force
|
||||
Remove-Item $BackupPath -Force -EA SilentlyContinue
|
||||
}
|
||||
21
.github/skills/pr-review/LICENSE.txt
vendored
Normal file
21
.github/skills/pr-review/LICENSE.txt
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
121
.github/skills/pr-review/SKILL.md
vendored
Normal file
121
.github/skills/pr-review/SKILL.md
vendored
Normal file
@@ -0,0 +1,121 @@
|
||||
---
|
||||
name: pr-review
|
||||
description: Comprehensive pull request review with multi-step analysis and comment posting. Use when asked to review a PR, analyze pull request changes, check PR for issues, post review comments, validate PR quality, run code review on a PR, or audit pull request. Generates 13 review step files covering functionality, security, performance, accessibility, and more.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# PR Review Skill
|
||||
|
||||
Perform comprehensive pull request reviews with multi-step analysis covering functionality, security, performance, accessibility, localization, and more.
|
||||
|
||||
## Skill Contents
|
||||
|
||||
This skill is **self-contained** with all required resources:
|
||||
|
||||
```
|
||||
.github/skills/pr-review/
|
||||
├── SKILL.md # This file
|
||||
├── LICENSE.txt # MIT License
|
||||
├── scripts/
|
||||
│ ├── Start-PRReviewWorkflow.ps1 # Main review script
|
||||
│ ├── Get-GitHubPrFilePatch.ps1 # Fetch PR file diffs
|
||||
│ ├── Get-GitHubRawFile.ps1 # Download repo files
|
||||
│ ├── Get-PrIncrementalChanges.ps1 # Detect incremental changes
|
||||
│ └── Test-IncrementalReview.ps1 # Test incremental detection
|
||||
└── references/
|
||||
├── review-pr.prompt.md # Full review prompt
|
||||
└── fix-pr-active-comments.prompt.md # Comment fix prompt
|
||||
```
|
||||
|
||||
## Output Directory
|
||||
|
||||
All generated artifacts are placed under `Generated Files/prReview/<pr-number>/` at the repository root (gitignored).
|
||||
|
||||
```
|
||||
Generated Files/prReview/
|
||||
└── <pr-number>/
|
||||
├── 00-OVERVIEW.md # Summary with all findings
|
||||
├── 01-functionality.md # Functional correctness
|
||||
├── 02-compatibility.md # Breaking changes, versioning
|
||||
├── 03-performance.md # Performance implications
|
||||
├── 04-accessibility.md # A11y compliance
|
||||
├── 05-security.md # Security concerns
|
||||
├── 06-localization.md # L10n readiness
|
||||
├── 07-globalization.md # G11n considerations
|
||||
├── 08-extensibility.md # API/extension points
|
||||
├── 09-solid-design.md # SOLID principles
|
||||
├── 10-repo-patterns.md # PowerToys conventions
|
||||
├── 11-docs-automation.md # Documentation coverage
|
||||
├── 12-code-comments.md # Code comment quality
|
||||
└── 13-copilot-guidance.md # (if applicable)
|
||||
```
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Review a specific pull request
|
||||
- Analyze PR changes for quality issues
|
||||
- Post review comments on a PR
|
||||
- Validate PR against PowerToys standards
|
||||
- Run comprehensive code review
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- GitHub CLI (`gh`) installed and authenticated
|
||||
- PowerShell 7+ for running scripts
|
||||
- GitHub MCP configured (for posting comments)
|
||||
|
||||
## Required Variables
|
||||
|
||||
⚠️ **Before starting**, confirm `{{PRNumber}}` with the user. If not provided, **ASK**: "What PR number should I review?"
|
||||
|
||||
| Variable | Description | Example |
|
||||
|----------|-------------|---------|
|
||||
| `{{PRNumber}}` | Pull request number to review | `45234` |
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Run PR Review
|
||||
|
||||
Execute the review workflow (use paths relative to this skill folder):
|
||||
|
||||
```powershell
|
||||
# From repo root
|
||||
.github/skills/pr-review/scripts/Start-PRReviewWorkflow.ps1 -PRNumbers {{PRNumber}} -CLIType copilot
|
||||
```
|
||||
|
||||
This will:
|
||||
1. Optionally assign GitHub Copilot as reviewer
|
||||
2. Fetch PR diff and changed files
|
||||
3. Generate 13 review step files
|
||||
4. Post findings as review comments
|
||||
|
||||
### Step 2: Review Output
|
||||
|
||||
Check the generated files at `Generated Files/prReview/{{PRNumber}}/`
|
||||
|
||||
## CLI Options
|
||||
|
||||
| Parameter | Description | Default |
|
||||
|-----------|-------------|---------|
|
||||
| `-PRNumbers` | PR number(s) to review | From worktrees |
|
||||
| `-CLIType` | AI CLI to use: `copilot` or `claude` | `copilot` |
|
||||
| `-MinSeverity` | Min severity to post: `high`, `medium`, `low`, `info` | `medium` |
|
||||
| `-SkipAssign` | Skip assigning Copilot as reviewer | `false` |
|
||||
| `-SkipReview` | Skip the review step | `false` |
|
||||
| `-SkipFix` | Skip the fix step | `false` |
|
||||
| `-MaxParallel` | Maximum parallel jobs | `3` |
|
||||
| `-Force` | Skip confirmation prompts | `false` |
|
||||
|
||||
## AI Prompt References
|
||||
|
||||
For manual AI invocation, prompts are at:
|
||||
- `references/review-pr.prompt.md` - Full review instructions
|
||||
- `references/fix-pr-active-comments.prompt.md` - Comment fix instructions
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Solution |
|
||||
|---------|----------|
|
||||
| PR not found | Verify PR number: `gh pr view {{PRNumber}}` |
|
||||
| Review incomplete | Check `_copilot-review.log` for errors |
|
||||
| Comments not posted | Ensure GitHub MCP is configured |
|
||||
70
.github/skills/pr-review/references/fix-pr-active-comments.prompt.md
vendored
Normal file
70
.github/skills/pr-review/references/fix-pr-active-comments.prompt.md
vendored
Normal file
@@ -0,0 +1,70 @@
|
||||
---
|
||||
description: 'Fix active pull request comments with scoped changes'
|
||||
name: 'fix-pr-active-comments'
|
||||
agent: 'agent'
|
||||
argument-hint: 'PR number or active PR URL'
|
||||
---
|
||||
|
||||
# Fix Active PR Comments
|
||||
|
||||
## Mission
|
||||
Resolve active pull request comments by applying only simple fixes. For complex refactors, write a plan instead of changing code.
|
||||
|
||||
## Scope & Preconditions
|
||||
- You must have an active pull request context or a provided PR number.
|
||||
- Only implement simple changes. Do not implement large refactors.
|
||||
- If required context is missing, request it and stop.
|
||||
|
||||
## Inputs
|
||||
- Required: ${input:pr_number:PR number or URL}
|
||||
- Optional: ${input:comment_scope:files or areas to focus on}
|
||||
- Optional: ${input:fixing_guidelines:additional fixing guidelines from the user}
|
||||
|
||||
## Workflow
|
||||
1. Locate all active (unresolved) PR review comments for the given PR.
|
||||
2. For each comment, classify the change scope:
|
||||
- Simple change: limited edits, localized fix, low risk, no broad redesign.
|
||||
- Large refactor: multi-file redesign, architecture change, or risky behavior change.
|
||||
3. For each large refactor request:
|
||||
- Do not modify code.
|
||||
- Write a planning document to Generated Files/prReview/${input:pr_number}/fixPlan/.
|
||||
4. For each simple change request:
|
||||
- Implement the fix with minimal edits.
|
||||
- Run quick checks if needed.
|
||||
- Commit and push the change.
|
||||
5. For comments that seem invalid, unclear, or not applicable (even if simple):
|
||||
- Do not change code.
|
||||
- Add the item to a summary table in Generated Files/prReview/${input:pr_number}/fixPlan/overview.md.
|
||||
- Consult back to the end user in a friendly, polite tone.
|
||||
6. Respond to each comment that you fixed:
|
||||
- Reply in the active conversation.
|
||||
- Use a polite or friendly tone.
|
||||
- Keep the response under 200 words.
|
||||
- Resolve the comment after replying.
|
||||
|
||||
## Output Expectations
|
||||
- Simple fixes: code changes committed and pushed.
|
||||
- Large refactors: a plan file saved to Generated Files/prReview/${input:pr_number}/fixPlan/.
|
||||
- Invalid or unclear comments: captured in Generated Files/prReview/${input:pr_number}/fixPlan/overview.md.
|
||||
- Each fixed comment has a reply under 200 words and is resolved.
|
||||
|
||||
## Plan File Template
|
||||
Use this template for each large refactor item:
|
||||
|
||||
# Fix Plan: <short title>
|
||||
|
||||
## Context
|
||||
- Comment link:
|
||||
- Impacted areas:
|
||||
|
||||
## Overview Table Template
|
||||
Use this table in Generated Files/prReview/${input:pr_number}/fixPlan/overview.md:
|
||||
|
||||
| Comment link | Summary | Reason not applied | Suggested follow-up |
|
||||
| --- | --- | --- | --- |
|
||||
| | | | |
|
||||
|
||||
## Quality Assurance
|
||||
- Verify plan file path exists.
|
||||
- Ensure no code changes were made for large refactor items.
|
||||
- Confirm replies are under 200 words and comments are resolved.
|
||||
9
.github/skills/pr-review/references/mcp-config.json
vendored
Normal file
9
.github/skills/pr-review/references/mcp-config.json
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"github-artifacts": {
|
||||
"command": "cmd",
|
||||
"args": ["/c", "for /f %i in ('git rev-parse --show-toplevel') do node %i/tools/mcp/github-artifacts/launch.js"],
|
||||
"tools": ["*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
198
.github/skills/pr-review/references/review-pr.prompt.md
vendored
Normal file
198
.github/skills/pr-review/references/review-pr.prompt.md
vendored
Normal file
@@ -0,0 +1,198 @@
|
||||
---
|
||||
agent: 'agent'
|
||||
description: 'Perform a comprehensive PR review with per-step Markdown and machine-readable outputs'
|
||||
---
|
||||
|
||||
# Review Pull Request
|
||||
|
||||
**Goal**: Given `{{pr_number}}`, run a *one-topic-per-step* review. Write files to `Generated Files/prReview/{{pr_number}}/` (replace `{{pr_number}}` with the integer). Emit machine‑readable blocks for a GitHub MCP to post review comments.
|
||||
|
||||
## PR selection
|
||||
Resolve the target PR using these fallbacks in order:
|
||||
1. Parse the invocation text for an explicit identifier (first integer following patterns such as a leading hash and digits or the text `PR:` followed by digits).
|
||||
2. If no PR is found yet, locate the newest `Generated Files/prReview/_batch/batch-overview-*.md` file (highest timestamp in filename, fallback newest mtime) and take the first entry in its `## PRs` list whose review folder is missing `00-OVERVIEW.md` or contains `__error.flag`.
|
||||
3. If the batch file has no pending PRs, query assignments with `gh pr list --assignee @me --state open --json number,updatedAt --limit 20` and pick the most recently updated PR that does not already have a completed review folder.
|
||||
4. If still unknown, run `gh pr view --json number` in the current branch and use that result when it is unambiguous.
|
||||
5. If every step above fails, prompt the user for a PR number before proceeding.
|
||||
|
||||
## Fetch PR data with `gh`
|
||||
- `gh pr view {{pr_number}} --json number,baseRefName,headRefName,baseRefOid,headRefOid,changedFiles,files`
|
||||
- `gh api repos/:owner/:repo/pulls/{{pr_number}}/files?per_page=250` # patches for line mapping
|
||||
|
||||
### Incremental review workflow
|
||||
1. **Check for existing review**: Read `Generated Files/prReview/{{pr_number}}/00-OVERVIEW.md`
|
||||
2. **Extract state**: Parse `Last reviewed SHA:` from review metadata section
|
||||
3. **Detect changes**: Run `Get-PrIncrementalChanges.ps1 -PullRequestNumber {{pr_number}} -LastReviewedCommitSha {{sha}}`
|
||||
4. **Analyze result**:
|
||||
- `NeedFullReview: true` → Review all files in the PR
|
||||
- `NeedFullReview: false` and `IsIncremental: true` → Review only files in `ChangedFiles` array
|
||||
- `ChangedFiles` is empty → No changes, skip review (update iteration history with "No changes since last review")
|
||||
5. **Apply smart filtering**: Use the file patterns in smart step filtering table to skip irrelevant steps
|
||||
6. **Update metadata**: After completing review, save current `headRefOid` as `Last reviewed SHA:` in `00-OVERVIEW.md`
|
||||
|
||||
### Reusable PowerShell scripts
|
||||
Scripts live in `.github/review-tools/` to avoid repeated manual approvals during PR reviews:
|
||||
|
||||
| Script | Usage |
|
||||
| --- | --- |
|
||||
| `.github/review-tools/Get-GitHubRawFile.ps1` | Download a repository file at a given ref, optionally with line numbers. |
|
||||
| `.github/review-tools/Get-GitHubPrFilePatch.ps1` | Fetch the unified diff for a specific file within a pull request via `gh api`. |
|
||||
| `.github/review-tools/Get-PrIncrementalChanges.ps1` | Compare last reviewed SHA with current PR head to identify incremental changes. Returns JSON with changed files, new commits, and whether full review is needed. |
|
||||
| `.github/review-tools/Test-IncrementalReview.ps1` | Test helper to preview incremental review detection for a PR. Use before running full review to see what changed. |
|
||||
|
||||
Always prefer these scripts (or new ones added under `.github/review-tools/`) over raw `gh api` or similar shell commands so the review flow does not trigger interactive approval prompts.
|
||||
|
||||
## Output files
|
||||
Folder: `Generated Files/prReview/{{pr_number}}/`
|
||||
Files: `00-OVERVIEW.md`, `01-functionality.md`, `02-compatibility.md`, `03-performance.md`, `04-accessibility.md`, `05-security.md`, `06-localization.md`, `07-globalization.md`, `08-extensibility.md`, `09-solid-design.md`, `10-repo-patterns.md`, `11-docs-automation.md`, `12-code-comments.md`, `13-copilot-guidance.md` *(only if guidance md exists).*
|
||||
- **Write-after-step rule:** Immediately after completing each TODO step, persist that step's markdown file before proceeding to the next. Generate `00-OVERVIEW.md` only after every step file has been refreshed for the current run.
|
||||
|
||||
## Iteration management
|
||||
- Determine the current review iteration by reading `00-OVERVIEW.md` (look for `Review iteration:`). If missing, assume iteration `1`.
|
||||
- Extract the last reviewed SHA from `00-OVERVIEW.md` (look for `Last reviewed SHA:` in the review metadata section). If missing, this is iteration 1.
|
||||
- **Incremental review detection**:
|
||||
1. Call `.github/review-tools/Get-PrIncrementalChanges.ps1 -PullRequestNumber {{pr_number}} -LastReviewedCommitSha {{last_sha}}` to get delta analysis.
|
||||
2. Parse the JSON result to determine if incremental review is possible (`IsIncremental: true`, `NeedFullReview: false`).
|
||||
3. If force-push detected or first review, proceed with full review of all changed files.
|
||||
4. If incremental, review only the files listed in `ChangedFiles` array and apply smart step filtering (see below).
|
||||
- Increment the iteration for each review run and propagate the new value to all step files and the overview.
|
||||
- Preserve prior iteration notes by keeping/expanding an `## Iteration history` section in each markdown file, appending the newest summary under `### Iteration <N>`.
|
||||
- Summaries should capture key deltas since the previous iteration so reruns can pick up context quickly.
|
||||
- **After review completion**, update `Last reviewed SHA:` in `00-OVERVIEW.md` with the current `headRefOid` and update the timestamp.
|
||||
|
||||
### Smart step filtering (incremental reviews only)
|
||||
When performing incremental review, skip steps that are irrelevant based on changed file types:
|
||||
|
||||
| File pattern | Required steps | Skippable steps |
|
||||
| --- | --- | --- |
|
||||
| `**/*.cs`, `**/*.cpp`, `**/*.h` | Functionality, Compatibility, Performance, Security, SOLID, Repo patterns, Code comments | (depends on files) |
|
||||
| `**/*.resx`, `**/Resources/*.xaml` | Localization, Globalization | Most others |
|
||||
| `**/*.md` (docs) | Docs & automation | Most others (unless copilot guidance) |
|
||||
| `**/*copilot*.md`, `.github/prompts/*.md` | Copilot guidance, Docs & automation | Most others |
|
||||
| `**/*.csproj`, `**/*.vcxproj`, `**/packages.config` | Compatibility, Security, Repo patterns | Localization, Globalization, Accessibility |
|
||||
| `**/UI/**`, `**/*View.xaml` | Accessibility, Localization | Performance (unless perf-sensitive controls) |
|
||||
|
||||
**Default**: If uncertain or files span multiple categories, run all applicable steps. When in doubt, be conservative and review more rather than less.
|
||||
|
||||
## TODO steps (one concern each)
|
||||
1) Functionality
|
||||
2) Compatibility
|
||||
3) Performance
|
||||
4) Accessibility
|
||||
5) Security
|
||||
6) Localization
|
||||
7) Globalization
|
||||
8) Extensibility
|
||||
9) SOLID principles
|
||||
10) Repo patterns
|
||||
11) Docs & automation coverage for the changes
|
||||
12) Code comments
|
||||
13) Copilot guidance (conditional): if changed folders contain `*copilot*.md` or `.github/prompts/*.md`, review diffs **against** that guidance and write `13-copilot-guidance.md` (omit if none).
|
||||
|
||||
## Per-step file template (use verbatim)
|
||||
```md
|
||||
# <STEP TITLE>
|
||||
**PR:** (populate with PR identifier) — Base:<baseRefName> Head:<headRefName>
|
||||
**Review iteration:** ITERATION
|
||||
|
||||
## Iteration history
|
||||
- Maintain subsections titled `### Iteration N` in reverse chronological order (append the latest at the top) with 2–4 bullet highlights.
|
||||
|
||||
### Iteration ITERATION
|
||||
- <Latest key point 1>
|
||||
- <Latest key point 2>
|
||||
|
||||
## Checks executed
|
||||
- List the concrete checks for *this step only* (5–10 bullets).
|
||||
|
||||
## Findings
|
||||
(If none, write **None**. Defaults have one or more blocks:)
|
||||
|
||||
```mcp-review-comment
|
||||
{"file":"relative/path.ext","start_line":123,"end_line":125,"severity":"high|medium|low|info","tags":["<step-slug>","pr-tag-here"],"related_files":["optional/other/file1"],"body":"Problem → Why it matters → Concrete fix. If spans multiple files, name them here."}
|
||||
```
|
||||
Use the second tag to encode the PR number.
|
||||
|
||||
```
|
||||
## Overview file (`00-OVERVIEW.md`) template
|
||||
```md
|
||||
# PR Review Overview — (populate with PR identifier)
|
||||
**Review iteration:** ITERATION
|
||||
**Changed files:** <n> | **High severity issues:** <count>
|
||||
|
||||
## Review metadata
|
||||
**Last reviewed SHA:** <headRefOid from gh pr view>
|
||||
**Last review timestamp:** <ISO8601 timestamp>
|
||||
**Review mode:** <Full|Incremental (N files changed since iteration X)>
|
||||
**Base ref:** <baseRefName>
|
||||
**Head ref:** <headRefName>
|
||||
|
||||
## Step results
|
||||
Write lines like: `01 Functionality — <OK|Issues|Skipped> (see 01-functionality.md)` … through step 13.
|
||||
Mark steps as "Skipped" when using incremental review smart filtering.
|
||||
|
||||
## Iteration history
|
||||
- Maintain subsections titled `### Iteration N` mirroring the per-step convention with concise deltas and cross-links to the relevant step files.
|
||||
- For incremental reviews, list the specific files that changed and which commits were added.
|
||||
```
|
||||
|
||||
## Line numbers & multi‑file issues
|
||||
- Map head‑side lines from `patch` hunks (`@@ -a,b +c,d @@` → new lines `+c..+c+d-1`).
|
||||
- For cross‑file issues: set the primary `"file"`, list others in `"related_files"`, and name them in `"body"`.
|
||||
|
||||
## Posting (for MCP)
|
||||
- Parse all ```mcp-review-comment``` blocks across step files and post as PR review comments.
|
||||
- If posting isn’t available, still write all files.
|
||||
|
||||
## Constraint
|
||||
Read/analyze only; don't modify code. Keep comments small, specific, and fix‑oriented.
|
||||
|
||||
**Testing**: Use `.github/review-tools/Test-IncrementalReview.ps1 -PullRequestNumber 42374` to preview incremental detection before running full review.
|
||||
|
||||
## Scratch cache for large PRs
|
||||
|
||||
Create a local scratch workspace to progressively summarize diffs and reload state across runs.
|
||||
|
||||
### Paths
|
||||
- Root: `Generated Files/prReview/{{pr_number}}/__tmp/`
|
||||
- Files:
|
||||
- `index.jsonl` — append-only JSON Lines index of artifacts.
|
||||
- `todo-queue.json` — pending items (files/chunks/steps).
|
||||
- `rollup-<step>-v<N>.md` — iterative per-step aggregates.
|
||||
- `file-<hash>.txt` — optional saved chunk text (when needed).
|
||||
|
||||
### JSON schema (per line in `index.jsonl`)
|
||||
```json
|
||||
{"type":"chunk|summary|issue|crosslink",
|
||||
"path":"relative/file.ext","chunk_id":"f-12","step":"functionality|compatibility|...",
|
||||
"base_sha":"...", "head_sha":"...", "range":[start,end], "version":1,
|
||||
"notes":"short text or key:value map", "created_utc":"ISO8601"}
|
||||
```
|
||||
|
||||
### Phases (stateful; resume-safe)
|
||||
0. **Discover** PR + SHAs: `gh pr view <PR> --json baseRefName,headRefName,baseRefOid,headRefOid,files`.
|
||||
1. **Chunk** each changed file (head): split into ~300–600 LOC or ~4k chars; stable `chunk_id` = hash(path+start).
|
||||
- Save `chunk` records. Optionally write `file-<hash>.txt` for expensive chunks.
|
||||
2. **Summarize** per chunk: intent, APIs, risks per TODO step; emit `summary` records (≤600 tokens each).
|
||||
3. **Issues**: convert findings to machine-readable blocks and emit `issue` records (later rendered to step MD).
|
||||
4. **Rollups**: build/update `rollup-<step>-v<N>.md` from `summary`+`issue`. Keep prior versions.
|
||||
5. **Finalize**: write per-step files + `00-OVERVIEW.md` from rollups. Post comments via MCP if available.
|
||||
|
||||
### Re-use & token limits
|
||||
- Always **reload** `index.jsonl` first; skip chunks with same `head_sha` and `range`.
|
||||
- **Incremental review optimization**: When `Get-PrIncrementalChanges.ps1` returns a subset of changed files, load only chunks from those files. Reuse existing chunks/summaries for unchanged files.
|
||||
- Prefer re-summarizing only changed chunks; merge chunk summaries → file summaries → step rollups.
|
||||
- When context is tight, load only the minimal chunk text (or its saved `file-<hash>.txt`) needed for a comment.
|
||||
|
||||
### Original vs diff
|
||||
- Fetch base content when needed: prefer `git show <baseRefName>:<path>`; fallback `gh api repos/:owner/:repo/contents/<path>?ref=<base_sha>` (base64).
|
||||
- Use patch hunks from `gh api .../pulls/<PR>/files` to compute **head** line numbers.
|
||||
|
||||
### Queue-driven loop
|
||||
- Seed `todo-queue.json` with all changed files.
|
||||
- Process: chunk → summarize → detect issues → roll up.
|
||||
- Append to `index.jsonl` after each step; never rewrite previous lines (append-only).
|
||||
|
||||
### Hygiene
|
||||
- `__tmp/` is implementation detail; do not include in final artifacts.
|
||||
- It is safe to delete to force a clean pass; the next run rebuilds it.
|
||||
79
.github/skills/pr-review/scripts/Get-GitHubPrFilePatch.ps1
vendored
Normal file
79
.github/skills/pr-review/scripts/Get-GitHubPrFilePatch.ps1
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Retrieves the unified diff patch for a specific file in a GitHub pull request.
|
||||
|
||||
.DESCRIPTION
|
||||
This script fetches the patch content (unified diff format) for a specified file
|
||||
within a pull request. It uses the GitHub CLI (gh) to query the GitHub API and
|
||||
retrieve file change information.
|
||||
|
||||
.PARAMETER PullRequestNumber
|
||||
The pull request number to query.
|
||||
|
||||
.PARAMETER FilePath
|
||||
The relative path to the file in the repository (e.g., "src/modules/main.cpp").
|
||||
|
||||
.PARAMETER RepositoryOwner
|
||||
The GitHub repository owner. Defaults to "microsoft".
|
||||
|
||||
.PARAMETER RepositoryName
|
||||
The GitHub repository name. Defaults to "PowerToys".
|
||||
|
||||
.EXAMPLE
|
||||
.\Get-GitHubPrFilePatch.ps1 -PullRequestNumber 42374 -FilePath "src/modules/cmdpal/main.cpp"
|
||||
Retrieves the patch for main.cpp in PR #42374.
|
||||
|
||||
.EXAMPLE
|
||||
.\Get-GitHubPrFilePatch.ps1 -PullRequestNumber 42374 -FilePath "README.md" -RepositoryOwner "myorg" -RepositoryName "myrepo"
|
||||
Retrieves the patch from a different repository.
|
||||
|
||||
.NOTES
|
||||
Requires GitHub CLI (gh) to be installed and authenticated.
|
||||
Run 'gh auth login' if not already authenticated.
|
||||
|
||||
.LINK
|
||||
https://cli.github.com/
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true, HelpMessage = "Pull request number")]
|
||||
[int]$PullRequestNumber,
|
||||
|
||||
[Parameter(Mandatory = $true, HelpMessage = "Relative path to the file in the repository")]
|
||||
[string]$FilePath,
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Repository owner")]
|
||||
[string]$RepositoryOwner = "microsoft",
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Repository name")]
|
||||
[string]$RepositoryName = "PowerToys"
|
||||
)
|
||||
|
||||
# Construct GitHub API path for pull request files
|
||||
$apiPath = "repos/$RepositoryOwner/$RepositoryName/pulls/$PullRequestNumber/files?per_page=250"
|
||||
|
||||
# Query GitHub API to get all files in the pull request
|
||||
try {
|
||||
$pullRequestFiles = gh api $apiPath | ConvertFrom-Json
|
||||
} catch {
|
||||
Write-Error "Failed to query GitHub API for PR #$PullRequestNumber. Ensure gh CLI is authenticated. Details: $_"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Find the matching file in the pull request
|
||||
$matchedFile = $pullRequestFiles | Where-Object { $_.filename -eq $FilePath }
|
||||
|
||||
if (-not $matchedFile) {
|
||||
Write-Error "File '$FilePath' not found in PR #$PullRequestNumber."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Check if patch content exists
|
||||
if (-not $matchedFile.patch) {
|
||||
Write-Warning "File '$FilePath' has no patch content (possibly binary or too large)."
|
||||
return
|
||||
}
|
||||
|
||||
# Output the patch content
|
||||
$matchedFile.patch
|
||||
91
.github/skills/pr-review/scripts/Get-GitHubRawFile.ps1
vendored
Normal file
91
.github/skills/pr-review/scripts/Get-GitHubRawFile.ps1
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Downloads and displays the content of a file from a GitHub repository at a specific git reference.
|
||||
|
||||
.DESCRIPTION
|
||||
This script fetches the raw content of a file from a GitHub repository using GitHub's raw content API.
|
||||
It can optionally display line numbers and supports any valid git reference (branch, tag, or commit SHA).
|
||||
|
||||
.PARAMETER FilePath
|
||||
The relative path to the file in the repository (e.g., "src/modules/main.cpp").
|
||||
|
||||
.PARAMETER GitReference
|
||||
The git reference (branch name, tag, or commit SHA) to fetch the file from. Defaults to "main".
|
||||
|
||||
.PARAMETER RepositoryOwner
|
||||
The GitHub repository owner. Defaults to "microsoft".
|
||||
|
||||
.PARAMETER RepositoryName
|
||||
The GitHub repository name. Defaults to "PowerToys".
|
||||
|
||||
.PARAMETER ShowLineNumbers
|
||||
When specified, displays line numbers before each line of content.
|
||||
|
||||
.PARAMETER StartLineNumber
|
||||
The starting line number to use when ShowLineNumbers is enabled. Defaults to 1.
|
||||
|
||||
.EXAMPLE
|
||||
.\Get-GitHubRawFile.ps1 -FilePath "README.md" -GitReference "main"
|
||||
Downloads and displays the README.md file from the main branch.
|
||||
|
||||
.EXAMPLE
|
||||
.\Get-GitHubRawFile.ps1 -FilePath "src/runner/main.cpp" -GitReference "dev/feature-branch" -ShowLineNumbers
|
||||
Downloads main.cpp from a feature branch and displays it with line numbers.
|
||||
|
||||
.EXAMPLE
|
||||
.\Get-GitHubRawFile.ps1 -FilePath "LICENSE" -GitReference "abc123def" -ShowLineNumbers -StartLineNumber 10
|
||||
Downloads the LICENSE file from a specific commit and displays it with line numbers starting at 10.
|
||||
|
||||
.NOTES
|
||||
Requires internet connectivity to access GitHub's raw content API.
|
||||
Does not require GitHub CLI authentication for public repositories.
|
||||
|
||||
.LINK
|
||||
https://docs.github.com/en/rest/repos/contents
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true, HelpMessage = "Relative path to the file in the repository")]
|
||||
[string]$FilePath,
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Git reference (branch, tag, or commit SHA)")]
|
||||
[string]$GitReference = "main",
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Repository owner")]
|
||||
[string]$RepositoryOwner = "microsoft",
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Repository name")]
|
||||
[string]$RepositoryName = "PowerToys",
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Display line numbers before each line")]
|
||||
[switch]$ShowLineNumbers,
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Starting line number for display")]
|
||||
[int]$StartLineNumber = 1
|
||||
)
|
||||
|
||||
# Construct the raw content URL
|
||||
$rawContentUrl = "https://raw.githubusercontent.com/$RepositoryOwner/$RepositoryName/$GitReference/$FilePath"
|
||||
|
||||
# Fetch the file content from GitHub
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -Uri $rawContentUrl
|
||||
} catch {
|
||||
Write-Error "Failed to fetch file from $rawContentUrl. Details: $_"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Split content into individual lines
|
||||
$contentLines = $response.Content -split "`n"
|
||||
|
||||
# Display the content with or without line numbers
|
||||
if ($ShowLineNumbers) {
|
||||
$currentLineNumber = $StartLineNumber
|
||||
foreach ($line in $contentLines) {
|
||||
Write-Output ("{0:d4}: {1}" -f $currentLineNumber, $line)
|
||||
$currentLineNumber++
|
||||
}
|
||||
} else {
|
||||
$contentLines | ForEach-Object { Write-Output $_ }
|
||||
}
|
||||
173
.github/skills/pr-review/scripts/Get-PrIncrementalChanges.ps1
vendored
Normal file
173
.github/skills/pr-review/scripts/Get-PrIncrementalChanges.ps1
vendored
Normal file
@@ -0,0 +1,173 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Detects changes between the last reviewed commit and current head of a pull request.
|
||||
|
||||
.DESCRIPTION
|
||||
This script compares a previously reviewed commit SHA with the current head of a pull request
|
||||
to determine what has changed. It helps enable incremental reviews by identifying new commits
|
||||
and modified files since the last review iteration.
|
||||
|
||||
The script handles several scenarios:
|
||||
- First review (no previous SHA provided)
|
||||
- No changes (current SHA matches last reviewed SHA)
|
||||
- Force-push detected (last reviewed SHA no longer in history)
|
||||
- Incremental changes (new commits added since last review)
|
||||
|
||||
.PARAMETER PullRequestNumber
|
||||
The pull request number to analyze.
|
||||
|
||||
.PARAMETER LastReviewedCommitSha
|
||||
The commit SHA that was last reviewed. If omitted, this is treated as a first review.
|
||||
|
||||
.PARAMETER RepositoryOwner
|
||||
The GitHub repository owner. Defaults to "microsoft".
|
||||
|
||||
.PARAMETER RepositoryName
|
||||
The GitHub repository name. Defaults to "PowerToys".
|
||||
|
||||
.OUTPUTS
|
||||
JSON object containing:
|
||||
- PullRequestNumber: The PR number being analyzed
|
||||
- CurrentHeadSha: The current head commit SHA
|
||||
- LastReviewedSha: The last reviewed commit SHA (if provided)
|
||||
- BaseRefName: Base branch name
|
||||
- HeadRefName: Head branch name
|
||||
- IsIncremental: Boolean indicating if incremental review is possible
|
||||
- NeedFullReview: Boolean indicating if a full review is required
|
||||
- ChangedFiles: Array of files that changed (filename, status, additions, deletions)
|
||||
- NewCommits: Array of commits added since last review (sha, message, author, date)
|
||||
- Summary: Human-readable description of changes
|
||||
|
||||
.EXAMPLE
|
||||
.\Get-PrIncrementalChanges.ps1 -PullRequestNumber 42374
|
||||
Analyzes PR #42374 with no previous review (first review scenario).
|
||||
|
||||
.EXAMPLE
|
||||
.\Get-PrIncrementalChanges.ps1 -PullRequestNumber 42374 -LastReviewedCommitSha "abc123def456"
|
||||
Compares current PR state against the last reviewed commit to identify incremental changes.
|
||||
|
||||
.EXAMPLE
|
||||
$changes = .\Get-PrIncrementalChanges.ps1 -PullRequestNumber 42374 -LastReviewedCommitSha "abc123" | ConvertFrom-Json
|
||||
if ($changes.IsIncremental) { Write-Host "Can perform incremental review" }
|
||||
Captures the output as a PowerShell object for further processing.
|
||||
|
||||
.NOTES
|
||||
Requires GitHub CLI (gh) to be installed and authenticated.
|
||||
Run 'gh auth login' if not already authenticated.
|
||||
|
||||
.LINK
|
||||
https://cli.github.com/
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true, HelpMessage = "Pull request number")]
|
||||
[int]$PullRequestNumber,
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Commit SHA that was last reviewed")]
|
||||
[string]$LastReviewedCommitSha,
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Repository owner")]
|
||||
[string]$RepositoryOwner = "microsoft",
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Repository name")]
|
||||
[string]$RepositoryName = "PowerToys"
|
||||
)
|
||||
|
||||
# Fetch current pull request state from GitHub
|
||||
try {
|
||||
$pullRequestData = gh pr view $PullRequestNumber --json headRefOid,headRefName,baseRefName,baseRefOid | ConvertFrom-Json
|
||||
} catch {
|
||||
Write-Error "Failed to fetch PR #$PullRequestNumber details. Details: $_"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$currentHeadSha = $pullRequestData.headRefOid
|
||||
$baseRefName = $pullRequestData.baseRefName
|
||||
$headRefName = $pullRequestData.headRefName
|
||||
|
||||
# Initialize result object
|
||||
$analysisResult = @{
|
||||
PullRequestNumber = $PullRequestNumber
|
||||
CurrentHeadSha = $currentHeadSha
|
||||
BaseRefName = $baseRefName
|
||||
HeadRefName = $headRefName
|
||||
LastReviewedSha = $LastReviewedCommitSha
|
||||
IsIncremental = $false
|
||||
NeedFullReview = $true
|
||||
ChangedFiles = @()
|
||||
NewCommits = @()
|
||||
Summary = ""
|
||||
}
|
||||
|
||||
# Scenario 1: First review (no previous SHA provided)
|
||||
if ([string]::IsNullOrWhiteSpace($LastReviewedCommitSha)) {
|
||||
$analysisResult.Summary = "Initial review - no previous iteration found"
|
||||
$analysisResult.NeedFullReview = $true
|
||||
return $analysisResult | ConvertTo-Json -Depth 10
|
||||
}
|
||||
|
||||
# Scenario 2: No changes since last review
|
||||
if ($currentHeadSha -eq $LastReviewedCommitSha) {
|
||||
$analysisResult.Summary = "No changes since last review (SHA: $currentHeadSha)"
|
||||
$analysisResult.NeedFullReview = $false
|
||||
$analysisResult.IsIncremental = $true
|
||||
return $analysisResult | ConvertTo-Json -Depth 10
|
||||
}
|
||||
|
||||
# Scenario 3: Check for force-push (last reviewed SHA no longer exists in history)
|
||||
try {
|
||||
$null = gh api "repos/$RepositoryOwner/$RepositoryName/commits/$LastReviewedCommitSha" 2>&1
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
# SHA not found - likely force-push or branch rewrite
|
||||
$analysisResult.Summary = "Force-push detected - last reviewed SHA $LastReviewedCommitSha no longer exists. Full review required."
|
||||
$analysisResult.NeedFullReview = $true
|
||||
return $analysisResult | ConvertTo-Json -Depth 10
|
||||
}
|
||||
} catch {
|
||||
$analysisResult.Summary = "Cannot verify last reviewed SHA $LastReviewedCommitSha - assuming force-push. Full review required."
|
||||
$analysisResult.NeedFullReview = $true
|
||||
return $analysisResult | ConvertTo-Json -Depth 10
|
||||
}
|
||||
|
||||
# Scenario 4: Get incremental changes between last reviewed SHA and current head
|
||||
try {
|
||||
$compareApiPath = "repos/$RepositoryOwner/$RepositoryName/compare/$LastReviewedCommitSha...$currentHeadSha"
|
||||
$comparisonData = gh api $compareApiPath | ConvertFrom-Json
|
||||
|
||||
# Extract new commits information
|
||||
$analysisResult.NewCommits = $comparisonData.commits | ForEach-Object {
|
||||
@{
|
||||
Sha = $_.sha.Substring(0, 7)
|
||||
Message = $_.commit.message.Split("`n")[0] # First line only
|
||||
Author = $_.commit.author.name
|
||||
Date = $_.commit.author.date
|
||||
}
|
||||
}
|
||||
|
||||
# Extract changed files information
|
||||
$analysisResult.ChangedFiles = $comparisonData.files | ForEach-Object {
|
||||
@{
|
||||
Filename = $_.filename
|
||||
Status = $_.status # added, modified, removed, renamed
|
||||
Additions = $_.additions
|
||||
Deletions = $_.deletions
|
||||
Changes = $_.changes
|
||||
}
|
||||
}
|
||||
|
||||
$fileCount = $analysisResult.ChangedFiles.Count
|
||||
$commitCount = $analysisResult.NewCommits.Count
|
||||
|
||||
$analysisResult.IsIncremental = $true
|
||||
$analysisResult.NeedFullReview = $false
|
||||
$analysisResult.Summary = "Incremental review: $commitCount new commit(s), $fileCount file(s) changed since SHA $($LastReviewedCommitSha.Substring(0, 7))"
|
||||
|
||||
} catch {
|
||||
Write-Error "Failed to compare commits. Details: $_"
|
||||
$analysisResult.Summary = "Error comparing commits - defaulting to full review"
|
||||
$analysisResult.NeedFullReview = $true
|
||||
}
|
||||
|
||||
# Return the analysis result as JSON
|
||||
return $analysisResult | ConvertTo-Json -Depth 10
|
||||
18
.github/skills/pr-review/scripts/IssueReviewLib.ps1
vendored
Normal file
18
.github/skills/pr-review/scripts/IssueReviewLib.ps1
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
# IssueReviewLib.ps1 - Minimal helpers for PR review workflow
|
||||
# Part of the PowerToys GitHub Copilot/Claude Code issue review system
|
||||
# This is a trimmed version - pr-review only needs console helpers and repo root
|
||||
|
||||
#region Console Output Helpers
|
||||
function Info { param([string]$Message) Write-Host $Message -ForegroundColor Cyan }
|
||||
function Warn { param([string]$Message) Write-Host $Message -ForegroundColor Yellow }
|
||||
function Err { param([string]$Message) Write-Host $Message -ForegroundColor Red }
|
||||
function Success { param([string]$Message) Write-Host $Message -ForegroundColor Green }
|
||||
#endregion
|
||||
|
||||
#region Repository Helpers
|
||||
function Get-RepoRoot {
|
||||
$root = git rev-parse --show-toplevel 2>$null
|
||||
if (-not $root) { throw 'Not inside a git repository.' }
|
||||
return (Resolve-Path $root).Path
|
||||
}
|
||||
#endregion
|
||||
541
.github/skills/pr-review/scripts/Start-PRReviewWorkflow.ps1
vendored
Normal file
541
.github/skills/pr-review/scripts/Start-PRReviewWorkflow.ps1
vendored
Normal file
@@ -0,0 +1,541 @@
|
||||
<#!
|
||||
.SYNOPSIS
|
||||
Review and fix PRs in parallel using GitHub Copilot and MCP.
|
||||
|
||||
.DESCRIPTION
|
||||
For each PR (from worktrees or specified), runs in parallel:
|
||||
1. Assigns GitHub Copilot as reviewer via GitHub MCP
|
||||
2. Runs review-pr.prompt.md to generate review and post comments
|
||||
3. Runs fix-pr-active-comments.prompt.md to fix issues
|
||||
|
||||
.PARAMETER PRNumbers
|
||||
Array of PR numbers to process. If not specified, finds PRs from issue worktrees.
|
||||
|
||||
.PARAMETER SkipAssign
|
||||
Skip assigning Copilot as reviewer.
|
||||
|
||||
.PARAMETER SkipReview
|
||||
Skip the review step.
|
||||
|
||||
.PARAMETER SkipFix
|
||||
Skip the fix step.
|
||||
|
||||
.PARAMETER MinSeverity
|
||||
Minimum severity to post as PR comments: high, medium, low, info. Default: medium.
|
||||
|
||||
.PARAMETER MaxParallel
|
||||
Maximum parallel jobs. Default: 3.
|
||||
|
||||
.PARAMETER DryRun
|
||||
Show what would be done without executing.
|
||||
|
||||
.PARAMETER CLIType
|
||||
AI CLI to use: copilot or claude. Default: copilot.
|
||||
|
||||
.EXAMPLE
|
||||
# Process all PRs from issue worktrees
|
||||
./Start-PRReviewWorkflow.ps1
|
||||
|
||||
.EXAMPLE
|
||||
# Process specific PRs
|
||||
./Start-PRReviewWorkflow.ps1 -PRNumbers 45234, 45235
|
||||
|
||||
.EXAMPLE
|
||||
# Only review, don't fix
|
||||
./Start-PRReviewWorkflow.ps1 -SkipFix
|
||||
|
||||
.EXAMPLE
|
||||
# Dry run
|
||||
./Start-PRReviewWorkflow.ps1 -DryRun
|
||||
|
||||
.NOTES
|
||||
Prerequisites:
|
||||
- GitHub CLI (gh) authenticated
|
||||
- Copilot CLI installed
|
||||
- GitHub MCP configured for posting comments
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[int[]]$PRNumbers,
|
||||
|
||||
[switch]$SkipAssign,
|
||||
|
||||
[switch]$SkipReview,
|
||||
|
||||
[switch]$SkipFix,
|
||||
|
||||
[ValidateSet('high', 'medium', 'low', 'info')]
|
||||
[string]$MinSeverity = 'medium',
|
||||
|
||||
[int]$MaxParallel = 3,
|
||||
|
||||
[switch]$DryRun,
|
||||
|
||||
[ValidateSet('copilot', 'claude')]
|
||||
[string]$CLIType = 'copilot',
|
||||
|
||||
[switch]$Force,
|
||||
|
||||
[switch]$Help
|
||||
)
|
||||
|
||||
# Load libraries
|
||||
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
. "$scriptDir/IssueReviewLib.ps1"
|
||||
|
||||
# Load worktree library
|
||||
$repoRoot = Get-RepoRoot
|
||||
$worktreeLib = Join-Path $repoRoot 'tools/build/WorktreeLib.ps1'
|
||||
if (Test-Path $worktreeLib) {
|
||||
. $worktreeLib
|
||||
}
|
||||
|
||||
if ($Help) {
|
||||
Get-Help $MyInvocation.MyCommand.Path -Full
|
||||
return
|
||||
}
|
||||
|
||||
function Get-PRsFromWorktrees {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Get PR numbers from issue worktrees by checking for open PRs on each branch.
|
||||
#>
|
||||
$worktrees = Get-WorktreeEntries | Where-Object { $_.Branch -like 'issue/*' }
|
||||
$prs = @()
|
||||
|
||||
foreach ($wt in $worktrees) {
|
||||
$prInfo = gh pr list --head $wt.Branch --json number,url --state open 2>$null | ConvertFrom-Json
|
||||
if ($prInfo -and $prInfo.Count -gt 0) {
|
||||
$prs += @{
|
||||
PRNumber = $prInfo[0].number
|
||||
PRUrl = $prInfo[0].url
|
||||
Branch = $wt.Branch
|
||||
WorktreePath = $wt.Path
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $prs
|
||||
}
|
||||
|
||||
function Invoke-AssignCopilotReviewer {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Assign GitHub Copilot as a reviewer to the PR using GitHub MCP.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$PRNumber,
|
||||
[string]$CLIType = 'copilot',
|
||||
[switch]$DryRun
|
||||
)
|
||||
|
||||
if ($DryRun) {
|
||||
Info " [DRY RUN] Would request Copilot review for PR #$PRNumber"
|
||||
return $true
|
||||
}
|
||||
|
||||
# Use a prompt that instructs Copilot to use GitHub MCP to assign Copilot as reviewer
|
||||
$prompt = @"
|
||||
Use the GitHub MCP to request a review from GitHub Copilot for PR #$PRNumber.
|
||||
|
||||
Steps:
|
||||
1. Use the GitHub MCP tool to add "Copilot" as a reviewer to pull request #$PRNumber in the microsoft/PowerToys repository
|
||||
2. This should add Copilot to the "Reviewers" section of the PR
|
||||
|
||||
If GitHub MCP is not available, report that and skip this step.
|
||||
"@
|
||||
|
||||
# MCP config for github-artifacts tools (relative to repo root)
|
||||
$mcpConfig = '@.github/skills/pr-review/references/mcp-config.json'
|
||||
|
||||
try {
|
||||
Info " Requesting Copilot review via GitHub MCP..."
|
||||
|
||||
switch ($CLIType) {
|
||||
'copilot' {
|
||||
& copilot --additional-mcp-config $mcpConfig -p $prompt --yolo -s 2>&1 | Out-Null
|
||||
}
|
||||
'claude' {
|
||||
& claude --print --dangerously-skip-permissions --prompt $prompt 2>&1 | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
return $true
|
||||
}
|
||||
catch {
|
||||
Warn " Could not assign Copilot reviewer: $($_.Exception.Message)"
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-PRReview {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Run review-pr.prompt.md using Copilot CLI.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$PRNumber,
|
||||
[string]$CLIType = 'copilot',
|
||||
[string]$MinSeverity = 'medium',
|
||||
[switch]$DryRun
|
||||
)
|
||||
|
||||
# Simple prompt - let the prompt file define all the details
|
||||
$prompt = @"
|
||||
Follow exactly what at .github/prompts/review-pr.prompt.md to do with PR #$PRNumber.
|
||||
Post findings with severity >= $MinSeverity as PR review comments via GitHub MCP.
|
||||
"@
|
||||
|
||||
if ($DryRun) {
|
||||
Info " [DRY RUN] Would run PR review for #$PRNumber"
|
||||
return @{ Success = $true; ReviewPath = "Generated Files/prReview/$PRNumber" }
|
||||
}
|
||||
|
||||
$reviewPath = Join-Path $repoRoot "Generated Files/prReview/$PRNumber"
|
||||
|
||||
# Ensure the review directory exists
|
||||
if (-not (Test-Path $reviewPath)) {
|
||||
New-Item -ItemType Directory -Path $reviewPath -Force | Out-Null
|
||||
}
|
||||
|
||||
# MCP config for github-artifacts tools (relative to repo root)
|
||||
$mcpConfig = '@.github/skills/pr-review/references/mcp-config.json'
|
||||
|
||||
Push-Location $repoRoot
|
||||
try {
|
||||
switch ($CLIType) {
|
||||
'copilot' {
|
||||
Info " Running Copilot review (this may take several minutes)..."
|
||||
$output = & copilot --additional-mcp-config $mcpConfig -p $prompt --yolo 2>&1
|
||||
# Log output for debugging
|
||||
$logFile = Join-Path $reviewPath "_copilot-review.log"
|
||||
$output | Out-File -FilePath $logFile -Force
|
||||
}
|
||||
'claude' {
|
||||
Info " Running Claude review (this may take several minutes)..."
|
||||
$output = & claude --print --dangerously-skip-permissions --prompt $prompt 2>&1
|
||||
$logFile = Join-Path $reviewPath "_claude-review.log"
|
||||
$output | Out-File -FilePath $logFile -Force
|
||||
}
|
||||
}
|
||||
|
||||
# Check if review files were created (at minimum, check for multiple step files)
|
||||
$overviewPath = Join-Path $reviewPath '00-OVERVIEW.md'
|
||||
$stepFiles = Get-ChildItem -Path $reviewPath -Filter "*.md" -ErrorAction SilentlyContinue
|
||||
$stepCount = ($stepFiles | Where-Object { $_.Name -match '^\d{2}-' }).Count
|
||||
|
||||
if ($stepCount -ge 5) {
|
||||
return @{ Success = $true; ReviewPath = $reviewPath; StepFilesCreated = $stepCount }
|
||||
} elseif (Test-Path $overviewPath) {
|
||||
Warn " Only overview created, step files may be incomplete ($stepCount step files)"
|
||||
return @{ Success = $true; ReviewPath = $reviewPath; StepFilesCreated = $stepCount; Partial = $true }
|
||||
} else {
|
||||
return @{ Success = $false; Error = "Review files not created (found $stepCount step files)" }
|
||||
}
|
||||
}
|
||||
catch {
|
||||
return @{ Success = $false; Error = $_.Exception.Message }
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-FixPRComments {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Run fix-pr-active-comments.prompt.md to fix issues.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$PRNumber,
|
||||
[string]$WorktreePath,
|
||||
[string]$CLIType = 'copilot',
|
||||
[switch]$DryRun
|
||||
)
|
||||
|
||||
# Simple prompt - let the prompt file define all the details
|
||||
$prompt = "Follow .github/prompts/fix-pr-active-comments.prompt.md for PR #$PRNumber."
|
||||
|
||||
if ($DryRun) {
|
||||
Info " [DRY RUN] Would fix PR comments for #$PRNumber"
|
||||
return @{ Success = $true }
|
||||
}
|
||||
|
||||
$workDir = if ($WorktreePath -and (Test-Path $WorktreePath)) { $WorktreePath } else { $repoRoot }
|
||||
|
||||
# MCP config for github-artifacts tools (relative to repo root)
|
||||
$mcpConfig = '@.github/skills/pr-review/references/mcp-config.json'
|
||||
|
||||
Push-Location $workDir
|
||||
try {
|
||||
switch ($CLIType) {
|
||||
'copilot' {
|
||||
Info " Running Copilot to fix comments..."
|
||||
$output = & copilot --additional-mcp-config $mcpConfig -p $prompt --yolo 2>&1
|
||||
# Log output for debugging
|
||||
$logPath = Join-Path $repoRoot "Generated Files/prReview/$PRNumber"
|
||||
if (-not (Test-Path $logPath)) {
|
||||
New-Item -ItemType Directory -Path $logPath -Force | Out-Null
|
||||
}
|
||||
$logFile = Join-Path $logPath "_copilot-fix.log"
|
||||
$output | Out-File -FilePath $logFile -Force
|
||||
}
|
||||
'claude' {
|
||||
Info " Running Claude to fix comments..."
|
||||
$output = & claude --print --dangerously-skip-permissions --prompt $prompt 2>&1
|
||||
$logPath = Join-Path $repoRoot "Generated Files/prReview/$PRNumber"
|
||||
if (-not (Test-Path $logPath)) {
|
||||
New-Item -ItemType Directory -Path $logPath -Force | Out-Null
|
||||
}
|
||||
$logFile = Join-Path $logPath "_claude-fix.log"
|
||||
$output | Out-File -FilePath $logFile -Force
|
||||
}
|
||||
}
|
||||
|
||||
return @{ Success = $true }
|
||||
}
|
||||
catch {
|
||||
return @{ Success = $false; Error = $_.Exception.Message }
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
function Start-PRWorkflowJob {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Process a single PR through the workflow.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$PRNumber,
|
||||
[string]$WorktreePath,
|
||||
[string]$CLIType = 'copilot',
|
||||
[string]$MinSeverity = 'medium',
|
||||
[switch]$SkipAssign,
|
||||
[switch]$SkipReview,
|
||||
[switch]$SkipFix,
|
||||
[switch]$DryRun
|
||||
)
|
||||
|
||||
$result = @{
|
||||
PRNumber = $PRNumber
|
||||
AssignResult = $null
|
||||
ReviewResult = $null
|
||||
FixResult = $null
|
||||
Success = $true
|
||||
}
|
||||
|
||||
# Step 1: Assign Copilot as reviewer
|
||||
if (-not $SkipAssign) {
|
||||
Info " Step 1: Assigning Copilot reviewer..."
|
||||
$result.AssignResult = Invoke-AssignCopilotReviewer -PRNumber $PRNumber -CLIType $CLIType -DryRun:$DryRun
|
||||
if (-not $result.AssignResult) {
|
||||
Warn " Assignment step had issues (continuing...)"
|
||||
}
|
||||
} else {
|
||||
Info " Step 1: Skipped (assign)"
|
||||
}
|
||||
|
||||
# Step 2: Run PR review
|
||||
if (-not $SkipReview) {
|
||||
Info " Step 2: Running PR review..."
|
||||
$result.ReviewResult = Invoke-PRReview -PRNumber $PRNumber -CLIType $CLIType -MinSeverity $MinSeverity -DryRun:$DryRun
|
||||
if (-not $result.ReviewResult.Success) {
|
||||
Warn " Review step failed: $($result.ReviewResult.Error)"
|
||||
$result.Success = $false
|
||||
} else {
|
||||
$stepInfo = if ($result.ReviewResult.StepFilesCreated) { " ($($result.ReviewResult.StepFilesCreated) step files)" } else { "" }
|
||||
$partialInfo = if ($result.ReviewResult.Partial) { " [PARTIAL]" } else { "" }
|
||||
Success " Review completed: $($result.ReviewResult.ReviewPath)$stepInfo$partialInfo"
|
||||
}
|
||||
} else {
|
||||
Info " Step 2: Skipped (review)"
|
||||
}
|
||||
|
||||
# Step 3: Fix PR comments
|
||||
if (-not $SkipFix) {
|
||||
Info " Step 3: Fixing PR comments..."
|
||||
$result.FixResult = Invoke-FixPRComments -PRNumber $PRNumber -WorktreePath $WorktreePath -CLIType $CLIType -DryRun:$DryRun
|
||||
if (-not $result.FixResult.Success) {
|
||||
Warn " Fix step failed: $($result.FixResult.Error)"
|
||||
$result.Success = $false
|
||||
} else {
|
||||
Success " Fix step completed"
|
||||
}
|
||||
} else {
|
||||
Info " Step 3: Skipped (fix)"
|
||||
}
|
||||
|
||||
return $result
|
||||
}
|
||||
|
||||
#region Main Script
|
||||
try {
|
||||
Info "Repository root: $repoRoot"
|
||||
Info "CLI type: $CLIType"
|
||||
Info "Min severity for comments: $MinSeverity"
|
||||
Info "Max parallel: $MaxParallel"
|
||||
|
||||
# Determine PRs to process
|
||||
$prsToProcess = @()
|
||||
|
||||
if ($PRNumbers -and $PRNumbers.Count -gt 0) {
|
||||
# Use specified PR numbers
|
||||
foreach ($prNum in $PRNumbers) {
|
||||
$prInfo = gh pr view $prNum --json number,url,headRefName 2>$null | ConvertFrom-Json
|
||||
if ($prInfo) {
|
||||
# Try to find matching worktree
|
||||
$wt = Get-WorktreeEntries | Where-Object { $_.Branch -eq $prInfo.headRefName } | Select-Object -First 1
|
||||
$prsToProcess += @{
|
||||
PRNumber = $prInfo.number
|
||||
PRUrl = $prInfo.url
|
||||
Branch = $prInfo.headRefName
|
||||
WorktreePath = if ($wt) { $wt.Path } else { $repoRoot }
|
||||
}
|
||||
} else {
|
||||
Warn "PR #$prNum not found"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
# Get PRs from worktrees
|
||||
Info "`nFinding PRs from issue worktrees..."
|
||||
$prsToProcess = Get-PRsFromWorktrees
|
||||
}
|
||||
|
||||
if ($prsToProcess.Count -eq 0) {
|
||||
Warn "No PRs found to process."
|
||||
return
|
||||
}
|
||||
|
||||
# Display PRs
|
||||
Info "`nPRs to process:"
|
||||
Info ("-" * 80)
|
||||
foreach ($pr in $prsToProcess) {
|
||||
Info (" #{0,-6} {1}" -f $pr.PRNumber, $pr.PRUrl)
|
||||
}
|
||||
Info ("-" * 80)
|
||||
|
||||
if ($DryRun) {
|
||||
Warn "`nDry run mode - no changes will be made."
|
||||
}
|
||||
|
||||
# Confirm
|
||||
if (-not $Force -and -not $DryRun) {
|
||||
$stepsDesc = @()
|
||||
if (-not $SkipAssign) { $stepsDesc += "assign Copilot" }
|
||||
if (-not $SkipReview) { $stepsDesc += "review" }
|
||||
if (-not $SkipFix) { $stepsDesc += "fix comments" }
|
||||
|
||||
$confirm = Read-Host "`nProceed with $($prsToProcess.Count) PRs ($($stepsDesc -join ', '))? (y/N)"
|
||||
if ($confirm -notmatch '^[yY]') {
|
||||
Info "Cancelled."
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
# Process PRs (using jobs for parallelization)
|
||||
$results = @{
|
||||
Success = @()
|
||||
Failed = @()
|
||||
}
|
||||
|
||||
if ($MaxParallel -gt 1 -and $prsToProcess.Count -gt 1) {
|
||||
# Parallel processing using PowerShell jobs
|
||||
Info "`nStarting parallel processing (max $MaxParallel concurrent)..."
|
||||
|
||||
$jobs = @()
|
||||
$prQueue = [System.Collections.Queue]::new($prsToProcess)
|
||||
|
||||
while ($prQueue.Count -gt 0 -or $jobs.Count -gt 0) {
|
||||
# Start new jobs up to MaxParallel
|
||||
while ($jobs.Count -lt $MaxParallel -and $prQueue.Count -gt 0) {
|
||||
$pr = $prQueue.Dequeue()
|
||||
|
||||
Info "`n" + ("=" * 60)
|
||||
Info "PROCESSING PR #$($pr.PRNumber)"
|
||||
Info ("=" * 60)
|
||||
|
||||
# For simplicity, process sequentially within each PR but PRs in parallel
|
||||
# Since copilot CLI might have issues with true parallel execution
|
||||
$jobResult = Start-PRWorkflowJob `
|
||||
-PRNumber $pr.PRNumber `
|
||||
-WorktreePath $pr.WorktreePath `
|
||||
-CLIType $CLIType `
|
||||
-MinSeverity $MinSeverity `
|
||||
-SkipAssign:$SkipAssign `
|
||||
-SkipReview:$SkipReview `
|
||||
-SkipFix:$SkipFix `
|
||||
-DryRun:$DryRun
|
||||
|
||||
if ($jobResult.Success) {
|
||||
$results.Success += $jobResult
|
||||
Success "✓ PR #$($pr.PRNumber) workflow completed"
|
||||
} else {
|
||||
$results.Failed += $jobResult
|
||||
Err "✗ PR #$($pr.PRNumber) workflow had failures"
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
# Sequential processing
|
||||
foreach ($pr in $prsToProcess) {
|
||||
Info "`n" + ("=" * 60)
|
||||
Info "PROCESSING PR #$($pr.PRNumber)"
|
||||
Info ("=" * 60)
|
||||
|
||||
$jobResult = Start-PRWorkflowJob `
|
||||
-PRNumber $pr.PRNumber `
|
||||
-WorktreePath $pr.WorktreePath `
|
||||
-CLIType $CLIType `
|
||||
-MinSeverity $MinSeverity `
|
||||
-SkipAssign:$SkipAssign `
|
||||
-SkipReview:$SkipReview `
|
||||
-SkipFix:$SkipFix `
|
||||
-DryRun:$DryRun
|
||||
|
||||
if ($jobResult.Success) {
|
||||
$results.Success += $jobResult
|
||||
Success "✓ PR #$($pr.PRNumber) workflow completed"
|
||||
} else {
|
||||
$results.Failed += $jobResult
|
||||
Err "✗ PR #$($pr.PRNumber) workflow had failures"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Summary
|
||||
Info "`n" + ("=" * 80)
|
||||
Info "PR REVIEW WORKFLOW COMPLETE"
|
||||
Info ("=" * 80)
|
||||
Info "Total PRs: $($prsToProcess.Count)"
|
||||
|
||||
if ($results.Success.Count -gt 0) {
|
||||
Success "Succeeded: $($results.Success.Count)"
|
||||
foreach ($r in $results.Success) {
|
||||
Success " PR #$($r.PRNumber)"
|
||||
}
|
||||
}
|
||||
|
||||
if ($results.Failed.Count -gt 0) {
|
||||
Err "Had issues: $($results.Failed.Count)"
|
||||
foreach ($r in $results.Failed) {
|
||||
Err " PR #$($r.PRNumber)"
|
||||
}
|
||||
}
|
||||
|
||||
Info "`nReview files location: Generated Files/prReview/<PR_NUMBER>/"
|
||||
Info ("=" * 80)
|
||||
|
||||
return $results
|
||||
}
|
||||
catch {
|
||||
Err "Error: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
#endregion
|
||||
170
.github/skills/pr-review/scripts/Test-IncrementalReview.ps1
vendored
Normal file
170
.github/skills/pr-review/scripts/Test-IncrementalReview.ps1
vendored
Normal file
@@ -0,0 +1,170 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Tests and previews incremental review detection for a pull request.
|
||||
|
||||
.DESCRIPTION
|
||||
This helper script validates the incremental review detection logic by analyzing an existing
|
||||
PR review folder. It reads the last reviewed SHA from the overview file, compares it with
|
||||
the current PR state, and displays detailed information about what has changed.
|
||||
|
||||
This is useful for:
|
||||
- Testing the incremental review system before running a full review
|
||||
- Understanding what changed since the last review iteration
|
||||
- Verifying that review metadata was properly recorded
|
||||
|
||||
.PARAMETER PullRequestNumber
|
||||
The pull request number to test incremental review detection for.
|
||||
|
||||
.PARAMETER RepositoryOwner
|
||||
The GitHub repository owner. Defaults to "microsoft".
|
||||
|
||||
.PARAMETER RepositoryName
|
||||
The GitHub repository name. Defaults to "PowerToys".
|
||||
|
||||
.OUTPUTS
|
||||
Colored console output displaying:
|
||||
- Current and last reviewed commit SHAs
|
||||
- Whether incremental review is possible
|
||||
- List of new commits since last review
|
||||
- List of changed files with status indicators
|
||||
- Recommended review strategy
|
||||
|
||||
.EXAMPLE
|
||||
.\Test-IncrementalReview.ps1 -PullRequestNumber 42374
|
||||
Tests incremental review detection for PR #42374.
|
||||
|
||||
.EXAMPLE
|
||||
.\Test-IncrementalReview.ps1 -PullRequestNumber 42374 -RepositoryOwner "myorg" -RepositoryName "myrepo"
|
||||
Tests incremental review for a PR in a different repository.
|
||||
|
||||
.NOTES
|
||||
Requires GitHub CLI (gh) to be installed and authenticated.
|
||||
Run 'gh auth login' if not already authenticated.
|
||||
|
||||
Prerequisites:
|
||||
- PR review folder must exist at "Generated Files\prReview\{PRNumber}"
|
||||
- 00-OVERVIEW.md must exist in the review folder
|
||||
- For incremental detection, overview must contain "Last reviewed SHA" metadata
|
||||
|
||||
.LINK
|
||||
https://cli.github.com/
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true, HelpMessage = "Pull request number to test")]
|
||||
[int]$PullRequestNumber,
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Repository owner")]
|
||||
[string]$RepositoryOwner = "microsoft",
|
||||
|
||||
[Parameter(Mandatory = $false, HelpMessage = "Repository name")]
|
||||
[string]$RepositoryName = "PowerToys"
|
||||
)
|
||||
|
||||
# Resolve paths to review folder and overview file
|
||||
$repositoryRoot = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||
$reviewFolderPath = Join-Path $repositoryRoot "Generated Files\prReview\$PullRequestNumber"
|
||||
$overviewFilePath = Join-Path $reviewFolderPath "00-OVERVIEW.md"
|
||||
|
||||
Write-Host "=== Testing Incremental Review for PR #$PullRequestNumber ===" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
# Check if review folder exists
|
||||
if (-not (Test-Path $reviewFolderPath)) {
|
||||
Write-Host "❌ Review folder not found: $reviewFolderPath" -ForegroundColor Red
|
||||
Write-Host "This appears to be a new review (iteration 1)" -ForegroundColor Yellow
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Check if overview file exists
|
||||
if (-not (Test-Path $overviewFilePath)) {
|
||||
Write-Host "❌ Overview file not found: $overviewFilePath" -ForegroundColor Red
|
||||
Write-Host "This appears to be an incomplete review" -ForegroundColor Yellow
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Read overview file and extract last reviewed SHA
|
||||
Write-Host "📄 Reading overview file..." -ForegroundColor Green
|
||||
$overviewFileContent = Get-Content $overviewFilePath -Raw
|
||||
|
||||
if ($overviewFileContent -match '\*\*Last reviewed SHA:\*\*\s+(\w+)') {
|
||||
$lastReviewedSha = $Matches[1]
|
||||
Write-Host "✅ Found last reviewed SHA: $lastReviewedSha" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host "⚠️ No 'Last reviewed SHA' found in overview - this may be an old format" -ForegroundColor Yellow
|
||||
Write-Host "Proceeding without incremental detection (full review will be needed)" -ForegroundColor Yellow
|
||||
exit 0
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "🔍 Running incremental change detection..." -ForegroundColor Cyan
|
||||
|
||||
# Call the incremental changes detection script
|
||||
$incrementalChangesScriptPath = Join-Path $PSScriptRoot "Get-PrIncrementalChanges.ps1"
|
||||
if (-not (Test-Path $incrementalChangesScriptPath)) {
|
||||
Write-Host "❌ Script not found: $incrementalChangesScriptPath" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
try {
|
||||
$analysisResult = & $incrementalChangesScriptPath `
|
||||
-PullRequestNumber $PullRequestNumber `
|
||||
-LastReviewedCommitSha $lastReviewedSha `
|
||||
-RepositoryOwner $RepositoryOwner `
|
||||
-RepositoryName $RepositoryName | ConvertFrom-Json
|
||||
|
||||
# Display analysis results
|
||||
Write-Host ""
|
||||
Write-Host "=== Incremental Review Analysis ===" -ForegroundColor Cyan
|
||||
Write-Host "Current HEAD SHA: $($analysisResult.CurrentHeadSha)" -ForegroundColor White
|
||||
Write-Host "Last reviewed SHA: $($analysisResult.LastReviewedSha)" -ForegroundColor White
|
||||
Write-Host "Base branch: $($analysisResult.BaseRefName)" -ForegroundColor White
|
||||
Write-Host "Head branch: $($analysisResult.HeadRefName)" -ForegroundColor White
|
||||
Write-Host ""
|
||||
Write-Host "Is incremental? $($analysisResult.IsIncremental)" -ForegroundColor $(if ($analysisResult.IsIncremental) { "Green" } else { "Yellow" })
|
||||
Write-Host "Need full review? $($analysisResult.NeedFullReview)" -ForegroundColor $(if ($analysisResult.NeedFullReview) { "Yellow" } else { "Green" })
|
||||
Write-Host ""
|
||||
Write-Host "Summary: $($analysisResult.Summary)" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
# Display new commits if any
|
||||
if ($analysisResult.NewCommits -and $analysisResult.NewCommits.Count -gt 0) {
|
||||
Write-Host "📝 New commits ($($analysisResult.NewCommits.Count)):" -ForegroundColor Green
|
||||
foreach ($commit in $analysisResult.NewCommits) {
|
||||
Write-Host " - $($commit.Sha): $($commit.Message)" -ForegroundColor Gray
|
||||
}
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
# Display changed files if any
|
||||
if ($analysisResult.ChangedFiles -and $analysisResult.ChangedFiles.Count -gt 0) {
|
||||
Write-Host "📁 Changed files ($($analysisResult.ChangedFiles.Count)):" -ForegroundColor Green
|
||||
foreach ($file in $analysisResult.ChangedFiles) {
|
||||
$statusDisplayColor = switch ($file.Status) {
|
||||
"added" { "Green" }
|
||||
"removed" { "Red" }
|
||||
"modified" { "Yellow" }
|
||||
"renamed" { "Cyan" }
|
||||
default { "White" }
|
||||
}
|
||||
Write-Host " - [$($file.Status)] $($file.Filename) (+$($file.Additions)/-$($file.Deletions))" -ForegroundColor $statusDisplayColor
|
||||
}
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
# Suggest review strategy based on analysis
|
||||
Write-Host "=== Recommended Review Strategy ===" -ForegroundColor Cyan
|
||||
if ($analysisResult.NeedFullReview) {
|
||||
Write-Host "🔄 Full review recommended" -ForegroundColor Yellow
|
||||
} elseif ($analysisResult.IsIncremental -and ($analysisResult.ChangedFiles.Count -eq 0)) {
|
||||
Write-Host "✅ No changes detected - no review needed" -ForegroundColor Green
|
||||
} elseif ($analysisResult.IsIncremental) {
|
||||
Write-Host "⚡ Incremental review possible - review only changed files" -ForegroundColor Green
|
||||
Write-Host "💡 Consider applying smart step filtering based on file types" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
} catch {
|
||||
Write-Host "❌ Error running incremental change detection: $_" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
30
.github/skills/release-note-generation/SKILL.md
vendored
30
.github/skills/release-note-generation/SKILL.md
vendored
@@ -1,12 +1,12 @@
|
||||
---
|
||||
name: release-note-generation
|
||||
description: Toolkit for generating PowerToys release notes from GitHub milestone PRs or commit ranges. Use when asked to create release notes, summarize milestone PRs, generate changelog, prepare release documentation, generate PR review summaries locally for release notes, update README for a new release, manage PR milestones, collect PRs between commits/tags, or prepare release assets (download installers and compute installer hashes).
|
||||
description: Toolkit for generating PowerToys release notes from GitHub milestone PRs or commit ranges. Use when asked to create release notes, summarize milestone PRs, generate changelog, prepare release documentation, request Copilot reviews for PRs, update README for a new release, manage PR milestones, or collect PRs between commits/tags. Supports PR collection by milestone or commit range, milestone assignment, grouping by label, summarization with external contributor attribution, and README version bumping.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# Release Note Generation Skill
|
||||
|
||||
Generate professional release notes for PowerToys milestones by collecting merged PRs, summarizing each PR with the local CLI agent, grouping by label, and producing user-facing summaries.
|
||||
Generate professional release notes for PowerToys milestones by collecting merged PRs, requesting Copilot code reviews, grouping by label, and producing user-facing summaries.
|
||||
|
||||
## Output Directory
|
||||
|
||||
@@ -26,17 +26,16 @@ Generated Files/ReleaseNotes/
|
||||
|
||||
- Generate release notes for a milestone
|
||||
- Summarize PRs merged in a release
|
||||
- Generate per-PR review summaries locally for release-notes copy
|
||||
- Request Copilot reviews for milestone PRs
|
||||
- Assign milestones to PRs missing them
|
||||
- Collect PRs between two commits/tags
|
||||
- Update README.md for a new version
|
||||
- Prepare GitHub release assets (download installers/symbols + compute hashes)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **GitHub CLI (`gh`) installed and authenticated** — The collection script uses `gh pr view` and `gh api graphql` to fetch PR metadata and co-author information. Run `gh auth status` to verify; if not logged in, run `gh auth login` first. See [Step 1.0.0](./references/step1-collection.md) for details.
|
||||
- MCP Server: github-mcp-server installed (used to fetch PR diffs/files for the local-agent review step)
|
||||
- For [prepare-release-assets.ps1](./scripts/prepare-release-assets.ps1) only: **Azure CLI** authenticated against the Microsoft tenant (`az login`) with the `azure-devops` extension; access to the `microsoft/Dart` ADO project
|
||||
- GitHub CLI (`gh`) installed and authenticated
|
||||
- MCP Server: github-mcp-server installed
|
||||
- GitHub Copilot code review enabled for the org/repo
|
||||
|
||||
## Required Variables
|
||||
|
||||
@@ -50,10 +49,6 @@ Generated Files/ReleaseNotes/
|
||||
|
||||
```
|
||||
┌────────────────────────────────┐
|
||||
│ 1.0 Verify gh auth + MemberList │
|
||||
└────────────────────────────────┘
|
||||
↓
|
||||
┌────────────────────────────────┐
|
||||
│ 1.1 Collect PRs (stable range) │
|
||||
└────────────────────────────────┘
|
||||
↓
|
||||
@@ -66,12 +61,12 @@ Generated Files/ReleaseNotes/
|
||||
└────────────────────────────────┘
|
||||
↓
|
||||
┌────────────────────────────────┐
|
||||
│ 3.1 Local-agent PR summaries │
|
||||
│ (writes CopilotSummary) │
|
||||
│ 3.1 Request Reviews (Copilot) │
|
||||
└────────────────────────────────┘
|
||||
↓
|
||||
┌────────────────────────────────┐
|
||||
│ 3.2 (Optional) Refresh PR data │
|
||||
│ 3.2 Refresh PR data │
|
||||
│ (CopilotSummary) │
|
||||
└────────────────────────────────┘
|
||||
↓
|
||||
┌────────────────────────────────┐
|
||||
@@ -90,11 +85,10 @@ Generated Files/ReleaseNotes/
|
||||
|
||||
| Step | Action | Details |
|
||||
|------|--------|---------|
|
||||
| 1.0 | Verify prerequisites | `gh auth status` must pass; generate MemberList.md |
|
||||
| 1.1 | Collect PRs | From previous release tag on `stable` branch → `sorted_prs.csv` |
|
||||
| 1.2 | Assign Milestones | Ensure all PRs have correct milestone |
|
||||
| 2.1–2.4 | Label PRs | Auto-suggest + human label low-confidence |
|
||||
| 3.1–3.3 | Reviews & Grouping | Local agent summarizes each PR diff into `CopilotSummary` → (optional refresh) → group by label |
|
||||
| 3.1–3.3 | Reviews & Grouping | Request Copilot reviews → refresh → group by label |
|
||||
| 4.1–4.2 | Summaries & Final | Generate grouped summaries, then consolidate |
|
||||
|
||||
## Detailed workflow docs
|
||||
@@ -115,7 +109,6 @@ Do not read all steps at once—only read the step you are executing.
|
||||
| [group-prs-by-label.ps1](./scripts/group-prs-by-label.ps1) | Group PRs into CSVs |
|
||||
| [collect-or-apply-milestones.ps1](./scripts/collect-or-apply-milestones.ps1) | Assign milestones |
|
||||
| [diff_prs.ps1](./scripts/diff_prs.ps1) | Incremental PR diff |
|
||||
| [prepare-release-assets.ps1](./scripts/prepare-release-assets.ps1) | Download installers + symbols from an ADO build, compute SHA256, emit the "Installer Hashes" markdown table for the GitHub release page |
|
||||
|
||||
## References
|
||||
|
||||
@@ -135,6 +128,5 @@ Do not read all steps at once—only read the step you are executing.
|
||||
|-------|----------|
|
||||
| `gh` command not found | Install GitHub CLI and add to PATH |
|
||||
| No PRs returned | Verify milestone title matches exactly |
|
||||
| Empty `CopilotSummary` for many PRs | Run Step 3.1 (local-agent summaries). Do **not** use `mcp_github_request_copilot_review` from a CLI/coding agent — the GitHub API rejects bot-initiated review requests, so the column will stay empty. |
|
||||
| Empty CopilotSummary | Request Copilot reviews first, then re-run dump |
|
||||
| Many unlabeled PRs | Return to labeling step before grouping |
|
||||
| `prepare-release-assets.ps1` fails with "Failed to acquire ADO access token" | Run `az login` and ensure you have access to the `microsoft/Dart` ADO project |
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
- Added mouse button actions so you can choose what left, right, or middle click does in [#1234](https://github.com/microsoft/PowerToys/pull/1234) by [@PesBandi](https://github.com/PesBandi)
|
||||
- Added mouse button actions so you can choose what left, right, or middle click does. Thanks [@PesBandi](https://github.com/PesBandi)!
|
||||
|
||||
- Aligned window styling with current Windows theme for a cleaner look in [#1235](https://github.com/microsoft/PowerToys/pull/1235) by [@sadirano](https://github.com/sadirano)
|
||||
- Aligned window styling with current Windows theme for a cleaner look. Thanks [@sadirano](https://github.com/sadirano)!
|
||||
|
||||
- Ensured screen readers are notified when the selected item in the list changes for better accessibility in [#1236](https://github.com/microsoft/PowerToys/pull/1236)
|
||||
- Ensured screen readers are notified when the selected item in the list changes for better accessibility.
|
||||
|
||||
- Implemented configurable UI test pipeline that can use pre-built official releases instead of building everything from scratch, reducing test execution time from 2+ hours in [#1237](https://github.com/microsoft/PowerToys/pull/1237)
|
||||
- Implemented configurable UI test pipeline that can use pre-built official releases instead of building everything from scratch, reducing test execution time from 2+ hours.
|
||||
|
||||
- Fixed Alt+Left Arrow navigation not working when search box contains text in [#1238](https://github.com/microsoft/PowerToys/pull/1238) by [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Fixed Alt+Left Arrow navigation not working when search box contains text. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
@@ -1,7 +1,6 @@
|
||||
# Step 1: Collection and Milestones
|
||||
|
||||
## 1.0 To-do
|
||||
- 1.0.0 Verify GitHub CLI authentication (REQUIRED)
|
||||
- 1.0.1 Generate MemberList.md (REQUIRED)
|
||||
- 1.1 Collect PRs
|
||||
- 1.2 Assign Milestones (REQUIRED)
|
||||
@@ -21,34 +20,6 @@
|
||||
|
||||
---
|
||||
|
||||
## 1.0.0 Verify GitHub CLI Authentication (REQUIRED)
|
||||
|
||||
⚠️ **BLOCKING:** The collection script requires an authenticated `gh` CLI to fetch PR metadata and co-author information via GitHub's GraphQL API. Without authentication, PR data and `NeedThanks` attribution will be incomplete.
|
||||
|
||||
### Check authentication status
|
||||
|
||||
```powershell
|
||||
gh auth status
|
||||
```
|
||||
|
||||
**If authenticated:** You'll see `Logged in to github.com account <username>`. Proceed to 1.0.1.
|
||||
|
||||
**If NOT authenticated:** Run the login flow before continuing:
|
||||
|
||||
```powershell
|
||||
# Interactive login (opens browser for OAuth)
|
||||
gh auth login --hostname github.com --web
|
||||
|
||||
# Or use a personal access token
|
||||
gh auth login --with-token <<< "YOUR_GITHUB_TOKEN"
|
||||
```
|
||||
|
||||
**Required scopes:** `repo` (for reading PR data and assigning milestones)
|
||||
|
||||
After login, verify again with `gh auth status` and confirm exit code 0.
|
||||
|
||||
---
|
||||
|
||||
## 1.0.1 Generate MemberList.md (REQUIRED)
|
||||
|
||||
Create `Generated Files/ReleaseNotes/MemberList.md` from the **PowerToys core team** section in [COMMUNITY.md](../../../COMMUNITY.md).
|
||||
@@ -109,8 +80,6 @@ The script detects both merge commits (`Merge pull request #12345`) and squash c
|
||||
**Output** (in `Generated Files/ReleaseNotes/`):
|
||||
- `milestone_prs.json` - raw PR data
|
||||
- `sorted_prs.csv` - sorted PR list with columns: Id, Title, Labels, Author, Url, Body, CopilotSummary, NeedThanks
|
||||
- `Author`: Comma-separated list of all contributors (PR opener + co-authors from commit trailers)
|
||||
- `NeedThanks`: Comma-separated list of external contributors to thank (excludes core team members from MemberList.md). Empty string means no thanks needed.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,40 +1,22 @@
|
||||
# Step 3: Local Agent Reviews and Grouping
|
||||
# Step 3: Copilot Reviews and Grouping
|
||||
|
||||
## 3.0 To-do
|
||||
- 3.1 Generate PR Summaries with the Local Agent
|
||||
- 3.2 (Optional) Refresh PR Data
|
||||
- 3.1 Request Copilot Reviews (Agent Mode)
|
||||
- 3.2 Refresh PR Data
|
||||
- 3.3 Group PRs by Label
|
||||
|
||||
## 3.1 Generate PR Summaries with the Local Agent
|
||||
## 3.1 Request Copilot Reviews (Agent Mode)
|
||||
|
||||
> ⚠️ **Do not use `mcp_github_request_copilot_review` (or any "request Copilot review" tool that calls the GitHub API).**
|
||||
> When this skill is driven from a CLI / coding agent, the request is made from a bot identity and the GitHub API rejects it ("Bot reviewers cannot be requested"). The PR ends up with no Copilot review and `CopilotSummary` stays empty.
|
||||
>
|
||||
> Instead, **the local agent that is running this skill performs the review itself** and writes the summary directly into `sorted_prs.csv`.
|
||||
Use MCP tools to request Copilot reviews for all PRs in `Generated Files/ReleaseNotes/sorted_prs.csv`:
|
||||
|
||||
For every PR listed in `Generated Files/ReleaseNotes/sorted_prs.csv` whose `CopilotSummary` is empty:
|
||||
|
||||
1. Fetch the PR diff using a tool that does **not** post anything back to GitHub. Any of these works:
|
||||
- `mcp_github_pull_request_read` with `method: get_diff`
|
||||
- `mcp_github_pull_request_read` with `method: get_files` (when the diff is large)
|
||||
- `gh pr diff <PR_NUMBER> --repo microsoft/PowerToys`
|
||||
2. Read the PR title, body, and diff. Produce a 1–3 sentence, user-facing summary in the same style as a Copilot PR review (focus on observable behavior change, not implementation details).
|
||||
3. Write the summary into the `CopilotSummary` column for that PR row in `Generated Files/ReleaseNotes/sorted_prs.csv`. Preserve all other columns and the existing row order.
|
||||
|
||||
**Batching guidance**
|
||||
|
||||
- Process PRs in the order they appear in `sorted_prs.csv`.
|
||||
- Generate summaries for **all** PRs in one pass before continuing to Step 3.3, so the human reviewer can validate them together.
|
||||
- For very large diffs, summarize from `get_files` (filenames + per-file patches) rather than the full diff.
|
||||
- Skip PRs that already have a non-empty `CopilotSummary` (e.g. PRs where a human reviewer already pasted one). Do not overwrite existing summaries.
|
||||
|
||||
**Why not post the summary back to the PR?** Posting a comment from the agent's identity would not be picked up by `dump-prs-since-commit.ps1` (which only matches Copilot bot authors), and it adds noise to the PR. Writing straight into the CSV keeps the artifact self-contained.
|
||||
- Use `mcp_github_request_copilot_review` for each PR ID
|
||||
- Do NOT generate or run scripts for this step
|
||||
|
||||
---
|
||||
|
||||
## 3.2 (Optional) Refresh PR Data
|
||||
## 3.2 Refresh PR Data
|
||||
|
||||
Only re-run the collection script if PR metadata on GitHub has changed (new labels, retitled PRs, etc.) since Step 1.1. **Skip this step if you only want to preserve the locally generated `CopilotSummary` values from Step 3.1**, because re-running the dump will overwrite the CSV.
|
||||
Re-run the collection script to capture Copilot review summaries into the `CopilotSummary` column:
|
||||
|
||||
```powershell
|
||||
pwsh ./.github/skills/release-note-generation/scripts/dump-prs-since-commit.ps1 `
|
||||
@@ -42,8 +24,6 @@ pwsh ./.github/skills/release-note-generation/scripts/dump-prs-since-commit.ps1
|
||||
-OutputDir 'Generated Files/ReleaseNotes'
|
||||
```
|
||||
|
||||
If you do refresh, redo Step 3.1 afterwards to repopulate `CopilotSummary`.
|
||||
|
||||
---
|
||||
|
||||
## 3.3 Group PRs by Label
|
||||
@@ -55,4 +35,3 @@ pwsh ./.github/skills/release-note-generation/scripts/group-prs-by-label.ps1 -Cs
|
||||
Creates `Generated Files/ReleaseNotes/grouped_csv/` with one CSV per label combination.
|
||||
|
||||
**Validation:** The `Unlabeled.csv` file should be minimal (ideally empty). If many PRs remain unlabeled, return to Step 2 (see [step2-labeling.md](./step2-labeling.md)).
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ For each CSV in `Generated Files/ReleaseNotes/grouped_csv/`, create a markdown f
|
||||
- Use the “Verb-ed + Scenario + Impact” sentence structure—make readers think, “That’s exactly what I need” or “Yes, that’s an awesome fix.”; The "impact" can be end-user focused (written to convey user excitement) or technical (performance/stability) when user-facing impact is minimal.
|
||||
- If nothing special on impact or unclear impact, mark as needing human summary
|
||||
- Source from Title, Body, and CopilotSummary (prefer CopilotSummary when available)
|
||||
- The `NeedThanks` column contains a comma-separated list of external contributor usernames who should be credited (empty = no attribution needed, all authors are core team). For each non-empty `NeedThanks` value, append a `by` attribution that lists **every** contributor, matching GitHub's standard contributor-attribution style: `by [@user1](https://github.com/user1)` for a single contributor, `by [@user1](https://github.com/user1) and [@user2](https://github.com/user2)` for two, or `by [@user1](https://github.com/user1), [@user2](https://github.com/user2), and [@user3](https://github.com/user3)` for three or more. In the final consolidated release notes (Step 4.2), the attribution follows the PR link, e.g. `…in [#1234](url) by [@user](url)`. Do not use "Thanks @user!" phrasing.
|
||||
- If the column `NeedThanks` in CSV is `True`, append: `Thanks [@Author](https://github.com/Author)!`
|
||||
- Do NOT include PR numbers in bullet lines
|
||||
- Do NOT mention “security” or “privacy” issues, since these are not known and could be leveraged by attackers in earlier versions. Instead, describe the user-facing scenario, usage, or impact.
|
||||
- If confidence < 70%, write: `Human Summary Needed: <PR full link>`
|
||||
@@ -72,13 +72,13 @@ Some items in the Development section may overlap and should be moved to the Mod
|
||||
|
||||
## Advanced Paste
|
||||
|
||||
- Wrapped paste option lists in a single ScrollViewer in [#5678](https://github.com/microsoft/PowerToys/pull/5678)
|
||||
- Added image input handling for AI-powered transformations in [#5679](https://github.com/microsoft/PowerToys/pull/5679)
|
||||
- Wrapped paste option lists in a single ScrollViewer
|
||||
- Added image input handling for AI-powered transformations
|
||||
...
|
||||
|
||||
## Awake
|
||||
|
||||
- Fixed timed mode expiration in [#5680](https://github.com/microsoft/PowerToys/pull/5680) by [@daverayment](https://github.com/daverayment)
|
||||
- Fixed timed mode expiration. Thanks [@daverayment](https://github.com/daverayment)!
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
@@ -42,7 +42,30 @@ param(
|
||||
[string]$OutputJson = "milestone_prs.json"
|
||||
)
|
||||
|
||||
# (See top-level synopsis above for full documentation)
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Dump merged PR information whose merge commits are reachable from EndCommit but not from StartCommit.
|
||||
.DESCRIPTION
|
||||
Uses git rev-list to compute commits in the (StartCommit, EndCommit] range, extracts PR numbers from merge commit messages,
|
||||
queries GitHub (gh CLI) for details, then outputs a CSV.
|
||||
|
||||
PR merge commit messages in PowerToys generally contain patterns like:
|
||||
Merge pull request #12345 from ...
|
||||
|
||||
.EXAMPLE
|
||||
pwsh ./dump-prs-since-commit.ps1 -StartCommit 0123abcd -Branch stable
|
||||
|
||||
.EXAMPLE
|
||||
pwsh ./dump-prs-since-commit.ps1 -StartCommit 0123abcd -EndCommit 89ef7654 -OutputCsv changes.csv
|
||||
|
||||
.NOTES
|
||||
Requires: gh CLI authenticated; git available in working directory (must be inside PowerToys repo clone).
|
||||
CopilotSummary behavior:
|
||||
- Attempts to locate the latest GitHub Copilot authored review (preferred).
|
||||
- If no review is found, lazily fetches PR comments to look for a Copilot-authored comment.
|
||||
- Normalizes whitespace and strips newlines. Empty when no Copilot activity detected.
|
||||
- Run with -Verbose to see whether the summary came from a 'review' or 'comment' source.
|
||||
#>
|
||||
|
||||
function Write-Info($msg) { Write-Host $msg -ForegroundColor Cyan }
|
||||
function Write-Warn($msg) { Write-Host $msg -ForegroundColor Yellow }
|
||||
@@ -128,11 +151,11 @@ catch {
|
||||
}
|
||||
|
||||
Write-Info "Collecting commits between $startSha..$endSha (excluding start, including end)."
|
||||
# Get list of commits reachable from end but not from start.
|
||||
# IMPORTANT: In PowerShell, the .. operator creates a numeric/char range. If $startSha and $endSha look like hex strings,
|
||||
# `$startSha..$endSha` must be passed as a single string argument.
|
||||
$rangeArg = "$startSha..$endSha"
|
||||
$commitList = git rev-list $rangeArg
|
||||
# Get list of commits reachable from end but not from start.
|
||||
# IMPORTANT: In PowerShell, the .. operator creates a numeric/char range. If $startSha and $endSha look like hex strings,
|
||||
# `$startSha..$endSha` must be passed as a single string argument.
|
||||
$rangeArg = "$startSha..$endSha"
|
||||
$commitList = git rev-list $rangeArg
|
||||
|
||||
# Normalize list (filter out empty strings)
|
||||
$normalizedCommits = $commitList | Where-Object { $_ -and $_.Trim() -ne '' }
|
||||
@@ -187,63 +210,6 @@ $prNumbers = $mergeCommits | Select-Object -ExpandProperty Pr -Unique | Sort-Obj
|
||||
Write-Info ("Found {0} unique PRs: {1}" -f $prNumbers.Count, ($prNumbers -join ', '))
|
||||
Write-DebugMsg ("Total merge commits examined: {0}" -f $mergeCommits.Count)
|
||||
|
||||
# Build a map of PR number → list of commit SHAs (for co-author extraction)
|
||||
$prToCommits = @{}
|
||||
foreach ($mc in $mergeCommits) {
|
||||
if (-not $prToCommits.ContainsKey($mc.Pr)) {
|
||||
$prToCommits[$mc.Pr] = @()
|
||||
}
|
||||
$prToCommits[$mc.Pr] += $mc.Sha
|
||||
}
|
||||
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Get all authors (including co-authors) for a set of commits via GitHub GraphQL API.
|
||||
.DESCRIPTION
|
||||
Uses the Commit.authors field in GitHub's GraphQL API which natively includes
|
||||
co-authors (from Co-authored-by trailers). Returns GitHub usernames (login)
|
||||
without any email parsing — GitHub resolves the association for us.
|
||||
|
||||
NOTE: For squash merges this captures all co-authors correctly because GitHub
|
||||
preserves Co-authored-by trailers in the squash commit. For traditional merge
|
||||
commits, only the merger's author is returned — co-authors on individual PR
|
||||
commits are not traversed. This is acceptable because PowerToys primarily uses
|
||||
squash merging.
|
||||
#>
|
||||
function Get-CommitAuthors {
|
||||
param(
|
||||
[string[]]$CommitShas,
|
||||
[string]$RepoFullName = "microsoft/PowerToys"
|
||||
)
|
||||
$parts = $RepoFullName -split '/'
|
||||
$owner = $parts[0]
|
||||
$repoName = $parts[1]
|
||||
$allAuthors = @()
|
||||
|
||||
foreach ($sha in $CommitShas) {
|
||||
try {
|
||||
$query = "{ repository(owner: `"$owner`", name: `"$repoName`") { object(expression: `"$sha`") { ... on Commit { authors(first: 20) { nodes { user { login } name } } } } } }"
|
||||
$result = gh api graphql -f query="$query" 2>$null | ConvertFrom-Json
|
||||
$nodes = $result.data.repository.object.authors.nodes
|
||||
if ($nodes) {
|
||||
foreach ($node in $nodes) {
|
||||
if ($node.user -and $node.user.login) {
|
||||
$allAuthors += $node.user.login
|
||||
} else {
|
||||
# User without a GitHub account (rare) — use display name as fallback
|
||||
Write-DebugMsg "Commit $sha has an author without GitHub account: $($node.name)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-DebugMsg "GraphQL authors query failed for commit ${sha}: $_"
|
||||
}
|
||||
}
|
||||
|
||||
return $allAuthors | Select-Object -Unique
|
||||
}
|
||||
|
||||
# Query GitHub for each PR
|
||||
$prDetails = @()
|
||||
function Get-CopilotSummaryFromPrJson {
|
||||
@@ -341,45 +307,22 @@ foreach ($pr in $prNumbers) {
|
||||
$bodyValue = if ($json.body) { ($json.body -replace "`r", '') -replace "`n", ' ' } else { '' }
|
||||
$bodyValue = $bodyValue -replace '\s+', ' '
|
||||
|
||||
# Collect all contributors: PR author + co-authors from commit messages
|
||||
# Determine if author needs thanks (not in member list)
|
||||
$authorLogin = $json.author.login
|
||||
$allContributors = @($authorLogin)
|
||||
|
||||
# Extract all authors (including co-authors) from associated commits via GitHub GraphQL API
|
||||
if ($prToCommits.ContainsKey([int]$pr)) {
|
||||
$commitAuthors = Get-CommitAuthors -CommitShas $prToCommits[[int]$pr] -RepoFullName $Repo
|
||||
if ($commitAuthors) {
|
||||
$allContributors += $commitAuthors
|
||||
}
|
||||
$needThanks = $true
|
||||
if ($memberList.Count -gt 0 -and $authorLogin) {
|
||||
$needThanks = -not ($memberList -contains $authorLogin)
|
||||
}
|
||||
|
||||
# Deduplicate contributors (case-insensitive)
|
||||
$allContributors = $allContributors | Where-Object { $_ } | Sort-Object -Unique
|
||||
|
||||
# Filter to only external contributors (not in member list) for thanks
|
||||
$externalContributors = @()
|
||||
if ($memberList.Count -gt 0) {
|
||||
$externalContributors = $allContributors | Where-Object { -not ($memberList -contains $_) }
|
||||
} else {
|
||||
$externalContributors = $allContributors
|
||||
}
|
||||
|
||||
# Author column: all contributors (comma-separated)
|
||||
$authorField = ($allContributors -join ', ')
|
||||
|
||||
# NeedThanks column: comma-separated list of external contributors who
|
||||
# deserve thanks attribution. Empty string means no thanks needed.
|
||||
$needThanksField = ($externalContributors -join ', ')
|
||||
|
||||
$prDetails += [PSCustomObject]@{
|
||||
Id = $json.number
|
||||
Title = $json.title
|
||||
Labels = $labelNames
|
||||
Author = $authorField
|
||||
Author = $authorLogin
|
||||
Url = $json.url
|
||||
Body = $bodyValue
|
||||
CopilotSummary = $copilot.Summary
|
||||
NeedThanks = $needThanksField
|
||||
NeedThanks = $needThanks
|
||||
}
|
||||
}
|
||||
catch {
|
||||
|
||||
@@ -1,334 +0,0 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Prepares the binary assets for a PowerToys GitHub release: downloads the
|
||||
four installers (per-user/per-machine x x64/arm64) and the symbol archives
|
||||
from an ADO pipeline build, computes SHA256 hashes, and emits the
|
||||
"Installer Hashes" markdown table.
|
||||
|
||||
.DESCRIPTION
|
||||
Given an ADO Dart pipeline build id (e.g. from
|
||||
https://microsoft.visualstudio.com/Dart/_build/results?buildId=NNN),
|
||||
downloads the four installer EXEs and the per-arch symbol zips into a
|
||||
single per-version folder, then writes a hashes.md alongside them with a
|
||||
markdown table ready to paste into the GitHub release notes.
|
||||
|
||||
Requires: az login (Azure CLI authenticated), az devops extension.
|
||||
|
||||
.EXAMPLE
|
||||
.\prepare-release-assets.ps1 -BuildId 145505247
|
||||
.\prepare-release-assets.ps1 -BuildId 145505247 -OutputFolder D:\Releases
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[int]$BuildId,
|
||||
|
||||
[string]$OutputFolder = "$env:USERPROFILE\Downloads",
|
||||
|
||||
[string]$Organization = "https://dev.azure.com/microsoft",
|
||||
[string]$Project = "Dart",
|
||||
|
||||
[string]$GitHubRepo = "microsoft/PowerToys"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$env:AZURE_CORE_NO_PROMPT = "true"
|
||||
|
||||
# --- Helpers -----------------------------------------------------------------
|
||||
|
||||
# Invoke an `az` CLI command and capture stderr in $script:LastAzError so
|
||||
# callers can surface the underlying message (expired login, blocked extension,
|
||||
# tenant policy, ...) instead of swallowing it with `2>$null`.
|
||||
function Invoke-Az {
|
||||
$tmpErr = [System.IO.Path]::GetTempFileName()
|
||||
try {
|
||||
$output = & az @args 2>$tmpErr
|
||||
# Get-Content -Raw returns $null for an empty file, and calling .Trim()
|
||||
# on $null throws under $ErrorActionPreference = 'Stop' -- which would
|
||||
# turn every successful (no-stderr) az call into a fatal error. Guard
|
||||
# explicitly so $script:LastAzError is always a (possibly empty) string.
|
||||
$rawErr = Get-Content $tmpErr -Raw -ErrorAction SilentlyContinue
|
||||
$script:LastAzError = if ($null -eq $rawErr) { '' } else { $rawErr.Trim() }
|
||||
return $output
|
||||
}
|
||||
finally {
|
||||
Remove-Item $tmpErr -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
# Build an ADO artifact download URL from scratch instead of regex-replacing
|
||||
# the URL returned by `az pipelines runs artifact list`. Preserves any other
|
||||
# query parameters and only swaps `format` and `subPath`, so we don't break if
|
||||
# the upstream URL shape ever changes.
|
||||
function Get-ArtifactDownloadUrl {
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$BaseUrl,
|
||||
[Parameter(Mandatory)][string]$SubPath,
|
||||
[Parameter(Mandatory)][ValidateSet('file', 'zip')][string]$Format
|
||||
)
|
||||
$encodedSubPath = [Uri]::EscapeDataString($SubPath)
|
||||
$idx = $BaseUrl.IndexOf('?')
|
||||
if ($idx -lt 0) {
|
||||
return "${BaseUrl}?format=${Format}&subPath=${encodedSubPath}"
|
||||
}
|
||||
$base = $BaseUrl.Substring(0, $idx)
|
||||
$kept = $BaseUrl.Substring($idx + 1) -split '&' | Where-Object {
|
||||
$_ -and -not ($_ -match '^(format|subPath)=')
|
||||
}
|
||||
$kept = @($kept) + @("format=$Format", "subPath=$encodedSubPath")
|
||||
return "${base}?$($kept -join '&')"
|
||||
}
|
||||
|
||||
# Download a single ADO artifact file with bearer auth and a small retry/backoff
|
||||
# loop. A transient network blip on a ~200 MB installer or symbol zip otherwise
|
||||
# aborts the entire release-prep run.
|
||||
function Invoke-AdoDownload {
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Url,
|
||||
[Parameter(Mandatory)][string]$DestPath,
|
||||
[Parameter(Mandatory)][string]$Token,
|
||||
[int]$MaxAttempts = 3
|
||||
)
|
||||
$lastError = $null
|
||||
for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
|
||||
$webClient = New-Object System.Net.WebClient
|
||||
$webClient.Headers.Add("Authorization", "Bearer $Token")
|
||||
try {
|
||||
$webClient.DownloadFile($Url, $DestPath)
|
||||
return
|
||||
}
|
||||
catch {
|
||||
$lastError = $_
|
||||
if (Test-Path $DestPath) {
|
||||
Remove-Item $DestPath -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
if ($attempt -lt $MaxAttempts) {
|
||||
$backoffSec = [int][Math]::Pow(2, $attempt) # 2, 4, 8 ...
|
||||
Write-Host " Attempt $attempt failed: $($_.Exception.Message). Retrying in ${backoffSec}s..." -ForegroundColor Yellow
|
||||
Start-Sleep -Seconds $backoffSec
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$webClient.Dispose()
|
||||
}
|
||||
}
|
||||
throw "Download failed after $MaxAttempts attempts. Last error: $($lastError.Exception.Message)`nURL: $Url"
|
||||
}
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
# Work around broken az extensions: if the default extension dir has
|
||||
# inaccessible files, redirect to a clean directory.
|
||||
$defaultExtDir = "$env:USERPROFILE\.azure\cliextensions"
|
||||
if (-not $env:AZURE_EXTENSION_DIR -and (Test-Path $defaultExtDir)) {
|
||||
$broken = Get-ChildItem "$defaultExtDir\*\*.dist-info" -Directory -ErrorAction SilentlyContinue | Where-Object {
|
||||
try { [System.IO.Directory]::GetFiles($_.FullName) | Out-Null; $false } catch { $true }
|
||||
}
|
||||
if ($broken) {
|
||||
$cleanDir = "$env:USERPROFILE\.azure\cliextensions_clean"
|
||||
Write-Host " Detected broken az extension, redirecting to $cleanDir" -ForegroundColor Yellow
|
||||
$env:AZURE_EXTENSION_DIR = $cleanDir
|
||||
if (-not (Test-Path $cleanDir)) { New-Item -ItemType Directory -Path $cleanDir -Force | Out-Null }
|
||||
}
|
||||
}
|
||||
|
||||
# Ensure azure-devops extension is installed
|
||||
$ext = Invoke-Az extension list --query "[?name=='azure-devops']" -o tsv
|
||||
if (-not $ext) {
|
||||
Write-Host "Installing azure-devops extension..." -ForegroundColor Yellow
|
||||
Invoke-Az extension add --name azure-devops --yes | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Error "Failed to install azure-devops extension. (az: $script:LastAzError)"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
# Configure az devops defaults
|
||||
Invoke-Az devops configure --defaults organization=$Organization project=$Project | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Error "Failed to configure az devops defaults. (az: $script:LastAzError)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# --- Step 1: Get build info to determine version ---
|
||||
Write-Host "Fetching build $BuildId info..." -ForegroundColor Cyan
|
||||
$buildJson = Invoke-Az pipelines build show --id $BuildId --output json
|
||||
if (-not $buildJson) {
|
||||
Write-Error "Could not fetch build $BuildId. Are you logged in (az login)? (az: $script:LastAzError)"
|
||||
exit 1
|
||||
}
|
||||
$build = $buildJson | ConvertFrom-Json
|
||||
|
||||
$versionParam = $build.templateParameters.VersionNumber
|
||||
if (-not $versionParam) {
|
||||
Write-Error "Could not determine version from build $BuildId"
|
||||
exit 1
|
||||
}
|
||||
Write-Host " Version: $versionParam" -ForegroundColor DarkGray
|
||||
|
||||
# --- Step 2: Get artifact metadata once ---
|
||||
Write-Host "Fetching artifact metadata..." -ForegroundColor Cyan
|
||||
$artifactsJson = Invoke-Az pipelines runs artifact list --run-id $BuildId --output json
|
||||
if (-not $artifactsJson) {
|
||||
Write-Error "Could not list artifacts for build $BuildId. (az: $script:LastAzError)"
|
||||
exit 1
|
||||
}
|
||||
$artifacts = $artifactsJson | ConvertFrom-Json
|
||||
|
||||
# --- Step 3: Prepare destination folder ---
|
||||
$destFolder = Join-Path $OutputFolder "PowerToys-v$versionParam"
|
||||
if (-not (Test-Path $destFolder)) {
|
||||
New-Item -ItemType Directory -Path $destFolder -Force | Out-Null
|
||||
}
|
||||
Write-Host " Destination: $destFolder" -ForegroundColor DarkGray
|
||||
|
||||
# --- Step 4: Get an ADO access token once ---
|
||||
$token = Invoke-Az account get-access-token --resource "499b84ac-1321-427f-aa17-267ca6975798" --query accessToken -o tsv
|
||||
if (-not $token) {
|
||||
Write-Error "Failed to acquire ADO access token. Run 'az login' first. (az: $script:LastAzError)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# --- Step 5: Define the four installers to download ---
|
||||
$targets = @(
|
||||
[pscustomobject]@{ Description = "Per user - x64"; Scope = "perUser"; Arch = "x64"; Artifact = "build-x64-Release"; FileName = "PowerToysUserSetup-$versionParam-x64.exe" }
|
||||
[pscustomobject]@{ Description = "Per user - ARM64"; Scope = "perUser"; Arch = "arm64"; Artifact = "build-arm64-Release"; FileName = "PowerToysUserSetup-$versionParam-arm64.exe" }
|
||||
[pscustomobject]@{ Description = "Machine wide - x64"; Scope = "perMachine"; Arch = "x64"; Artifact = "build-x64-Release"; FileName = "PowerToysSetup-$versionParam-x64.exe" }
|
||||
[pscustomobject]@{ Description = "Machine wide - ARM64"; Scope = "perMachine"; Arch = "arm64"; Artifact = "build-arm64-Release"; FileName = "PowerToysSetup-$versionParam-arm64.exe" }
|
||||
)
|
||||
|
||||
# --- Step 6: Download each installer (skip if already present) ---
|
||||
foreach ($t in $targets) {
|
||||
$destPath = Join-Path $destFolder $t.FileName
|
||||
|
||||
if (Test-Path $destPath) {
|
||||
$sizeMB = [math]::Round((Get-Item $destPath).Length / 1MB, 1)
|
||||
Write-Host "[skip] $($t.FileName) already exists ($sizeMB MB)" -ForegroundColor DarkGray
|
||||
continue
|
||||
}
|
||||
|
||||
$artifact = $artifacts | Where-Object { $_.name -eq $t.Artifact }
|
||||
if (-not $artifact) {
|
||||
Write-Error "Artifact '$($t.Artifact)' not found in build $BuildId. Available: $(($artifacts | ForEach-Object name) -join ', ')"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$fileUrl = Get-ArtifactDownloadUrl -BaseUrl $artifact.resource.downloadUrl -SubPath "/$($t.FileName)" -Format file
|
||||
|
||||
Write-Host "Downloading $($t.FileName) ..." -ForegroundColor Cyan
|
||||
try {
|
||||
Invoke-AdoDownload -Url $fileUrl -DestPath $destPath -Token $token
|
||||
}
|
||||
catch {
|
||||
Write-Error "Download failed for $($t.FileName): $_"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$sizeMB = [math]::Round((Get-Item $destPath).Length / 1MB, 1)
|
||||
Write-Host " Saved ($sizeMB MB)" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# --- Step 6b: Download symbols (one zip per arch) ---
|
||||
$symbolTargets = @(
|
||||
[pscustomobject]@{ Arch = "x64"; Artifact = "build-x64-Release"; SubPath = "/symbols-x64" }
|
||||
[pscustomobject]@{ Arch = "arm64"; Artifact = "build-arm64-Release"; SubPath = "/symbols-arm64" }
|
||||
)
|
||||
|
||||
foreach ($s in $symbolTargets) {
|
||||
$finalZip = Join-Path $destFolder "symbols-$($s.Arch).zip"
|
||||
if (Test-Path $finalZip) {
|
||||
$sizeMB = [math]::Round((Get-Item $finalZip).Length / 1MB, 1)
|
||||
Write-Host "[skip] symbols-$($s.Arch).zip already exists ($sizeMB MB)" -ForegroundColor DarkGray
|
||||
continue
|
||||
}
|
||||
|
||||
$artifact = $artifacts | Where-Object { $_.name -eq $s.Artifact }
|
||||
if (-not $artifact) {
|
||||
Write-Error "Artifact '$($s.Artifact)' not found in build $BuildId."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Symbols are downloaded as a folder => keep format=zip and append subPath
|
||||
$symbolsUrl = Get-ArtifactDownloadUrl -BaseUrl $artifact.resource.downloadUrl -SubPath $s.SubPath -Format zip
|
||||
|
||||
$tmpZip = Join-Path ([System.IO.Path]::GetTempPath()) ("ptsym-$($s.Arch)-$([Guid]::NewGuid().ToString('N')).zip")
|
||||
$tmpExtract = Join-Path ([System.IO.Path]::GetTempPath()) ("ptsym-$($s.Arch)-$([Guid]::NewGuid().ToString('N'))")
|
||||
$stageRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("ptsym-stage-$([Guid]::NewGuid().ToString('N'))")
|
||||
|
||||
try {
|
||||
Write-Host "Downloading symbols-$($s.Arch).zip ..." -ForegroundColor Cyan
|
||||
try {
|
||||
Invoke-AdoDownload -Url $symbolsUrl -DestPath $tmpZip -Token $token
|
||||
}
|
||||
catch {
|
||||
Write-Error "Symbols download failed for $($s.Arch): $_"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host " Extracting..." -ForegroundColor DarkGray
|
||||
Expand-Archive -Path $tmpZip -DestinationPath $tmpExtract -Force
|
||||
|
||||
# Walk down while the current dir holds exactly one subfolder and no files.
|
||||
$current = Get-Item $tmpExtract
|
||||
while ($true) {
|
||||
$children = Get-ChildItem -LiteralPath $current.FullName -Force
|
||||
$subDirs = @($children | Where-Object { $_.PSIsContainer })
|
||||
$files = @($children | Where-Object { -not $_.PSIsContainer })
|
||||
if ($subDirs.Count -eq 1 -and $files.Count -eq 0) {
|
||||
$current = $subDirs[0]
|
||||
}
|
||||
else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# Stage to a folder named symbols-<arch> so the zip extracts to that name.
|
||||
$stageInner = Join-Path $stageRoot "symbols-$($s.Arch)"
|
||||
New-Item -ItemType Directory -Path $stageInner -Force | Out-Null
|
||||
Get-ChildItem -LiteralPath $current.FullName -Force | ForEach-Object {
|
||||
Copy-Item -LiteralPath $_.FullName -Destination $stageInner -Recurse -Force
|
||||
}
|
||||
|
||||
Write-Host " Repacking to $finalZip ..." -ForegroundColor DarkGray
|
||||
if (Test-Path $finalZip) { Remove-Item $finalZip -Force }
|
||||
Compress-Archive -Path "$stageInner\*" -DestinationPath $finalZip -CompressionLevel Optimal
|
||||
|
||||
$sizeMB = [math]::Round((Get-Item $finalZip).Length / 1MB, 1)
|
||||
Write-Host " Saved symbols-$($s.Arch).zip ($sizeMB MB)" -ForegroundColor Green
|
||||
}
|
||||
catch {
|
||||
# Don't leave a half-built zip behind if anything in the pipeline blew up.
|
||||
if (Test-Path $finalZip) { Remove-Item $finalZip -Force -ErrorAction SilentlyContinue }
|
||||
throw
|
||||
}
|
||||
finally {
|
||||
Remove-Item $tmpZip -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item $tmpExtract -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item $stageRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
# --- Step 7: Compute SHA256 and build markdown ---
|
||||
Write-Host "`nComputing SHA256 hashes..." -ForegroundColor Cyan
|
||||
|
||||
$sb = [System.Text.StringBuilder]::new()
|
||||
[void]$sb.AppendLine("## Installer Hashes")
|
||||
[void]$sb.AppendLine("")
|
||||
[void]$sb.AppendLine("| Description | Filename | sha256 hash |")
|
||||
[void]$sb.AppendLine("| --- | --- | --- |")
|
||||
|
||||
foreach ($t in $targets) {
|
||||
$destPath = Join-Path $destFolder $t.FileName
|
||||
$hash = (Get-FileHash -Path $destPath -Algorithm SHA256).Hash.ToUpper()
|
||||
[void]$sb.AppendLine("| $($t.Description) | $($t.FileName) | $hash |")
|
||||
Write-Host " $($t.FileName) $hash" -ForegroundColor DarkGray
|
||||
}
|
||||
|
||||
$markdown = $sb.ToString()
|
||||
$mdPath = Join-Path $destFolder "hashes.md"
|
||||
Set-Content -Path $mdPath -Value $markdown -Encoding UTF8
|
||||
|
||||
Write-Host "`nMarkdown written to: $mdPath" -ForegroundColor Green
|
||||
Write-Host "`n----- Installer Hashes -----`n" -ForegroundColor Yellow
|
||||
Write-Host $markdown
|
||||
|
||||
Write-Host "Draft a new GitHub release at: https://github.com/$GitHubRepo/releases/new?tag=v$versionParam" -ForegroundColor Green
|
||||
21
.github/skills/submit-pr/LICENSE.txt
vendored
Normal file
21
.github/skills/submit-pr/LICENSE.txt
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
126
.github/skills/submit-pr/SKILL.md
vendored
Normal file
126
.github/skills/submit-pr/SKILL.md
vendored
Normal file
@@ -0,0 +1,126 @@
|
||||
---
|
||||
name: submit-pr
|
||||
description: Commit changes and create pull requests for fixed issues. Use when asked to create a PR, submit changes, commit fixes, push changes for an issue, create pull request from worktree, or finalize issue fix. Generates AI-assisted commit messages and PR descriptions following PowerToys conventions.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# Submit PR Skill
|
||||
|
||||
Commit changes from issue worktrees and create pull requests with AI-generated titles and descriptions following PowerToys conventions.
|
||||
|
||||
## Skill Contents
|
||||
|
||||
This skill is **self-contained** with all required resources:
|
||||
|
||||
```
|
||||
.github/skills/submit-pr/
|
||||
├── SKILL.md # This file
|
||||
├── LICENSE.txt # MIT License
|
||||
├── scripts/
|
||||
│ └── Submit-IssueFixes.ps1 # Main submit script
|
||||
└── references/
|
||||
├── create-commit-title.prompt.md # Commit title rules
|
||||
└── create-pr-summary.prompt.md # PR description template
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
PRs are created on GitHub with:
|
||||
- Conventional commit title (e.g., `fix(fancyzones): resolve editor crash on multi-monitor`)
|
||||
- Description following `.github/pull_request_template.md`
|
||||
- Auto-linked to the original issue via `Fixes #{{IssueNumber}}`
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Create a PR for a fixed issue
|
||||
- Commit and push changes from a worktree
|
||||
- Submit changes after using `issue-fix` skill
|
||||
- Generate PR title and description
|
||||
- Finalize an issue fix with a pull request
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- GitHub CLI (`gh`) installed and authenticated
|
||||
- Changes made in an issue worktree (from `issue-fix` skill)
|
||||
- PowerShell 7+ for running scripts
|
||||
|
||||
## Required Variables
|
||||
|
||||
| Variable | Description | Example |
|
||||
|----------|-------------|---------|
|
||||
| `{{IssueNumber}}` | Issue number(s) to submit | `44044` or `44044, 32950` |
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Verify Changes Exist
|
||||
|
||||
Check that the worktree has uncommitted or unpushed changes:
|
||||
|
||||
```powershell
|
||||
# List issue worktrees
|
||||
git worktree list | Select-String "issue/"
|
||||
|
||||
# Check status in a worktree
|
||||
cd Q:/PowerToys-xxxx
|
||||
git status
|
||||
```
|
||||
|
||||
### Step 2: Submit PR
|
||||
|
||||
Execute the submit script (use paths relative to this skill folder):
|
||||
|
||||
```powershell
|
||||
# From repo root
|
||||
.github/skills/submit-pr/scripts/Submit-IssueFixes.ps1 -IssueNumbers {{IssueNumber}} -CLIType copilot
|
||||
```
|
||||
|
||||
This will:
|
||||
1. Generate a commit title using AI (following conventional commits)
|
||||
2. Stage and commit all changes
|
||||
3. Push the branch to origin
|
||||
4. Generate a PR description using AI
|
||||
5. Create the PR on GitHub
|
||||
|
||||
### Step 3: Review Created PR
|
||||
|
||||
The script outputs the PR URL. Review it on GitHub.
|
||||
|
||||
## CLI Options
|
||||
|
||||
| Parameter | Description | Default |
|
||||
|-----------|-------------|---------|
|
||||
| `-IssueNumbers` | Issue number(s) to submit | All worktrees |
|
||||
| `-CLIType` | AI CLI to use: `copilot`, `claude`, or `manual` | `copilot` |
|
||||
| `-TargetBranch` | Base branch for PR | `main` |
|
||||
| `-Draft` | Create as draft PR | `false` |
|
||||
| `-Force` | Skip confirmation prompts | `false` |
|
||||
| `-DryRun` | Show what would be done | `false` |
|
||||
|
||||
## PR Title Format
|
||||
|
||||
Titles follow conventional commits (see `references/create-commit-title.prompt.md`):
|
||||
|
||||
```
|
||||
<type>(<scope>): <description>
|
||||
```
|
||||
|
||||
| Type | When to use |
|
||||
|------|-------------|
|
||||
| `fix` | Bug fixes |
|
||||
| `feat` | New features |
|
||||
| `docs` | Documentation only |
|
||||
| `refactor` | Code restructuring |
|
||||
|
||||
## AI Prompt References
|
||||
|
||||
For manual AI invocation, prompts are at:
|
||||
- `references/create-commit-title.prompt.md` - Commit title generation
|
||||
- `references/create-pr-summary.prompt.md` - PR description generation
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Solution |
|
||||
|---------|----------|
|
||||
| No changes to commit | Verify fix was applied, check `git status` |
|
||||
| PR already exists | Script will skip and report existing PR URL |
|
||||
| Push rejected | Pull latest changes or force push with `--force-with-lease` |
|
||||
49
.github/skills/submit-pr/references/create-commit-title.prompt.md
vendored
Normal file
49
.github/skills/submit-pr/references/create-commit-title.prompt.md
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
---
|
||||
agent: 'agent'
|
||||
description: 'Generate an 80-character git commit title for the local diff'
|
||||
---
|
||||
|
||||
# Generate Commit Title
|
||||
|
||||
## Purpose
|
||||
Provide a single-line, ready-to-paste git commit title (<= 80 characters) that reflects the most important local changes since `HEAD`.
|
||||
|
||||
## Input to collect
|
||||
- Run exactly one command to view the local diff:
|
||||
```@terminal
|
||||
git diff HEAD
|
||||
```
|
||||
|
||||
## How to decide the title
|
||||
1. From the diff, find the dominant area (e.g., `src/modules/*`, `doc/devdocs/**`) and the change type (bug fix, docs update, config tweak).
|
||||
2. Draft an imperative, plain-ASCII title that:
|
||||
- Mentions the primary component when obvious (e.g., `FancyZones:` or `Docs:`)
|
||||
- Stays within 80 characters and has no trailing punctuation
|
||||
|
||||
## Final output
|
||||
- Reply with only the commit title on a single line—no extra text.
|
||||
|
||||
## PR title convention (when asked)
|
||||
Use Conventional Commits style:
|
||||
|
||||
`<type>(<scope>): <summary>`
|
||||
|
||||
**Allowed types**
|
||||
- feat, fix, docs, refactor, perf, test, build, ci, chore
|
||||
|
||||
**Scope rules**
|
||||
- Use a short, PowerToys-focused scope (one word preferred). Common scopes:
|
||||
- Core: `runner`, `settings-ui`, `common`, `docs`, `build`, `ci`, `installer`, `gpo`, `dsc`
|
||||
- Modules: `fancyzones`, `powerrename`, `awake`, `colorpicker`, `imageresizer`, `keyboardmanager`, `mouseutils`, `peek`, `hosts`, `file-locksmith`, `screen-ruler`, `text-extractor`, `cropandlock`, `paste`, `powerlauncher`
|
||||
- If unclear, pick the closest module or subsystem; omit only if unavoidable
|
||||
|
||||
**Summary rules**
|
||||
- Imperative, present tense (“add”, “update”, “remove”, “fix”)
|
||||
- Keep it <= 72 characters when possible; be specific, avoid “misc changes”
|
||||
|
||||
**Examples**
|
||||
- `feat(fancyzones): add canvas template duplication`
|
||||
- `fix(mouseutils): guard crosshair toggle when dpi info missing`
|
||||
- `docs(runner): document tray icon states`
|
||||
- `build(installer): align wix v5 suffix flag`
|
||||
- `ci(ci): cache pipeline artifacts for x64`
|
||||
24
.github/skills/submit-pr/references/create-pr-summary.prompt.md
vendored
Normal file
24
.github/skills/submit-pr/references/create-pr-summary.prompt.md
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
---
|
||||
agent: 'agent'
|
||||
description: 'Generate a PowerToys-ready pull request description from the local diff'
|
||||
---
|
||||
|
||||
# Generate PR Summary
|
||||
|
||||
**Goal:** Produce a ready-to-paste PR title and description that follows PowerToys conventions by comparing the current branch against a user-selected target branch.
|
||||
|
||||
**Repo guardrails:**
|
||||
- Treat `.github/pull_request_template.md` as the single source of truth; load it at runtime instead of embedding hardcoded content in this prompt.
|
||||
- Preserve section order from the template but only surface checklist lines that are relevant for the detected changes, filling them with `[x]`/`[ ]` as appropriate.
|
||||
- Cite touched paths with inline backticks, matching the guidance in `.github/copilot-instructions.md`.
|
||||
- Call out test coverage explicitly: list automated tests run (unit/UI) or state why they are not applicable.
|
||||
|
||||
**Workflow:**
|
||||
1. Determine the target branch from user context; default to `main` when no branch is supplied.
|
||||
2. Run `git status --short` once to surface uncommitted files that may influence the summary.
|
||||
3. Run `git diff <target-branch>...HEAD` a single time to review the detailed changes. Only when confidence stays low dig deeper with focused calls such as `git diff <target-branch>...HEAD -- <path>`.
|
||||
4. From the diff, capture impacted areas, key file changes, behavioral risks, migrations, and noteworthy edge cases.
|
||||
5. Confirm validation: list tests executed with results or state why tests were skipped in line with repo guidance.
|
||||
6. Load `.github/pull_request_template.md`, mirror its section order, and populate it with the gathered facts. Include only relevant checklist entries, marking them `[x]/[ ]` and noting any intentional omissions as "N/A".
|
||||
7. Present the filled template inside a fenced ```markdown code block with no extra commentary so it is ready to paste into a PR, clearly flagging any placeholders that still need user input.
|
||||
8. Prepend the PR title above the filled template, applying the Conventional Commit type/scope rules from `.github/prompts/create-commit-title.prompt.md`; pick the dominant component from the diff and keep the title concise and imperative.
|
||||
9
.github/skills/submit-pr/references/mcp-config.json
vendored
Normal file
9
.github/skills/submit-pr/references/mcp-config.json
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"github-artifacts": {
|
||||
"command": "cmd",
|
||||
"args": ["/c", "for /f %i in ('git rev-parse --show-toplevel') do node %i/tools/mcp/github-artifacts/launch.js"],
|
||||
"tools": ["*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
18
.github/skills/submit-pr/scripts/IssueReviewLib.ps1
vendored
Normal file
18
.github/skills/submit-pr/scripts/IssueReviewLib.ps1
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
# IssueReviewLib.ps1 - Minimal helpers for PR submission workflow
|
||||
# Part of the PowerToys GitHub Copilot/Claude Code issue review system
|
||||
# This is a trimmed version - submit-pr only needs console helpers and repo root
|
||||
|
||||
#region Console Output Helpers
|
||||
function Info { param([string]$Message) Write-Host $Message -ForegroundColor Cyan }
|
||||
function Warn { param([string]$Message) Write-Host $Message -ForegroundColor Yellow }
|
||||
function Err { param([string]$Message) Write-Host $Message -ForegroundColor Red }
|
||||
function Success { param([string]$Message) Write-Host $Message -ForegroundColor Green }
|
||||
#endregion
|
||||
|
||||
#region Repository Helpers
|
||||
function Get-RepoRoot {
|
||||
$root = git rev-parse --show-toplevel 2>$null
|
||||
if (-not $root) { throw 'Not inside a git repository.' }
|
||||
return (Resolve-Path $root).Path
|
||||
}
|
||||
#endregion
|
||||
559
.github/skills/submit-pr/scripts/Submit-IssueFixes.ps1
vendored
Normal file
559
.github/skills/submit-pr/scripts/Submit-IssueFixes.ps1
vendored
Normal file
@@ -0,0 +1,559 @@
|
||||
<#!
|
||||
.SYNOPSIS
|
||||
Commit and create PRs for completed issue fixes in worktrees.
|
||||
|
||||
.DESCRIPTION
|
||||
For each specified issue (or all issue worktrees), commits changes using AI-generated
|
||||
commit messages and creates PRs with AI-generated summaries, linking to the original issue.
|
||||
|
||||
.PARAMETER IssueNumbers
|
||||
Array of issue numbers to submit. If not specified, processes all issue/* worktrees.
|
||||
|
||||
.PARAMETER DryRun
|
||||
Show what would be done without actually committing or creating PRs.
|
||||
|
||||
.PARAMETER SkipCommit
|
||||
Skip the commit step (assume changes are already committed).
|
||||
|
||||
.PARAMETER SkipPush
|
||||
Skip pushing to remote (useful for testing).
|
||||
|
||||
.PARAMETER TargetBranch
|
||||
Target branch for the PR. Default: main.
|
||||
|
||||
.PARAMETER CLIType
|
||||
AI CLI to use for generating messages: copilot, claude, or manual. Default: copilot.
|
||||
|
||||
.PARAMETER Draft
|
||||
Create PRs as drafts.
|
||||
|
||||
.EXAMPLE
|
||||
# Submit all issue worktrees
|
||||
./Submit-IssueFixes.ps1
|
||||
|
||||
.EXAMPLE
|
||||
# Submit specific issues
|
||||
./Submit-IssueFixes.ps1 -IssueNumbers 44044, 44480
|
||||
|
||||
.EXAMPLE
|
||||
# Dry run to see what would happen
|
||||
./Submit-IssueFixes.ps1 -DryRun
|
||||
|
||||
.EXAMPLE
|
||||
# Create draft PRs
|
||||
./Submit-IssueFixes.ps1 -Draft
|
||||
|
||||
.NOTES
|
||||
Prerequisites:
|
||||
- Worktrees created by Start-IssueAutoFix.ps1
|
||||
- Changes made in the worktrees
|
||||
- GitHub CLI (gh) authenticated
|
||||
- Copilot CLI or Claude Code CLI
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[int[]]$IssueNumbers,
|
||||
|
||||
[switch]$DryRun,
|
||||
|
||||
[switch]$SkipCommit,
|
||||
|
||||
[switch]$SkipPush,
|
||||
|
||||
[string]$TargetBranch = 'main',
|
||||
|
||||
[ValidateSet('copilot', 'claude', 'manual')]
|
||||
[string]$CLIType = 'copilot',
|
||||
|
||||
[switch]$Draft,
|
||||
|
||||
[switch]$Force,
|
||||
|
||||
[switch]$Help
|
||||
)
|
||||
|
||||
# Load libraries
|
||||
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
. "$scriptDir/IssueReviewLib.ps1"
|
||||
|
||||
# Load worktree library
|
||||
$repoRoot = Get-RepoRoot
|
||||
$worktreeLib = Join-Path $repoRoot 'tools/build/WorktreeLib.ps1'
|
||||
if (Test-Path $worktreeLib) {
|
||||
. $worktreeLib
|
||||
}
|
||||
|
||||
if ($Help) {
|
||||
Get-Help $MyInvocation.MyCommand.Path -Full
|
||||
return
|
||||
}
|
||||
|
||||
function Get-AIGeneratedCommitTitle {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Generate commit title using AI CLI with create-commit-title prompt.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$WorktreePath,
|
||||
[string]$CLIType = 'copilot'
|
||||
)
|
||||
|
||||
$promptFile = Join-Path $repoRoot '.github/prompts/create-commit-title.prompt.md'
|
||||
if (-not (Test-Path $promptFile)) {
|
||||
throw "Prompt file not found: $promptFile"
|
||||
}
|
||||
|
||||
$prompt = "Follow the instructions in .github/prompts/create-commit-title.prompt.md to generate a commit title for the current changes. Output ONLY the commit title, nothing else."
|
||||
|
||||
# MCP config for github-artifacts tools (relative to repo root)
|
||||
$mcpConfig = '@.github/skills/submit-pr/references/mcp-config.json'
|
||||
|
||||
Push-Location $WorktreePath
|
||||
try {
|
||||
switch ($CLIType) {
|
||||
'copilot' {
|
||||
$result = & copilot --additional-mcp-config $mcpConfig -p $prompt --yolo -s 2>&1
|
||||
# Extract just the title line (last non-empty line that looks like a title)
|
||||
$lines = $result -split "`n" | Where-Object { $_.Trim() -and $_ -notmatch '^\s*```' -and $_ -notmatch '^\s*#' }
|
||||
$title = $lines | Select-Object -Last 1
|
||||
return $title.Trim()
|
||||
}
|
||||
'claude' {
|
||||
$result = & claude --print --dangerously-skip-permissions --prompt $prompt 2>&1
|
||||
$lines = $result -split "`n" | Where-Object { $_.Trim() -and $_ -notmatch '^\s*```' }
|
||||
$title = $lines | Select-Object -Last 1
|
||||
return $title.Trim()
|
||||
}
|
||||
'manual' {
|
||||
# Show diff and ask user for title
|
||||
git diff HEAD --stat
|
||||
return Read-Host "Enter commit title"
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
function Get-AIGeneratedPRSummary {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Generate PR summary using AI CLI with create-pr-summary prompt.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$WorktreePath,
|
||||
[Parameter(Mandatory)]
|
||||
[int]$IssueNumber,
|
||||
[string]$TargetBranch = 'main',
|
||||
[string]$CLIType = 'copilot'
|
||||
)
|
||||
|
||||
$prompt = @"
|
||||
Follow the instructions in .github/prompts/create-pr-summary.prompt.md to generate a PR summary.
|
||||
Target branch: $TargetBranch
|
||||
This PR fixes issue #$IssueNumber.
|
||||
|
||||
IMPORTANT:
|
||||
1. Output the PR title on the first line
|
||||
2. Then output the PR body in markdown format
|
||||
3. Make sure to include "Fixes #$IssueNumber" in the body to auto-link the issue
|
||||
"@
|
||||
|
||||
# MCP config for github-artifacts tools (relative to repo root)
|
||||
$mcpConfig = '@.github/skills/submit-pr/references/mcp-config.json'
|
||||
|
||||
Push-Location $WorktreePath
|
||||
try {
|
||||
switch ($CLIType) {
|
||||
'copilot' {
|
||||
$result = & copilot --additional-mcp-config $mcpConfig -p $prompt --yolo -s 2>&1
|
||||
return $result -join "`n"
|
||||
}
|
||||
'claude' {
|
||||
$result = & claude --print --dangerously-skip-permissions --prompt $prompt 2>&1
|
||||
return $result -join "`n"
|
||||
}
|
||||
'manual' {
|
||||
git diff "$TargetBranch...HEAD" --stat
|
||||
$title = Read-Host "Enter PR title"
|
||||
$body = Read-Host "Enter PR body (or press Enter for default)"
|
||||
if (-not $body) {
|
||||
$body = "Fixes #$IssueNumber"
|
||||
}
|
||||
return "$title`n`n$body"
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
function Parse-PRContent {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Parse AI output to extract PR title and body.
|
||||
Expected format:
|
||||
Line 1: feat(scope): title text
|
||||
Line 2+: ```markdown
|
||||
## Summary...
|
||||
```
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Content,
|
||||
[int]$IssueNumber
|
||||
)
|
||||
|
||||
$lines = $Content -split "`n"
|
||||
|
||||
# Title is the FIRST line that looks like a conventional commit
|
||||
# Body is the content INSIDE the ```markdown ... ``` block
|
||||
$title = $null
|
||||
$body = $null
|
||||
|
||||
# Find title - first line matching conventional commit format
|
||||
foreach ($line in $lines) {
|
||||
$trimmed = $line.Trim()
|
||||
if ($trimmed -match '^(feat|fix|docs|refactor|perf|test|build|ci|chore)(\([^)]+\))?:') {
|
||||
$title = $trimmed -replace '^#+\s*', ''
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# Fallback title
|
||||
if (-not $title) {
|
||||
$title = "fix: address issue #$IssueNumber"
|
||||
}
|
||||
|
||||
# Extract body from markdown code block
|
||||
$fullContent = $Content
|
||||
if ($fullContent -match '```markdown\r?\n([\s\S]*?)\r?\n```') {
|
||||
$body = $Matches[1].Trim()
|
||||
} else {
|
||||
# No markdown block - use everything after the title line
|
||||
$titleIndex = [array]::IndexOf($lines, ($lines | Where-Object { $_.Trim() -eq $title } | Select-Object -First 1))
|
||||
if ($titleIndex -ge 0 -and $titleIndex -lt $lines.Count - 1) {
|
||||
$body = ($lines[($titleIndex + 1)..($lines.Count - 1)] -join "`n").Trim()
|
||||
# Clean up any remaining code fences
|
||||
$body = $body -replace '^```\w*\r?\n', '' -replace '\r?\n```\s*$', ''
|
||||
} else {
|
||||
$body = ""
|
||||
}
|
||||
}
|
||||
|
||||
# Ensure issue link is present
|
||||
if ($body -notmatch "Fixes\s*#$IssueNumber" -and $body -notmatch "Closes\s*#$IssueNumber" -and $body -notmatch "Resolves\s*#$IssueNumber") {
|
||||
$body = "$body`n`nFixes #$IssueNumber"
|
||||
}
|
||||
|
||||
return @{
|
||||
Title = $title
|
||||
Body = $body
|
||||
}
|
||||
}
|
||||
|
||||
function Submit-IssueFix {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Commit changes, push, and create PR for a single issue.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[int]$IssueNumber,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$WorktreePath,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Branch,
|
||||
[string]$TargetBranch = 'main',
|
||||
[string]$CLIType = 'copilot',
|
||||
[switch]$DryRun,
|
||||
[switch]$SkipCommit,
|
||||
[switch]$SkipPush,
|
||||
[switch]$Draft
|
||||
)
|
||||
|
||||
Push-Location $WorktreePath
|
||||
try {
|
||||
# Check for changes
|
||||
$status = git status --porcelain
|
||||
$hasUncommitted = $status.Count -gt 0
|
||||
|
||||
# Check for commits ahead of target
|
||||
git fetch origin $TargetBranch 2>$null
|
||||
$commitsAhead = git rev-list --count "origin/$TargetBranch..$Branch" 2>$null
|
||||
if (-not $commitsAhead) { $commitsAhead = 0 }
|
||||
|
||||
Info "Issue #$IssueNumber in $WorktreePath"
|
||||
Info " Branch: $Branch"
|
||||
Info " Uncommitted changes: $hasUncommitted"
|
||||
Info " Commits ahead of $TargetBranch`: $commitsAhead"
|
||||
|
||||
if (-not $hasUncommitted -and $commitsAhead -eq 0) {
|
||||
Warn " No changes to submit for issue #$IssueNumber"
|
||||
return @{ IssueNumber = $IssueNumber; Status = 'NoChanges' }
|
||||
}
|
||||
|
||||
# Step 1: Commit if there are uncommitted changes
|
||||
if ($hasUncommitted -and -not $SkipCommit) {
|
||||
Info " Generating commit title..."
|
||||
|
||||
if ($DryRun) {
|
||||
Info " [DRY RUN] Would generate commit title and commit changes"
|
||||
} else {
|
||||
$commitTitle = Get-AIGeneratedCommitTitle -WorktreePath $WorktreePath -CLIType $CLIType
|
||||
|
||||
if (-not $commitTitle) {
|
||||
throw "Failed to generate commit title"
|
||||
}
|
||||
|
||||
Info " Commit title: $commitTitle"
|
||||
|
||||
# Stage all changes and commit
|
||||
git add -A
|
||||
git commit -m $commitTitle
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Git commit failed"
|
||||
}
|
||||
|
||||
Success " ✓ Changes committed"
|
||||
}
|
||||
}
|
||||
|
||||
# Step 2: Push to remote
|
||||
if (-not $SkipPush) {
|
||||
if ($DryRun) {
|
||||
Info " [DRY RUN] Would push branch $Branch to origin"
|
||||
} else {
|
||||
Info " Pushing to origin..."
|
||||
git push -u origin $Branch 2>&1 | Out-Null
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
# Try force push if normal push fails (branch might have been reset)
|
||||
Warn " Normal push failed, trying force push..."
|
||||
git push -u origin $Branch --force-with-lease 2>&1 | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Git push failed"
|
||||
}
|
||||
}
|
||||
|
||||
Success " ✓ Pushed to origin"
|
||||
}
|
||||
}
|
||||
|
||||
# Step 3: Create PR
|
||||
Info " Generating PR summary..."
|
||||
|
||||
if ($DryRun) {
|
||||
Info " [DRY RUN] Would generate PR summary and create PR"
|
||||
Info " [DRY RUN] PR would link to issue #$IssueNumber"
|
||||
return @{ IssueNumber = $IssueNumber; Status = 'DryRun' }
|
||||
}
|
||||
|
||||
# Check if PR already exists
|
||||
$existingPR = gh pr list --head $Branch --json number,url 2>$null | ConvertFrom-Json
|
||||
if ($existingPR -and $existingPR.Count -gt 0) {
|
||||
Warn " PR already exists: $($existingPR[0].url)"
|
||||
return @{ IssueNumber = $IssueNumber; Status = 'PRExists'; PRUrl = $existingPR[0].url }
|
||||
}
|
||||
|
||||
$prContent = Get-AIGeneratedPRSummary -WorktreePath $WorktreePath -IssueNumber $IssueNumber -TargetBranch $TargetBranch -CLIType $CLIType
|
||||
$parsed = Parse-PRContent -Content $prContent -IssueNumber $IssueNumber
|
||||
|
||||
if (-not $parsed.Title) {
|
||||
throw "Failed to generate PR title"
|
||||
}
|
||||
|
||||
Info " PR Title: $($parsed.Title)"
|
||||
|
||||
# Create PR using gh CLI
|
||||
$ghArgs = @(
|
||||
'pr', 'create',
|
||||
'--base', $TargetBranch,
|
||||
'--head', $Branch,
|
||||
'--title', $parsed.Title,
|
||||
'--body', $parsed.Body
|
||||
)
|
||||
|
||||
if ($Draft) {
|
||||
$ghArgs += '--draft'
|
||||
}
|
||||
|
||||
$prResult = & gh @ghArgs 2>&1
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Failed to create PR: $prResult"
|
||||
}
|
||||
|
||||
# Extract PR URL from result
|
||||
$prUrl = $prResult | Select-String -Pattern 'https://github.com/[^\s]+' | ForEach-Object { $_.Matches[0].Value }
|
||||
|
||||
Success " ✓ PR created: $prUrl"
|
||||
|
||||
return @{
|
||||
IssueNumber = $IssueNumber
|
||||
Status = 'Success'
|
||||
PRUrl = $prUrl
|
||||
CommitTitle = $commitTitle
|
||||
PRTitle = $parsed.Title
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Err " ✗ Failed: $($_.Exception.Message)"
|
||||
return @{
|
||||
IssueNumber = $IssueNumber
|
||||
Status = 'Failed'
|
||||
Error = $_.Exception.Message
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
#region Main Script
|
||||
try {
|
||||
Info "Repository root: $repoRoot"
|
||||
Info "Target branch: $TargetBranch"
|
||||
Info "CLI type: $CLIType"
|
||||
|
||||
# Get all issue worktrees
|
||||
$allWorktrees = Get-WorktreeEntries | Where-Object { $_.Branch -like 'issue/*' }
|
||||
|
||||
if ($allWorktrees.Count -eq 0) {
|
||||
Warn "No issue worktrees found. Run Start-IssueAutoFix.ps1 first."
|
||||
return
|
||||
}
|
||||
|
||||
# Filter to specified issues if provided
|
||||
$worktreesToProcess = @()
|
||||
|
||||
if ($IssueNumbers -and $IssueNumbers.Count -gt 0) {
|
||||
foreach ($issueNum in $IssueNumbers) {
|
||||
$wt = $allWorktrees | Where-Object { $_.Branch -match "issue/$issueNum\b" }
|
||||
if ($wt) {
|
||||
$worktreesToProcess += $wt
|
||||
} else {
|
||||
Warn "No worktree found for issue #$issueNum"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$worktreesToProcess = $allWorktrees
|
||||
}
|
||||
|
||||
if ($worktreesToProcess.Count -eq 0) {
|
||||
Warn "No worktrees to process."
|
||||
return
|
||||
}
|
||||
|
||||
# Display worktrees to process
|
||||
Info "`nWorktrees to submit:"
|
||||
Info ("-" * 80)
|
||||
foreach ($wt in $worktreesToProcess) {
|
||||
# Extract issue number from branch name
|
||||
if ($wt.Branch -match 'issue/(\d+)') {
|
||||
$issueNum = $Matches[1]
|
||||
Info " #$issueNum -> $($wt.Path) [$($wt.Branch)]"
|
||||
}
|
||||
}
|
||||
Info ("-" * 80)
|
||||
|
||||
if ($DryRun) {
|
||||
Warn "`nDry run mode - no changes will be made."
|
||||
}
|
||||
|
||||
# Confirm before proceeding
|
||||
if (-not $Force -and -not $DryRun) {
|
||||
$confirm = Read-Host "`nProceed with submitting $($worktreesToProcess.Count) fixes? (y/N)"
|
||||
if ($confirm -notmatch '^[yY]') {
|
||||
Info "Cancelled."
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
# Process each worktree
|
||||
$results = @{
|
||||
Success = @()
|
||||
Failed = @()
|
||||
NoChanges = @()
|
||||
PRExists = @()
|
||||
DryRun = @()
|
||||
}
|
||||
|
||||
foreach ($wt in $worktreesToProcess) {
|
||||
if ($wt.Branch -match 'issue/(\d+)') {
|
||||
$issueNum = [int]$Matches[1]
|
||||
|
||||
Info "`n" + ("=" * 60)
|
||||
Info "SUBMITTING ISSUE #$issueNum"
|
||||
Info ("=" * 60)
|
||||
|
||||
$result = Submit-IssueFix `
|
||||
-IssueNumber $issueNum `
|
||||
-WorktreePath $wt.Path `
|
||||
-Branch $wt.Branch `
|
||||
-TargetBranch $TargetBranch `
|
||||
-CLIType $CLIType `
|
||||
-DryRun:$DryRun `
|
||||
-SkipCommit:$SkipCommit `
|
||||
-SkipPush:$SkipPush `
|
||||
-Draft:$Draft
|
||||
|
||||
switch ($result.Status) {
|
||||
'Success' { $results.Success += $result }
|
||||
'Failed' { $results.Failed += $result }
|
||||
'NoChanges' { $results.NoChanges += $result }
|
||||
'PRExists' { $results.PRExists += $result }
|
||||
'DryRun' { $results.DryRun += $result }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Summary
|
||||
Info "`n" + ("=" * 80)
|
||||
Info "SUBMISSION COMPLETE"
|
||||
Info ("=" * 80)
|
||||
Info "Total worktrees: $($worktreesToProcess.Count)"
|
||||
|
||||
if ($results.Success.Count -gt 0) {
|
||||
Success "PRs created: $($results.Success.Count)"
|
||||
foreach ($r in $results.Success) {
|
||||
Success " #$($r.IssueNumber): $($r.PRUrl)"
|
||||
}
|
||||
}
|
||||
|
||||
if ($results.PRExists.Count -gt 0) {
|
||||
Warn "PRs already exist: $($results.PRExists.Count)"
|
||||
foreach ($r in $results.PRExists) {
|
||||
Warn " #$($r.IssueNumber): $($r.PRUrl)"
|
||||
}
|
||||
}
|
||||
|
||||
if ($results.NoChanges.Count -gt 0) {
|
||||
Warn "No changes: $($results.NoChanges.Count)"
|
||||
Warn " Issues: $($results.NoChanges.IssueNumber -join ', ')"
|
||||
}
|
||||
|
||||
if ($results.Failed.Count -gt 0) {
|
||||
Err "Failed: $($results.Failed.Count)"
|
||||
foreach ($r in $results.Failed) {
|
||||
Err " #$($r.IssueNumber): $($r.Error)"
|
||||
}
|
||||
}
|
||||
|
||||
if ($results.DryRun.Count -gt 0) {
|
||||
Info "Dry run: $($results.DryRun.Count)"
|
||||
}
|
||||
|
||||
Info ("=" * 80)
|
||||
|
||||
return $results
|
||||
}
|
||||
catch {
|
||||
Err "Error: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
#endregion
|
||||
192
.github/skills/winmd-api-search/SKILL.md
vendored
192
.github/skills/winmd-api-search/SKILL.md
vendored
@@ -1,192 +0,0 @@
|
||||
---
|
||||
name: winmd-api-search
|
||||
description: 'Find and explore Windows desktop APIs. Use when building features that need platform capabilities — camera, file access, notifications, UI controls, AI/ML, sensors, networking, etc. Discovers the right API for a task and retrieves full type details (methods, properties, events, enumeration values).'
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# WinMD API Search
|
||||
|
||||
This skill helps you find the right Windows API for any capability and get its full details. It searches a local cache of all WinMD metadata from:
|
||||
|
||||
- **Windows Platform SDK** — all `Windows.*` WinRT APIs (always available, no restore needed)
|
||||
- **WinAppSDK / WinUI** — bundled as a baseline in the cache generator (always available, no restore needed)
|
||||
- **NuGet packages** — any additional packages in restored projects that contain `.winmd` files
|
||||
- **Project-output WinMD** — class libraries (C++/WinRT, C#) that produce `.winmd` as build output
|
||||
|
||||
Even on a fresh clone with no restore or build, you still get full Platform SDK + WinAppSDK coverage.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- User wants to build a feature and you need to find which API provides that capability
|
||||
- User asks "how do I do X?" where X involves a platform feature (camera, files, notifications, sensors, AI, etc.)
|
||||
- You need the exact methods, properties, events, or enumeration values of a type before writing code
|
||||
- You're unsure which control, class, or interface to use for a UI or system task
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **.NET SDK 8.0 or later** — required to build the cache generator. Install from [dotnet.microsoft.com](https://dotnet.microsoft.com/download) if not available.
|
||||
|
||||
## Cache Setup (Required Before First Use)
|
||||
|
||||
All query and search commands read from a local JSON cache. **You must generate the cache before running any queries.**
|
||||
|
||||
```powershell
|
||||
# All projects in the repo (recommended for first run)
|
||||
.\.github\skills\winmd-api-search\scripts\Update-WinMdCache.ps1
|
||||
|
||||
# Single project
|
||||
.\.github\skills\winmd-api-search\scripts\Update-WinMdCache.ps1 -ProjectDir <project-folder>
|
||||
```
|
||||
|
||||
No project restore or build is needed for baseline coverage (Platform SDK + WinAppSDK). For additional NuGet packages, the project needs `dotnet restore` (which generates `project.assets.json`) or a `packages.config` file.
|
||||
|
||||
Cache is stored at `Generated Files\winmd-cache\`, deduplicated per-package+version.
|
||||
|
||||
### What gets indexed
|
||||
|
||||
| Source | When available |
|
||||
|--------|----------------|
|
||||
| Windows Platform SDK | Always (reads from local SDK install) |
|
||||
| WinAppSDK (latest) | Always (bundled as baseline in cache generator) |
|
||||
| WinAppSDK Runtime | When installed on the system (detected via `Get-AppxPackage`) |
|
||||
| Project NuGet packages | After `dotnet restore` or with `packages.config` |
|
||||
| Project-output `.winmd` | After project build (class libraries that produce WinMD) |
|
||||
|
||||
> **Note:** This cache directory should be in `.gitignore` — it's generated, not source.
|
||||
|
||||
## How to Use
|
||||
|
||||
Pick the path that matches the situation:
|
||||
|
||||
---
|
||||
|
||||
### Discover — "I don't know which API to use"
|
||||
|
||||
The user describes a capability in their own words. You need to find the right API.
|
||||
|
||||
**0. Ensure the cache exists**
|
||||
|
||||
If the cache hasn't been generated yet, run `Update-WinMdCache.ps1` first — see [Cache Setup](#cache-setup-required-before-first-use) above.
|
||||
|
||||
**1. Translate user language → search keywords**
|
||||
|
||||
Map the user's daily language to programming terms. Try multiple variations:
|
||||
|
||||
| User says | Search keywords to try (in order) |
|
||||
|-----------|-----------------------------------|
|
||||
| "take a picture" | `camera`, `capture`, `photo`, `MediaCapture` |
|
||||
| "load from disk" | `file open`, `picker`, `FileOpen`, `StorageFile` |
|
||||
| "describe what's in it" | `image description`, `Vision`, `Recognition` |
|
||||
| "show a popup" | `dialog`, `flyout`, `popup`, `ContentDialog` |
|
||||
| "drag and drop" | `drag`, `drop`, `DragDrop` |
|
||||
| "save settings" | `settings`, `ApplicationData`, `LocalSettings` |
|
||||
|
||||
Start with simple everyday words. If results are weak or irrelevant, try the more technical variation.
|
||||
|
||||
**2. Run searches**
|
||||
|
||||
```powershell
|
||||
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action search -Query "<keyword>"
|
||||
```
|
||||
|
||||
This returns ranked namespaces with top matching types and the **JSON file path**.
|
||||
|
||||
If results have **low scores (below 60) or are irrelevant**, fall back to searching online documentation:
|
||||
|
||||
1. Use web search to find the right API on Microsoft Learn, for example:
|
||||
- `site:learn.microsoft.com/uwp/api <capability keywords>` for `Windows.*` APIs
|
||||
- `site:learn.microsoft.com/windows/windows-app-sdk/api/winrt <capability keywords>` for `Microsoft.*` WinAppSDK APIs
|
||||
2. Read the documentation pages to identify which type matches the user's requirement.
|
||||
3. Once you know the type name, come back and use `-Action members` or `-Action enums` to get the exact local signatures.
|
||||
|
||||
**3. Read the JSON to choose the right API**
|
||||
|
||||
Read the file at the path(s) from the top results. The JSON has all types in that namespace — full members, signatures, parameters, return types, enumeration values.
|
||||
|
||||
Read and decide which types and members fit the user's requirement.
|
||||
|
||||
**4. Look up official documentation for context**
|
||||
|
||||
The cache contains only signatures — no descriptions or usage guidance. For explanations, examples, and remarks, look up the type on Microsoft Learn:
|
||||
|
||||
| Namespace prefix | Documentation base URL |
|
||||
|-----------------|----------------------|
|
||||
| `Windows.*` | `https://learn.microsoft.com/uwp/api/{fully.qualified.typename}` |
|
||||
| `Microsoft.*` (WinAppSDK) | `https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/{fully.qualified.typename}` |
|
||||
|
||||
For example, `Microsoft.UI.Xaml.Controls.NavigationView` maps to:
|
||||
`https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.navigationview`
|
||||
|
||||
**5. Use the API knowledge to answer or write code**
|
||||
|
||||
---
|
||||
|
||||
### Lookup — "I know the API, show me the details"
|
||||
|
||||
You already know (or suspect) the type or namespace name. Go direct:
|
||||
|
||||
```powershell
|
||||
# Get all members of a known type
|
||||
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action members -TypeName "Microsoft.UI.Xaml.Controls.NavigationView"
|
||||
|
||||
# Get enum values
|
||||
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action enums -TypeName "Microsoft.UI.Xaml.Visibility"
|
||||
|
||||
# List all types in a namespace
|
||||
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action types -Namespace "Microsoft.UI.Xaml.Controls"
|
||||
|
||||
# Browse namespaces
|
||||
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action namespaces -Filter "Microsoft.UI"
|
||||
```
|
||||
|
||||
If you need full detail beyond what `-Action members` shows, use `-Action search` to get the JSON file path, then read the JSON file directly.
|
||||
|
||||
---
|
||||
|
||||
### Other Commands
|
||||
|
||||
```powershell
|
||||
# List cached projects
|
||||
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action projects
|
||||
|
||||
# List packages for a project
|
||||
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action packages
|
||||
|
||||
# Show stats
|
||||
.\.github\skills\winmd-api-search\scripts\Invoke-WinMdQuery.ps1 -Action stats
|
||||
```
|
||||
|
||||
> If only one project is cached, `-Project` is auto-selected.
|
||||
> If multiple projects exist, add `-Project <name>` (use `-Action projects` to see available names).
|
||||
> In scan mode, manifest names include a short hash suffix to avoid collisions; you can pass the base project name without the suffix if it's unambiguous.
|
||||
|
||||
## Search Scoring
|
||||
|
||||
The search ranks type names and member names against your query:
|
||||
|
||||
| Score | Match type | Example |
|
||||
|-------|-----------|---------|
|
||||
| 100 | Exact name | `Button` → `Button` |
|
||||
| 80 | Starts with | `Navigation` → `NavigationView` |
|
||||
| 60 | Contains | `Dialog` → `ContentDialog` |
|
||||
| 50 | PascalCase initials | `ASB` → `AutoSuggestBox` |
|
||||
| 40 | Multi-keyword AND | `navigation item` → `NavigationViewItem` |
|
||||
| 20 | Fuzzy character match | `NavVw` → `NavigationView` |
|
||||
|
||||
Results are grouped by namespace. Higher-scored namespaces appear first.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Fix |
|
||||
|-------|-----|
|
||||
| "Cache not found" | Run `Update-WinMdCache.ps1` |
|
||||
| "Multiple projects cached" | Add `-Project <name>` |
|
||||
| "Namespace not found" | Use `-Action namespaces` to list available ones |
|
||||
| "Type not found" | Use fully qualified name (e.g., `Microsoft.UI.Xaml.Controls.Button`) |
|
||||
| Stale after NuGet update | Re-run `Update-WinMdCache.ps1` |
|
||||
| Cache in git history | Add `Generated Files/` to `.gitignore` |
|
||||
|
||||
## References
|
||||
|
||||
- [Windows Platform SDK API reference](https://learn.microsoft.com/uwp/api/) — documentation for `Windows.*` namespaces
|
||||
- [Windows App SDK API reference](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/) — documentation for `Microsoft.*` WinAppSDK namespaces
|
||||
@@ -1,505 +0,0 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Query WinMD API metadata from cached JSON files.
|
||||
|
||||
.DESCRIPTION
|
||||
Reads pre-built JSON cache of WinMD types, members, and namespaces.
|
||||
The cache is organized per-package (deduplicated) with project manifests
|
||||
that map each project to its referenced packages.
|
||||
|
||||
Supports listing namespaces, types, members, searching, enum value lookup,
|
||||
and listing cached projects/packages.
|
||||
|
||||
.PARAMETER Action
|
||||
The query action to perform:
|
||||
- projects : List cached projects
|
||||
- packages : List packages for a project
|
||||
- stats : Show aggregate statistics for a project
|
||||
- namespaces : List all namespaces (optional -Filter prefix)
|
||||
- types : List types in a namespace (-Namespace required)
|
||||
- members : List members of a type (-TypeName required)
|
||||
- search : Search types and members by name (-Query required)
|
||||
- enums : List enum values (-TypeName required)
|
||||
|
||||
.PARAMETER Project
|
||||
Project name to query. Auto-selected if only one project is cached.
|
||||
Use -Action projects to list available projects.
|
||||
|
||||
.PARAMETER Namespace
|
||||
Namespace to query types from (used with -Action types).
|
||||
|
||||
.PARAMETER TypeName
|
||||
Full type name e.g. "Microsoft.UI.Xaml.Controls.Button" (used with -Action members, enums).
|
||||
|
||||
.PARAMETER Query
|
||||
Search query string (used with -Action search).
|
||||
|
||||
.PARAMETER Filter
|
||||
Optional prefix filter for namespaces (used with -Action namespaces).
|
||||
|
||||
.PARAMETER CacheDir
|
||||
Path to the winmd-cache directory. Defaults to "Generated Files\winmd-cache"
|
||||
relative to the workspace root.
|
||||
|
||||
.PARAMETER MaxResults
|
||||
Maximum number of results to return for search. Defaults to 30.
|
||||
|
||||
.EXAMPLE
|
||||
.\Invoke-WinMdQuery.ps1 -Action projects
|
||||
.\Invoke-WinMdQuery.ps1 -Action packages -Project BlankWinUI
|
||||
.\Invoke-WinMdQuery.ps1 -Action stats -Project BlankWinUI
|
||||
.\Invoke-WinMdQuery.ps1 -Action namespaces -Filter "Microsoft.UI"
|
||||
.\Invoke-WinMdQuery.ps1 -Action types -Namespace "Microsoft.UI.Xaml.Controls"
|
||||
.\Invoke-WinMdQuery.ps1 -Action members -TypeName "Microsoft.UI.Xaml.Controls.Button"
|
||||
.\Invoke-WinMdQuery.ps1 -Action search -Query "NavigationView"
|
||||
.\Invoke-WinMdQuery.ps1 -Action enums -TypeName "Microsoft.UI.Xaml.Visibility"
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[ValidateSet('projects', 'packages', 'stats', 'namespaces', 'types', 'members', 'search', 'enums')]
|
||||
[string]$Action,
|
||||
|
||||
[string]$Project,
|
||||
[string]$Namespace,
|
||||
[string]$TypeName,
|
||||
[string]$Query,
|
||||
[string]$Filter,
|
||||
[string]$CacheDir,
|
||||
[int]$MaxResults = 30
|
||||
)
|
||||
|
||||
# ─── Resolve cache directory ─────────────────────────────────────────────────
|
||||
|
||||
if (-not $CacheDir) {
|
||||
# Convention: skill lives at .github/skills/winmd-api-search/scripts/
|
||||
# so workspace root is 4 levels up from $PSScriptRoot.
|
||||
$scriptDir = $PSScriptRoot
|
||||
$root = (Resolve-Path (Join-Path $scriptDir '..\..\..\..')).Path
|
||||
$CacheDir = Join-Path $root 'Generated Files\winmd-cache'
|
||||
}
|
||||
|
||||
if (-not (Test-Path $CacheDir)) {
|
||||
Write-Error "Cache not found at: $CacheDir`nRun: .\Update-WinMdCache.ps1 (from .github\skills\winmd-api-search\scripts\)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# ─── Project resolution helpers ──────────────────────────────────────────────
|
||||
|
||||
function Get-CachedProjects {
|
||||
$projectsDir = Join-Path $CacheDir 'projects'
|
||||
if (-not (Test-Path $projectsDir)) { return @() }
|
||||
Get-ChildItem $projectsDir -Filter '*.json' | ForEach-Object { $_.BaseName }
|
||||
}
|
||||
|
||||
function Resolve-ProjectManifest {
|
||||
param([string]$Name)
|
||||
|
||||
$projectsDir = Join-Path $CacheDir 'projects'
|
||||
if (-not (Test-Path $projectsDir)) {
|
||||
Write-Error "No projects cached. Run Update-WinMdCache.ps1 first."
|
||||
exit 1
|
||||
}
|
||||
|
||||
if ($Name) {
|
||||
$path = Join-Path $projectsDir "$Name.json"
|
||||
if (-not (Test-Path $path)) {
|
||||
# Scan mode appends a hash suffix -- try prefix match
|
||||
$matching = @(Get-ChildItem $projectsDir -Filter "${Name}_*.json" -ErrorAction SilentlyContinue)
|
||||
if ($matching.Count -eq 1) {
|
||||
return Get-Content $matching[0].FullName -Raw | ConvertFrom-Json
|
||||
}
|
||||
if ($matching.Count -gt 1) {
|
||||
$names = ($matching | ForEach-Object { $_.BaseName }) -join ', '
|
||||
Write-Error "Multiple projects match '$Name'. Specify the full name: $names"
|
||||
exit 1
|
||||
}
|
||||
$available = (Get-CachedProjects) -join ', '
|
||||
Write-Error "Project '$Name' not found. Available: $available"
|
||||
exit 1
|
||||
}
|
||||
return Get-Content $path -Raw | ConvertFrom-Json
|
||||
}
|
||||
|
||||
# Auto-select if only one project
|
||||
$manifests = Get-ChildItem $projectsDir -Filter '*.json' -ErrorAction SilentlyContinue
|
||||
if ($manifests.Count -eq 0) {
|
||||
Write-Error "No projects cached. Run Update-WinMdCache.ps1 first."
|
||||
exit 1
|
||||
}
|
||||
if ($manifests.Count -eq 1) {
|
||||
return Get-Content $manifests[0].FullName -Raw | ConvertFrom-Json
|
||||
}
|
||||
|
||||
$available = ($manifests | ForEach-Object { $_.BaseName }) -join ', '
|
||||
Write-Error "Multiple projects cached -- use -Project to specify. Available: $available"
|
||||
exit 1
|
||||
}
|
||||
|
||||
function Get-PackageCacheDirs {
|
||||
param($Manifest)
|
||||
$dirs = @()
|
||||
foreach ($pkg in $Manifest.packages) {
|
||||
$dir = Join-Path (Join-Path (Join-Path $CacheDir 'packages') $pkg.id) $pkg.version
|
||||
if (Test-Path $dir) {
|
||||
$dirs += $dir
|
||||
}
|
||||
}
|
||||
return $dirs
|
||||
}
|
||||
|
||||
# ─── Action: projects ────────────────────────────────────────────────────────
|
||||
|
||||
function Show-Projects {
|
||||
$projects = Get-CachedProjects
|
||||
if ($projects.Count -eq 0) {
|
||||
Write-Output "No projects cached."
|
||||
return
|
||||
}
|
||||
Write-Output "Cached projects ($($projects.Count)):"
|
||||
foreach ($p in $projects) {
|
||||
$manifest = Get-Content (Join-Path (Join-Path $CacheDir 'projects') "$p.json") -Raw | ConvertFrom-Json
|
||||
$pkgCount = $manifest.packages.Count
|
||||
Write-Output " $p ($pkgCount package(s))"
|
||||
}
|
||||
}
|
||||
|
||||
# ─── Action: packages ────────────────────────────────────────────────────────
|
||||
|
||||
function Show-Packages {
|
||||
$manifest = Resolve-ProjectManifest -Name $Project
|
||||
Write-Output "Packages for project '$($manifest.projectName)' ($($manifest.packages.Count)):"
|
||||
foreach ($pkg in $manifest.packages) {
|
||||
$metaPath = Join-Path (Join-Path (Join-Path (Join-Path $CacheDir 'packages') $pkg.id) $pkg.version) 'meta.json'
|
||||
if (Test-Path $metaPath) {
|
||||
$meta = Get-Content $metaPath -Raw | ConvertFrom-Json
|
||||
Write-Output " $($pkg.id)@$($pkg.version) -- $($meta.totalTypes) types, $($meta.totalMembers) members"
|
||||
} else {
|
||||
Write-Output " $($pkg.id)@$($pkg.version) -- (cache missing)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# ─── Action: stats ───────────────────────────────────────────────────────────
|
||||
|
||||
function Show-Stats {
|
||||
$manifest = Resolve-ProjectManifest -Name $Project
|
||||
$totalTypes = 0
|
||||
$totalMembers = 0
|
||||
$totalNamespaces = 0
|
||||
$totalWinMd = 0
|
||||
|
||||
foreach ($pkg in $manifest.packages) {
|
||||
$metaPath = Join-Path (Join-Path (Join-Path (Join-Path $CacheDir 'packages') $pkg.id) $pkg.version) 'meta.json'
|
||||
if (Test-Path $metaPath) {
|
||||
$meta = Get-Content $metaPath -Raw | ConvertFrom-Json
|
||||
$totalTypes += $meta.totalTypes
|
||||
$totalMembers += $meta.totalMembers
|
||||
$totalNamespaces += $meta.totalNamespaces
|
||||
$totalWinMd += $meta.winMdFiles.Count
|
||||
}
|
||||
}
|
||||
|
||||
Write-Output "WinMD Index Statistics -- $($manifest.projectName)"
|
||||
Write-Output "======================================"
|
||||
Write-Output " Packages: $($manifest.packages.Count)"
|
||||
Write-Output " Namespaces: $totalNamespaces (may overlap across packages)"
|
||||
Write-Output " Types: $totalTypes"
|
||||
Write-Output " Members: $totalMembers"
|
||||
Write-Output " WinMD files: $totalWinMd"
|
||||
}
|
||||
|
||||
# ─── Action: namespaces ──────────────────────────────────────────────────────
|
||||
|
||||
function Get-Namespaces {
|
||||
param([string]$Prefix)
|
||||
$manifest = Resolve-ProjectManifest -Name $Project
|
||||
$dirs = Get-PackageCacheDirs -Manifest $manifest
|
||||
$allNs = @()
|
||||
|
||||
foreach ($dir in $dirs) {
|
||||
$nsFile = Join-Path $dir 'namespaces.json'
|
||||
if (Test-Path $nsFile) {
|
||||
$allNs += (Get-Content $nsFile -Raw | ConvertFrom-Json)
|
||||
}
|
||||
}
|
||||
|
||||
$allNs = $allNs | Sort-Object -Unique
|
||||
if ($Prefix) {
|
||||
$allNs = $allNs | Where-Object { $_ -like "$Prefix*" }
|
||||
}
|
||||
$allNs | ForEach-Object { Write-Output $_ }
|
||||
}
|
||||
|
||||
# ─── Action: types ───────────────────────────────────────────────────────────
|
||||
|
||||
function Get-TypesInNamespace {
|
||||
param([string]$Ns)
|
||||
if (-not $Ns) {
|
||||
Write-Error "-Namespace is required for 'types' action."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$manifest = Resolve-ProjectManifest -Name $Project
|
||||
$dirs = Get-PackageCacheDirs -Manifest $manifest
|
||||
$safeFile = $Ns.Replace('.', '_') + '.json'
|
||||
$found = $false
|
||||
$seen = @{}
|
||||
|
||||
foreach ($dir in $dirs) {
|
||||
$filePath = Join-Path $dir "types\$safeFile"
|
||||
if (-not (Test-Path $filePath)) { continue }
|
||||
$found = $true
|
||||
$types = Get-Content $filePath -Raw | ConvertFrom-Json
|
||||
foreach ($t in $types) {
|
||||
if ($seen.ContainsKey($t.fullName)) { continue }
|
||||
$seen[$t.fullName] = $true
|
||||
Write-Output "$($t.kind) $($t.fullName)$(if ($t.baseType) { " : $($t.baseType)" } else { '' })"
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $found) {
|
||||
Write-Error "Namespace not found: $Ns"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
# ─── Action: members ─────────────────────────────────────────────────────────
|
||||
|
||||
function Get-MembersOfType {
|
||||
param([string]$FullName)
|
||||
if (-not $FullName) {
|
||||
Write-Error "-TypeName is required for 'members' action."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$lastDot = $FullName.LastIndexOf('.')
|
||||
if ($lastDot -lt 0) {
|
||||
Write-Error "-TypeName must include a namespace (for example: 'MyNamespace.MyType'). Provided: $FullName"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$ns = $FullName.Substring(0, $lastDot)
|
||||
$safeFile = $ns.Replace('.', '_') + '.json'
|
||||
|
||||
$manifest = Resolve-ProjectManifest -Name $Project
|
||||
$dirs = Get-PackageCacheDirs -Manifest $manifest
|
||||
|
||||
foreach ($dir in $dirs) {
|
||||
$filePath = Join-Path $dir "types\$safeFile"
|
||||
if (-not (Test-Path $filePath)) { continue }
|
||||
|
||||
$types = Get-Content $filePath -Raw | ConvertFrom-Json
|
||||
$type = $types | Where-Object { $_.fullName -eq $FullName }
|
||||
if (-not $type) { continue }
|
||||
|
||||
Write-Output "$($type.kind) $($type.fullName)"
|
||||
if ($type.baseType) { Write-Output " Extends: $($type.baseType)" }
|
||||
Write-Output ""
|
||||
foreach ($m in $type.members) {
|
||||
Write-Output " [$($m.kind)] $($m.signature)"
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Write-Error "Type not found: $FullName"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# ─── Action: search ──────────────────────────────────────────────────────────
|
||||
# Ranks namespaces by best match score on type names and member names.
|
||||
# Outputs: ranked namespaces with top matching types and the JSON file path.
|
||||
# The agent can then read the JSON file to inspect all members intelligently.
|
||||
|
||||
function Search-WinMd {
|
||||
param([string]$SearchQuery, [int]$Max)
|
||||
if (-not $SearchQuery) {
|
||||
Write-Error "-Query is required for 'search' action."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$manifest = Resolve-ProjectManifest -Name $Project
|
||||
$dirs = Get-PackageCacheDirs -Manifest $manifest
|
||||
|
||||
# Collect: namespace -> { bestScore, matchingTypes[], filePath }
|
||||
$nsResults = @{}
|
||||
|
||||
foreach ($dir in $dirs) {
|
||||
$nsFile = Join-Path $dir 'namespaces.json'
|
||||
if (-not (Test-Path $nsFile)) { continue }
|
||||
$nsList = Get-Content $nsFile -Raw | ConvertFrom-Json
|
||||
|
||||
foreach ($n in $nsList) {
|
||||
$safeFile = $n.Replace('.', '_') + '.json'
|
||||
$filePath = Join-Path $dir "types\$safeFile"
|
||||
if (-not (Test-Path $filePath)) { continue }
|
||||
|
||||
$types = Get-Content $filePath -Raw | ConvertFrom-Json
|
||||
foreach ($t in $types) {
|
||||
$typeScore = Get-MatchScore -Name $t.name -FullName $t.fullName -Query $SearchQuery
|
||||
|
||||
# Also search member names for matches
|
||||
$bestMemberScore = 0
|
||||
$matchingMember = $null
|
||||
if ($t.members) {
|
||||
foreach ($m in $t.members) {
|
||||
$memberName = $m.name
|
||||
$mScore = Get-MatchScore -Name $memberName -FullName "$($t.fullName).$memberName" -Query $SearchQuery
|
||||
if ($mScore -gt $bestMemberScore) {
|
||||
$bestMemberScore = $mScore
|
||||
$matchingMember = $m.signature
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$score = [Math]::Max($typeScore, $bestMemberScore)
|
||||
if ($score -le 0) { continue }
|
||||
|
||||
if (-not $nsResults.ContainsKey($n)) {
|
||||
$nsResults[$n] = @{ BestScore = 0; Types = @(); FilePaths = @() }
|
||||
}
|
||||
$entry = $nsResults[$n]
|
||||
if ($score -gt $entry.BestScore) { $entry.BestScore = $score }
|
||||
if ($entry.FilePaths -notcontains $filePath) {
|
||||
$entry.FilePaths += $filePath
|
||||
}
|
||||
|
||||
if ($typeScore -ge $bestMemberScore) {
|
||||
$entry.Types += @{ Text = "$($t.kind) $($t.fullName) [$typeScore]"; Score = $typeScore }
|
||||
} else {
|
||||
$entry.Types += @{ Text = "$($t.kind) $($t.fullName) -> $matchingMember [$bestMemberScore]"; Score = $bestMemberScore }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($nsResults.Count -eq 0) {
|
||||
Write-Output "No results found for: $SearchQuery"
|
||||
return
|
||||
}
|
||||
|
||||
$ranked = $nsResults.GetEnumerator() |
|
||||
Sort-Object { $_.Value.BestScore } -Descending |
|
||||
Select-Object -First $Max
|
||||
|
||||
foreach ($r in $ranked) {
|
||||
$ns = $r.Key
|
||||
$info = $r.Value
|
||||
Write-Output "[$($info.BestScore)] $ns"
|
||||
foreach ($fp in $info.FilePaths) {
|
||||
Write-Output " File: $fp"
|
||||
}
|
||||
# Show top 5 highest-scoring matching types in this namespace
|
||||
$info.Types | Sort-Object { $_.Score } -Descending |
|
||||
Select-Object -First 5 |
|
||||
ForEach-Object { Write-Output " $($_.Text)" }
|
||||
Write-Output ""
|
||||
}
|
||||
}
|
||||
|
||||
# ─── Search scoring ──────────────────────────────────────────────────────────
|
||||
# Simple ranked scoring on type names. Higher = better.
|
||||
# 100 = exact name 80 = starts-with 60 = substring
|
||||
# 50 = PascalCase 40 = multi-keyword 20 = fuzzy subsequence
|
||||
|
||||
function Get-MatchScore {
|
||||
param([string]$Name, [string]$FullName, [string]$Query)
|
||||
|
||||
$q = $Query.Trim()
|
||||
if (-not $q) { return 0 }
|
||||
|
||||
if ($Name -eq $q) { return 100 }
|
||||
if ($Name -like "$q*") { return 80 }
|
||||
if ($Name -like "*$q*" -or $FullName -like "*$q*") { return 60 }
|
||||
|
||||
$initials = ($Name.ToCharArray() | Where-Object { [char]::IsUpper($_) }) -join ''
|
||||
if ($initials.Length -ge 2 -and $initials -like "*$q*") { return 50 }
|
||||
|
||||
$words = $q -split '\s+' | Where-Object { $_.Length -gt 0 }
|
||||
if ($words.Count -gt 1) {
|
||||
$allFound = $true
|
||||
foreach ($w in $words) {
|
||||
if ($Name -notlike "*$w*" -and $FullName -notlike "*$w*") {
|
||||
$allFound = $false
|
||||
break
|
||||
}
|
||||
}
|
||||
if ($allFound) { return 40 }
|
||||
}
|
||||
|
||||
if (Test-FuzzySubsequence -Text $Name -Pattern $q) { return 20 }
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
function Test-FuzzySubsequence {
|
||||
param([string]$Text, [string]$Pattern)
|
||||
$ti = 0
|
||||
$tLower = $Text.ToLowerInvariant()
|
||||
$pLower = $Pattern.ToLowerInvariant()
|
||||
foreach ($ch in $pLower.ToCharArray()) {
|
||||
$idx = $tLower.IndexOf($ch, $ti)
|
||||
if ($idx -lt 0) { return $false }
|
||||
$ti = $idx + 1
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
# ─── Action: enums ───────────────────────────────────────────────────────────
|
||||
|
||||
function Get-EnumValues {
|
||||
param([string]$FullName)
|
||||
if (-not $FullName) {
|
||||
Write-Error "-TypeName is required for 'enums' action."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$lastDot = $FullName.LastIndexOf('.')
|
||||
if ($lastDot -lt 1) {
|
||||
Write-Error "-TypeName must be a fully-qualified type name including namespace, e.g. 'Namespace.TypeName'. Provided: $FullName"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$ns = $FullName.Substring(0, $lastDot)
|
||||
$safeFile = $ns.Replace('.', '_') + '.json'
|
||||
|
||||
$manifest = Resolve-ProjectManifest -Name $Project
|
||||
$dirs = Get-PackageCacheDirs -Manifest $manifest
|
||||
|
||||
foreach ($dir in $dirs) {
|
||||
$filePath = Join-Path $dir "types\$safeFile"
|
||||
if (-not (Test-Path $filePath)) { continue }
|
||||
|
||||
$types = Get-Content $filePath -Raw | ConvertFrom-Json
|
||||
$type = $types | Where-Object { $_.fullName -eq $FullName }
|
||||
if (-not $type) { continue }
|
||||
|
||||
if ($type.kind -ne 'Enum') {
|
||||
Write-Error "$FullName is not an Enum (kind: $($type.kind))"
|
||||
exit 1
|
||||
}
|
||||
Write-Output "Enum $($type.fullName)"
|
||||
if ($type.enumValues) {
|
||||
$type.enumValues | ForEach-Object { Write-Output " $_" }
|
||||
} else {
|
||||
Write-Output " (no values)"
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Write-Error "Type not found: $FullName"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# ─── Dispatch ─────────────────────────────────────────────────────────────────
|
||||
|
||||
switch ($Action) {
|
||||
'projects' { Show-Projects }
|
||||
'packages' { Show-Packages }
|
||||
'stats' { Show-Stats }
|
||||
'namespaces' { Get-Namespaces -Prefix $Filter }
|
||||
'types' { Get-TypesInNamespace -Ns $Namespace }
|
||||
'members' { Get-MembersOfType -FullName $TypeName }
|
||||
'search' { Search-WinMd -SearchQuery $Query -Max $MaxResults }
|
||||
'enums' { Get-EnumValues -FullName $TypeName }
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Generate or refresh the WinMD cache for the Agent Skill.
|
||||
|
||||
.DESCRIPTION
|
||||
Builds and runs the standalone cache generator to export cached JSON files
|
||||
from all WinMD metadata found in project NuGet packages and Windows SDK.
|
||||
|
||||
The cache is per-package+version: if two projects reference the same
|
||||
package at the same version, the WinMD data is parsed once and shared.
|
||||
|
||||
Supports single project or recursive scan of an entire repo.
|
||||
|
||||
.PARAMETER ProjectDir
|
||||
Path to a project directory (contains .csproj/.vcxproj), or a project file itself.
|
||||
Defaults to scanning the workspace root.
|
||||
|
||||
.PARAMETER Scan
|
||||
Recursively discover all .csproj/.vcxproj files under ProjectDir.
|
||||
|
||||
.PARAMETER OutputDir
|
||||
Path to the cache output directory. Defaults to "Generated Files\winmd-cache".
|
||||
|
||||
.EXAMPLE
|
||||
.\Update-WinMdCache.ps1
|
||||
.\Update-WinMdCache.ps1 -ProjectDir BlankWinUI
|
||||
.\Update-WinMdCache.ps1 -Scan -ProjectDir .
|
||||
.\Update-WinMdCache.ps1 -ProjectDir "src\MyApp\MyApp.csproj"
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$ProjectDir,
|
||||
[switch]$Scan,
|
||||
[string]$OutputDir = 'Generated Files\winmd-cache'
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Convention: skill lives at .github/skills/winmd-api-search/scripts/
|
||||
# so workspace root is 4 levels up from $PSScriptRoot.
|
||||
$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..\..\..')).Path
|
||||
$generatorProj = Join-Path (Join-Path $PSScriptRoot 'cache-generator') 'CacheGenerator.csproj'
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# WinAppSDK version detection -- look only at the repo root folder (no recursion)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function Get-WinAppSdkVersionFromDirectoryPackagesProps {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Extract Microsoft.WindowsAppSDK version from a Directory.Packages.props
|
||||
(Central Package Management) at the repo root.
|
||||
#>
|
||||
param([string]$RepoRoot)
|
||||
$propsFile = Join-Path $RepoRoot 'Directory.Packages.props'
|
||||
if (-not (Test-Path $propsFile)) { return $null }
|
||||
try {
|
||||
[xml]$xml = Get-Content $propsFile -Raw
|
||||
$node = $xml.SelectNodes('//PackageVersion') |
|
||||
Where-Object { $_.Include -eq 'Microsoft.WindowsAppSDK' } |
|
||||
Select-Object -First 1
|
||||
if ($node) { return $node.Version }
|
||||
} catch {
|
||||
Write-Verbose "Could not parse $propsFile : $_"
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Get-WinAppSdkVersionFromPackagesConfig {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Extract Microsoft.WindowsAppSDK version from a packages.config at the repo root.
|
||||
#>
|
||||
param([string]$RepoRoot)
|
||||
$configFile = Join-Path $RepoRoot 'packages.config'
|
||||
if (-not (Test-Path $configFile)) { return $null }
|
||||
try {
|
||||
[xml]$xml = Get-Content $configFile -Raw
|
||||
$node = $xml.SelectNodes('//package') |
|
||||
Where-Object { $_.id -eq 'Microsoft.WindowsAppSDK' } |
|
||||
Select-Object -First 1
|
||||
if ($node) { return $node.version }
|
||||
} catch {
|
||||
Write-Verbose "Could not parse $configFile : $_"
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# Try Directory.Packages.props first (CPM), then packages.config
|
||||
$winAppSdkVersion = Get-WinAppSdkVersionFromDirectoryPackagesProps -RepoRoot $root
|
||||
if (-not $winAppSdkVersion) {
|
||||
$winAppSdkVersion = Get-WinAppSdkVersionFromPackagesConfig -RepoRoot $root
|
||||
}
|
||||
if ($winAppSdkVersion) {
|
||||
Write-Host "Detected WinAppSDK version from repo: $winAppSdkVersion" -ForegroundColor Cyan
|
||||
} else {
|
||||
Write-Host "No WinAppSDK version found at repo root; will use latest (Version=*)" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
# Default: if no ProjectDir, scan the workspace root
|
||||
if (-not $ProjectDir) {
|
||||
$ProjectDir = $root
|
||||
$Scan = $true
|
||||
}
|
||||
|
||||
Push-Location $root
|
||||
|
||||
try {
|
||||
# Detect installed .NET SDK -- require >= 8.0, prefer stable over preview
|
||||
$dotnetSdks = dotnet --list-sdks 2>$null
|
||||
$bestMajor = $dotnetSdks |
|
||||
Where-Object { $_ -notmatch 'preview|rc|alpha|beta' } |
|
||||
ForEach-Object { if ($_ -match '^(\d+)\.') { [int]$Matches[1] } } |
|
||||
Where-Object { $_ -ge 8 } |
|
||||
Sort-Object -Descending |
|
||||
Select-Object -First 1
|
||||
|
||||
# Fall back to preview SDKs if no stable SDK found
|
||||
if (-not $bestMajor) {
|
||||
$bestMajor = $dotnetSdks |
|
||||
ForEach-Object { if ($_ -match '^(\d+)\.') { [int]$Matches[1] } } |
|
||||
Where-Object { $_ -ge 8 } |
|
||||
Sort-Object -Descending |
|
||||
Select-Object -First 1
|
||||
}
|
||||
|
||||
if (-not $bestMajor) {
|
||||
Write-Error "No .NET SDK >= 8.0 found. Install from https://dotnet.microsoft.com/download"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$targetFramework = "net$bestMajor.0"
|
||||
Write-Host "Using .NET SDK: $targetFramework" -ForegroundColor Cyan
|
||||
|
||||
# Build MSBuild properties -- pass detected WinAppSDK version when available
|
||||
$sdkVersionProp = ''
|
||||
if ($winAppSdkVersion) {
|
||||
$sdkVersionProp = "-p:WinAppSdkVersion=$winAppSdkVersion"
|
||||
}
|
||||
|
||||
Write-Host "Building cache generator..." -ForegroundColor Cyan
|
||||
$restoreArgs = @($generatorProj, "-p:TargetFramework=$targetFramework", '--nologo', '-v', 'q')
|
||||
if ($sdkVersionProp) { $restoreArgs += $sdkVersionProp }
|
||||
dotnet restore @restoreArgs
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Error "Restore failed"
|
||||
exit 1
|
||||
}
|
||||
$buildArgs = @($generatorProj, '-c', 'Release', '--nologo', '-v', 'q', "-p:TargetFramework=$targetFramework", '--no-restore')
|
||||
if ($sdkVersionProp) { $buildArgs += $sdkVersionProp }
|
||||
dotnet build @buildArgs
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Error "Build failed"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Run the built executable directly (avoids dotnet run target framework mismatch issues)
|
||||
$generatorDir = Join-Path $PSScriptRoot 'cache-generator'
|
||||
$exePath = Join-Path $generatorDir "bin\Release\$targetFramework\CacheGenerator.exe"
|
||||
if (-not (Test-Path $exePath)) {
|
||||
# Fallback: try dll with dotnet
|
||||
$dllPath = Join-Path $generatorDir "bin\Release\$targetFramework\CacheGenerator.dll"
|
||||
if (Test-Path $dllPath) {
|
||||
$exePath = $null
|
||||
} else {
|
||||
Write-Error "Built executable not found at: $exePath"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
$runArgs = @()
|
||||
if ($Scan) {
|
||||
$runArgs += '--scan'
|
||||
}
|
||||
|
||||
# Detect installed WinAppSDK runtime via Get-AppxPackage (the WindowsApps
|
||||
# folder is ACL-restricted so C# cannot enumerate it directly).
|
||||
# WinMD files are architecture-independent metadata, so pick whichever arch
|
||||
# matches the current OS to ensure the package is present.
|
||||
$osArch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()
|
||||
$runtimePkg = Get-AppxPackage -Name 'Microsoft.WindowsAppRuntime.*' -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.Name -notmatch 'CBS' -and $_.Architecture -eq $osArch } |
|
||||
Sort-Object -Property Version -Descending |
|
||||
Select-Object -First 1
|
||||
if ($runtimePkg -and $runtimePkg.InstallLocation -and (Test-Path $runtimePkg.InstallLocation)) {
|
||||
Write-Host "Detected WinAppSDK runtime: $($runtimePkg.Name) v$($runtimePkg.Version)" -ForegroundColor Cyan
|
||||
$runArgs += '--winappsdk-runtime'
|
||||
$runArgs += $runtimePkg.InstallLocation
|
||||
}
|
||||
|
||||
$runArgs += $ProjectDir
|
||||
$runArgs += $OutputDir
|
||||
|
||||
Write-Host "Exporting WinMD cache..." -ForegroundColor Cyan
|
||||
if ($exePath) {
|
||||
& $exePath @runArgs
|
||||
} else {
|
||||
dotnet $dllPath @runArgs
|
||||
}
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Error "Cache export failed"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "Cache updated at: $OutputDir" -ForegroundColor Green
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<!-- Default fallback; Update-WinMdCache.ps1 overrides via -p:TargetFramework=net{X}.0 -->
|
||||
<TargetFramework Condition="'$(TargetFramework)' == ''">net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
<!-- System.Reflection.Metadata is inbox in net9.0+, only needed for net8.0 -->
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
|
||||
<PackageReference Include="System.Reflection.Metadata" Version="8.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
Baseline WinAppSDK packages: downloaded during restore so the cache generator
|
||||
can always index WinAppSDK APIs, even if the target project hasn't been restored.
|
||||
ExcludeAssets="all" means they're downloaded but don't affect this tool's build.
|
||||
|
||||
When the repo has a known version (passed via -p:WinAppSdkVersion=X.Y.Z from
|
||||
Update-WinMdCache.ps1), prefer that version to avoid unnecessary NuGet downloads.
|
||||
Falls back to Version="*" (latest) on fresh clones with no restore.
|
||||
-->
|
||||
<ItemGroup Condition="'$(WinAppSdkVersion)' != ''">
|
||||
<PackageReference Include="Microsoft.WindowsAppSDK" Version="$(WinAppSdkVersion)" ExcludeAssets="all" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(WinAppSdkVersion)' == ''">
|
||||
<PackageReference Include="Microsoft.WindowsAppSDK" Version="*" ExcludeAssets="all" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,3 +0,0 @@
|
||||
<Project>
|
||||
<!-- Isolate this standalone tool from the repo-level build configuration -->
|
||||
</Project>
|
||||
@@ -1,3 +0,0 @@
|
||||
<Project>
|
||||
<!-- Isolate this standalone tool from the repo-level build targets -->
|
||||
</Project>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user