# Support handoff: irm https://mole.fit/windows/diagnose | iex # Independent of the installed Mole version. PowerShell 5.1, ordinary user permissions. The older # installation/network diagnostic (-Feedback:$false) was retired 2026-10-16: it wrote raw paths, crash.log # text and download URLs and replaced the clipboard (weekly audit U2). [CmdletBinding()] param([switch]$ChooseFolder, [string]$TargetPath, [string]$OutputDirectory) function Invoke-MoleFeedback { param([string]$Folder, [string]$Destination) $ErrorActionPreference = 'Stop' # These helpers run in isolated, time-bounded PowerShell workers. Only allowlisted # fields leave a worker: no exception messages, command lines or private file names. $helpers = { $ErrorActionPreference = 'Stop' function Pdh-Code($value) { '0x{0:X8}' -f [uint32]$value } # What Mole's CPU tile got from PDH: the total it adds first, else the Processor Time it falls back to. function Pdh-CpuVerdict($query,$counters,$systemCpu) { if(-not $query -or $query.Status){return $null} if($query.OpenStatus-ne '0x00000000'){return 'open-failed'} $ok='0x00000000' $used=@($counters|Where-Object {$_.Id-eq 'cpu-utility-total' -and $_.AddStatus-eq $ok})+@($counters|Where-Object {$_.Id-eq 'cpu-time-total' -and $_.AddStatus-eq $ok})|Select-Object -First 1 if(-not $used){return 'add-failed'} if($query.SecondCollect-ne $ok){return 'collect-failed'} if($null-eq $used.Value){return 'invalid-data'} if($used.Value-eq 0 -and $systemCpu -and $systemCpu.BusyPercent-ge 5){return 'zero-while-busy'} 'ok' } # ACPI thermal zones from PDH, readable unelevated: the firmware's zone, not necessarily the CPU package. # Kelvin to Celsius; a name outside the ACPI shape leaves as 'other'. function Thermal-ZoneFacts($row) { if(-not $row -or $null-eq $row.Names){return} for($k=0;$k-lt $row.Names.Count;$k++){ $value=$row.Values[$k] $name=[string]$row.Names[$k] [pscustomobject]@{Kind='ThermalZone';Name=$(if($name -match '^[\\_.A-Za-z0-9]{1,32}$'){$name}else{'other'});Celsius=$(if([double]::IsNaN($value) -or $value-le 0){$null}else{[Math]::Round($value-273.15,1)})} } } # Summary: ":" per zone. Empty only when the counter was added and its array read with zero # instances; a failed add, collect or array read is null, with its PDH status in the PdhCounter row (schema 18: # schema 17 read every failure as an empty list, which said "this PC has no thermal zone"). function Thermal-Summary($query,$counters,$zones) { $ok='0x00000000' if(-not $query -or $query.Status -or $query.OpenStatus-ne $ok -or $query.SecondCollect-ne $ok){return $null} $counter=@($counters|Where-Object Id -eq 'thermal-zone')|Select-Object -First 1 if(-not $counter -or $counter.AddStatus-ne $ok -or $counter.ArrayStatus-ne $ok -or $null-eq $counter.Instances){return $null} $zones=@($zones) if([int]$counter.Instances-ne $zones.Count){return $null} ,@($zones|ForEach-Object {[string]$_.Name+':'+$(if($null-ne $_.Celsius){[string]$_.Celsius}else{'unknown'})}) } # One PdhCounter row. A wildcard counter keeps its array status beside the instance count, and the count is null when # the counter was never added, so a failed read cannot pass for zero instances (schema 18). function Pdh-CounterRow($r,[bool]$opened) { $wildcard=$r.Id-like '*-cores' -or $r.Id-in @('gpu-engine','thermal-zone') $added=$opened -and $r.AddStatus-eq 0 [pscustomobject]@{Kind='PdhCounter';Id=$r.Id;AddStatus=(Pdh-Code $r.AddStatus);FormatStatus=(Pdh-Code $r.FormatStatus);ValueStatus=(Pdh-Code $r.ValueStatus);Value=$(if($r.HasValue){[Math]::Round($r.Value,1)}else{$null});Instances=$(if($wildcard -and $added){[int]$r.Instances}else{$null});ArrayStatus=$(if($wildcard -and $added){Pdh-Code $r.ArrayStatus}else{$null})} } function Safe-Version($value) { if ([string]$value -match '^\d[0-9A-Za-z.+_-]{0,63}$') { return [string]$value } return $null } function Metadata-PathCheck([string]$path) { if ($path -notmatch '^[A-Za-z]:[\\/]' -or $path.Substring(2).Contains(':')) { return [pscustomobject]@{Reason='non-local-or-invalid';Path=$null} } try { $normal=[IO.Path]::GetFullPath($path.Replace('/','\')) $drive=New-Object IO.DriveInfo ([IO.Path]::GetPathRoot($normal)) if($drive.DriveType-ne [IO.DriveType]::Fixed){return [pscustomobject]@{Reason='non-fixed-drive';Path=$null}} $chain=New-Object System.Collections.Generic.List[string] $part=$normal while($part){$chain.Add($part);$part=[IO.Path]::GetDirectoryName($part)} # Inspect from the drive down before accessing a child through a junction. for($i=$chain.Count-1;$i-ge 0;$i--) { try {$item=Get-Item -LiteralPath $chain[$i] -Force -ErrorAction Stop} catch { if($_.CategoryInfo.Category-eq 'ObjectNotFound'){return [pscustomobject]@{Reason='missing';Path=$normal}} return [pscustomobject]@{Reason=(Error-Status $_);Path=$null} } if($item.Attributes -band [IO.FileAttributes]::ReparsePoint){return [pscustomobject]@{Reason='reparse-point';Path=$null}} } return [pscustomobject]@{Reason='present';Path=$normal} } catch {return [pscustomobject]@{Reason=(Error-Status $_);Path=$null}} } function Local-MetadataPath([string]$path) { (Metadata-PathCheck $path).Path } function Read-SmallText([string]$path, [switch]$LocalOnly) { if($LocalOnly){$path=Local-MetadataPath $path;if(-not $path){throw 'Metadata refused'}} if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { return $null } $item = Get-Item -LiteralPath $path -Force if ($item.Length -gt 1MB -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Metadata refused' } return [IO.File]::ReadAllText($path) } function Unique-LocalPaths($paths) { $seen=New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) foreach($path in $paths) { if([string]::IsNullOrWhiteSpace($path)){continue} $normal=Local-MetadataPath ([string]$path) if(-not $normal){continue};$normal=$normal.TrimEnd('\') if($seen.Add($normal)){$normal} } } function Known-ProcessImage([string]$image) { $name=$image.ToLowerInvariant() -replace '\.exe$','' if($name -in @('chrome','msedge','chatgpt','codex','steam','steamwebhelper','mole')){return $name} return 'other' } function Startup-Facts([string]$text) { if(-not $text){return} try { $r=$text|ConvertFrom-Json if($r.Schema-ne 1 -or $r.Result -notin @('Done','Declined','Failed')){return} if($r.Stage -notin @('write','read-write','validate','launch','execute','verify','ledger')){return} if($r.Source -notmatch '^(UserRun|MachineRun|MachineRun32|UserStartupFolder|CommonStartupFolder|PackagedTask|ScheduledTask|Service)$'){return} [pscustomobject]@{Kind='StartupOperation';Utc=((Json-Time $r.Utc).ToUniversalTime().ToString('o'));Source=$r.Source;App=$(if($r.App-eq 'ChatGPT'){'ChatGPT'}else{'other'});BeforeEnabled=[bool]$r.BeforeEnabled;RequestedEnabled=[bool]$r.RequestedEnabled;ObservedEnabled=$(if($null-ne $r.ObservedEnabled){[bool]$r.ObservedEnabled}else{$null});Result=$r.Result;Stage=$r.Stage;ErrorCode=$(if($null-ne $r.ErrorCode){[int]$r.ErrorCode}else{$null})} }catch{[pscustomobject]@{Kind='StartupOperation';Status='invalid'}} } function Clean-ScanFacts([string]$text,[DateTime]$now) { # The app's clean-scan-summary.json (CleanScanTiming): fixed stage names and catalog rule ids with milliseconds. if(-not $text){return [pscustomobject]@{Kind='CleanScan';Status='none-recorded'}} try { $r=$text|ConvertFrom-Json if($r.Schema-ne 1){return [pscustomobject]@{Kind='CleanScan';Status='other-schema'}} $stageNames=@('catalog','external','admin','orphans','installers','delivery-optimization','recycle-bin') $stages=@(@($r.Stages)|Where-Object {$_ -and $stageNames -contains [string]$_.Stage}|Select-Object -First 7|ForEach-Object {[pscustomobject]@{Stage=[string]$_.Stage;Ms=[long]$_.Ms}}) $rules=@(@($r.SlowRules)|Where-Object {$_ -and [string]$_.Rule -cmatch '^[a-z0-9][a-z0-9.-]{0,63}$'}|Select-Object -First 12|ForEach-Object {[pscustomobject]@{Rule=[string]$_.Rule;Ms=[long]$_.Ms}}) $utc=Json-Time $r.Utc [pscustomobject]@{Kind='CleanScan';Status='complete';Utc=$(if($utc){$utc.UtcDateTime.ToString('o')}else{$null});AgeHours=$(if($utc){[Math]::Round(($now-$utc.UtcDateTime).TotalHours,1)}else{$null});TotalMs=[long]$r.TotalMs;Rows=[int]$r.Rows;Stages=$stages;SlowRules=$rules} }catch{[pscustomobject]@{Kind='CleanScan';Status='invalid'}} } function Zone-Id([string]$text) { # The Mark of the Web's zone only; HostUrl and ReferrerUrl never leave. if(-not $text){return $null} if($text -match '(?m)^\s*ZoneId\s*=\s*([0-4])\s*$'){return [int]$Matches[1]} return $null } function Signature-Facts([string]$role,$signature) { if(-not $signature){return [pscustomobject]@{Kind='LaunchSignature';Role=$role;Status='missing'}} $status=[string]$signature.Status if($status -notin @('Valid','UnknownError','NotSigned','HashMismatch','NotTrusted','NotSupportedFileFormat','Incompatible')){$status='other'} $subject=$(if($signature.SignerCertificate){[string]$signature.SignerCertificate.Subject}else{''}) $signer=$(if(-not $subject){$null}elseif($subject -match 'CN="?Faberon Technology Limited'){'mole'}else{'other'}) [pscustomobject]@{Kind='LaunchSignature';Role=$role;Status=$status;Signer=$signer;TimeStamped=($null-ne $signature.TimeStamperCertificate)} } function Defender-LaunchFacts($detections) { # Detections whose resources name Mole's install folder or a Mole setup file, as Defender's public threat id, # time and outcome; the resource paths never leave. foreach($d in @($detections|Where-Object {$_})) { $where=$null foreach($resource in @($d.Resources)) { $text=[string]$resource if($text -match '(?i)\\Tw93\.Mole\\'){$where='install';break} if($text -match '(?i)\\Mole[^\\]*Setup[^\\]*\.exe$'){$where='setup';break} } if(-not $where){continue} $time=$d.InitialDetectionTime [pscustomobject]@{Kind='LaunchDefender';Where=$where;ThreatId=$(if($null-ne $d.ThreatID){[long]$d.ThreatID}else{$null});DetectedUtc=$(if($time -is [DateTime]){$time.ToUniversalTime().ToString('o')}else{$null});ActionSuccess=$(if($null-ne $d.ActionSuccess){[bool]$d.ActionSuccess}else{$null})} } } function CodeIntegrity-LaunchFacts($events) { # Code Integrity blocks (Smart App Control, WDAC) naming Mole's install folder: event id and time only. foreach($e in @($events|Where-Object {$_})) { if([string]$e.Message -notmatch '(?i)\\Tw93\.Mole\\'){continue} [pscustomobject]@{Kind='LaunchCodeIntegrity';EventId=[int]$e.Id;Utc=$(if($e.TimeCreated -is [DateTime]){$e.TimeCreated.ToUniversalTime().ToString('o')}else{$null})} } } function Number-OrNull($value,[type]$type) { if($null-eq $value){return $null} return $value -as $type } function Int-Array($value, [int]$Length) { # Fixed-length integer arrays only (pixel rects and points); anything else is null. if($null-eq $value){return $null} $items=@($value) if($items.Count-ne $Length){return $null} $out=New-Object 'int[]' $Length for($i=0;$i-lt $Length;$i++){ if(-not ($items[$i]-is [ValueType]) -or $items[$i]-is [bool]){return $null} $n=0L;if(-not [long]::TryParse([string]$items[$i],[ref]$n) -or [Math]::Abs($n)-gt 1000000){return $null} $out[$i]=[int]$n } return ,$out } function Unique-Events($rows) { # Each status snapshot carries the full tray and placement history; two snapshots repeated it all. $seen=New-Object 'System.Collections.Generic.HashSet[string]' foreach($row in $rows) { if($row.Kind-eq 'TrayEvent'){if(-not $seen.Add('t|'+$row.Utc+'|'+$row.Event)){continue}} elseif($row.Kind-eq 'PanelPlacement'){if(-not $seen.Add('p|'+$row.Utc+'|'+$row.Anchor)){continue}} elseif($row.Kind-in @('PanelPlacements','MoleRuntime','KeepAwake') -and $row.Status){if(-not $seen.Add('s|'+$row.Kind)){continue}} $row } } function Json-Time($value) { # pwsh 7's ConvertFrom-Json turns an ISO string into a DateTime ("Z" gives Kind Utc), and [string] on that drops # the zone, so a UTC time read back as local moved by the offset: FrameAgeMs ran 8 h long on three 2026-10-15 # reports. Windows PowerShell 5.1 keeps the string. Every time read from JSON goes through here. if($value -is [DateTimeOffset]){return $value} if($value -is [DateTime]){if($value.Kind-eq [DateTimeKind]::Unspecified){return [DateTimeOffset]::new([DateTime]::SpecifyKind($value,[DateTimeKind]::Utc))};return [DateTimeOffset]::new($value.ToUniversalTime())} $at=[DateTimeOffset]::MinValue if($null-ne $value -and [DateTimeOffset]::TryParse([string]$value,[Globalization.CultureInfo]::InvariantCulture,[Globalization.DateTimeStyles]::AssumeUniversal,[ref]$at)){return $at} $null } function Sample-Age($value, [DateTimeOffset]$ObservedUtc) { if(-not $value){return $null} $at=Json-Time $value if($null-eq $at -or $at-gt $ObservedUtc){return $null} return [Math]::Round(($ObservedUtc-$at).TotalMilliseconds) } function Runtime-StatusFacts([string]$text, [DateTimeOffset]$ObservedUtc = [DateTimeOffset]::UtcNow) { $r=$text|ConvertFrom-Json if($r.Schema-ne 1){throw 'Unsupported status schema'} [pscustomobject]@{Kind='MoleStatus';TrayHistoryAvailable=($r.PSObject.Properties.Name-contains 'TrayEvents');PanelHistoryAvailable=($r.PSObject.Properties.Name-contains 'PanelPlacements');ObservedUtc=$ObservedUtc.ToUniversalTime().ToString('o');FrameAgeMs=(Sample-Age $r.FrameUtc $ObservedUtc);ProcessSampleAgeMs=(Sample-Age $r.ProcessSampleUtc $ObservedUtc);FrameUtc=$(if($r.FrameUtc){(Json-Time $r.FrameUtc).ToString('o')}else{$null});ProcessSampleUtc=$(if($r.ProcessSampleUtc){(Json-Time $r.ProcessSampleUtc).ToString('o')}else{$null});OrderHeld=[bool]$r.OrderHeld;SearchActive=$(if($r.PSObject.Properties['SearchActive']){[bool]$r.SearchActive}else{$null});GpuTemperatureCelsius=(Number-OrNull $r.GpuTemperatureCelsius ([double]));DriveTemperatureCelsius=(Number-OrNull $r.DriveTemperatureCelsius ([double]));Sampling=[bool]$r.Sampling;WindowActive=[bool]$r.WindowActive;CpuPercent=(Number-OrNull $r.CpuPercent ([double]));LogicalProcessors=(Number-OrNull $r.LogicalProcessors ([int]));MemoryUsedBytes=(Number-OrNull $r.MemoryUsedBytes ([long]));MemoryTotalBytes=(Number-OrNull $r.MemoryTotalBytes ([long]));GpuPercent=(Number-OrNull $r.GpuPercent ([double]))} # Fields a newer build added are reported unavailable on an older one, never as an empty history. $names=@($r.PSObject.Properties.Name) if($names-contains 'PanelPlacements') { foreach($p in @($r.PanelPlacements|Where-Object {$null-ne $_}|Select-Object -Last 16)) { $at=Json-Time $p.Utc if($null-eq $at -or $p.Anchor-notin @('icon','click','edge')){continue} $placed=Int-Array $p.Placed 4;$work=Int-Array $p.Work 4;$bounds=Int-Array $p.Bounds 4 if(-not $placed -or -not $work -or -not $bounds){continue} [pscustomobject]@{Kind='PanelPlacement';Utc=$at.ToUniversalTime().ToString('o');Anchor=$p.Anchor;Icon=(Int-Array $p.Icon 4);Click=(Int-Array $p.Click 2);Placed=$placed;Observed=(Int-Array $p.Observed 4);Moved=$(if($p.Moved-is [bool]){$p.Moved}else{$null});Work=$work;Bounds=$bounds;Dpi=$(if($p.Dpi-is [ValueType] -and [int]$p.Dpi-ge 48 -and [int]$p.Dpi-le 960){[int]$p.Dpi}else{$null})} } } else {[pscustomobject]@{Kind='PanelPlacements';Status='unavailable-in-this-build'}} if($names-contains 'Runtime' -and $null-ne $r.Runtime) { $rt=$r.Runtime [pscustomobject]@{Kind='MoleRuntime';GcHeapBytes=(Number-OrNull $rt.GcHeapBytes ([long]));GcCommittedBytes=(Number-OrNull $rt.GcCommittedBytes ([long]));Gen0Collections=(Number-OrNull $rt.Gen0Collections ([int]));Gen1Collections=(Number-OrNull $rt.Gen1Collections ([int]));Gen2Collections=(Number-OrNull $rt.Gen2Collections ([int]));PlanetGpuActive=$(if($rt.PlanetGpuActive-is [bool]){$rt.PlanetGpuActive}else{$null});PlanetGpuDevices=(Number-OrNull $rt.PlanetGpuDevices ([int]));OffScreenSeconds=(Number-OrNull $rt.OffScreenSeconds ([int]));GcLargeObjectBytes=(Number-OrNull $rt.GcLargeObjectBytes ([long]));GcFragmentedBytes=(Number-OrNull $rt.GcFragmentedBytes ([long]));GcPinnedObjects=(Number-OrNull $rt.GcPinnedObjects ([int]));CachedIcons=(Number-OrNull $rt.CachedIcons ([int]));WindowState=$(if($rt.WindowState-in @('normal','maximized','minimized','hidden')){[string]$rt.WindowState}else{$null})} } else {[pscustomobject]@{Kind='MoleRuntime';Status='unavailable-in-this-build'}} if($names-contains 'KeepAwake' -and $null-ne $r.KeepAwake) { $k=$r.KeepAwake [pscustomobject]@{Kind='KeepAwake';Active=$(if($k.Active-is [bool]){$k.Active}else{$null});Mode=$(if($k.Mode-in @('screen','work')){[string]$k.Mode}else{$null});Paused=$(if($k.Paused-is [bool]){$k.Paused}else{$null});Indefinite=$(if($k.Indefinite-is [bool]){$k.Indefinite}else{$null});MinutesLeft=(Number-OrNull $k.MinutesLeft ([int]))} } else {[pscustomobject]@{Kind='KeepAwake';Status='unavailable-in-this-build'}} foreach($event in @($r.TrayEvents|Where-Object {$null-ne $_}|Select-Object -Last 64)) { if($event.Event-notin @('Primary','PrimaryKey','PrimaryDouble','Secondary','secondary-echo','NotificationClicked','settled','show-request','shown','activated','deactivated','hide-deactivated','hide-requested')){continue} $at=Json-Time $event.Utc if($null-eq $at){continue} [pscustomobject]@{Kind='TrayEvent';Utc=$at.ToUniversalTime().ToString('o');Event=$event.Event;Open=$(if($event.Open-is [bool]){$event.Open}else{$null});Swap=$(if($event.Swap-is [bool]){$event.Swap}else{$null});Foreground=$(if($event.Foreground-in @('mole','explorer','mydockfinder','none','unavailable')){$event.Foreground}else{'other'})} } foreach($gpu in @($r.GpuAdapters|Where-Object {$null-ne $_}|Select-Object -First 8)) { [pscustomobject]@{Kind='MoleGpuAdapter';AdapterLuid=(Number-OrNull $gpu.AdapterLuid ([long]));UsagePercent=[double]$gpu.UsagePercent;DedicatedUsedBytes=[long]$gpu.DedicatedUsedBytes;DedicatedLimitBytes=[long]$gpu.DedicatedLimitBytes;TemperatureCelsius=(Number-OrNull $gpu.TemperatureCelsius ([double]))} } foreach($row in @($r.Rows|Select-Object -First 20)) { $members=@($row.Members|Where-Object {$null-ne $_}|Select-Object -First 64) [pscustomobject]@{Kind='MoleProcess';ProcessId=[int]$row.Pid;Image=(Known-ProcessImage $row.Image);CpuPercent=[double]$row.CpuPercent;MemoryBytes=[long]$row.MemoryBytes;MemberCount=[int]$row.MemberCount;ExportedMemberCount=$members.Count;MembersTruncated=([int]$row.MemberCount-gt $members.Count);DisplayedCpuPercent=(Number-OrNull $row.DisplayedCpuPercent ([double]));DisplayedMemoryBytes=(Number-OrNull $row.DisplayedMemoryBytes ([long]))} foreach($member in $members) { [pscustomobject]@{Kind='MoleProcessMember';GroupProcessId=[int]$row.Pid;ProcessId=[int]$member.Pid;CreatedUtc=((Json-Time $member.CreationTimeUtc).ToString('o'));Image=(Known-ProcessImage $member.Image);CpuTime100ns=[long]$member.CpuTime100ns;CpuPercent=[double]$member.CpuPercent;MemoryBytes=[long]$member.MemoryBytes} } } } function Read-MoleStatus([int]$ProcessId) { $pipe=New-Object IO.Pipes.NamedPipeClientStream('.',('Mole.Status.'+$ProcessId),[IO.Pipes.PipeDirection]::In,[IO.Pipes.PipeOptions]::Asynchronous) try { $pipe.Connect(300) $buffer=New-Object byte[] 262144;$used=0;$timer=[Diagnostics.Stopwatch]::StartNew() while($used-lt $buffer.Length) { $read=$pipe.ReadAsync($buffer,$used,$buffer.Length-$used) if(-not $read.Wait([Math]::Max(1,1500-[int]$timer.ElapsedMilliseconds))){throw 'Snapshot timeout'} $count=$read.Result;if($count-eq 0){break};$used+=$count } if($used-ge $buffer.Length){throw 'Snapshot limit'} Runtime-StatusFacts ([Text.Encoding]::UTF8.GetString($buffer,0,$used)) } catch {[pscustomobject]@{Kind='MoleStatus';Status='unavailable';Note='Requires a running Mole build with the support snapshot endpoint'}} finally {$pipe.Dispose()} } function Memory-Sample($Process, [int]$Index, [string]$Instance) { $Process.Refresh() [pscustomobject]@{Kind='MemorySample';Instance=$Instance;Index=$Index;Utc=[DateTime]::UtcNow.ToString('o');WorkingSetBytes=$Process.WorkingSet64;PrivateBytes=$Process.PrivateMemorySize64;PeakWorkingSetBytes=$Process.PeakWorkingSet64;VirtualBytes=$Process.VirtualMemorySize64;HandleCount=$Process.HandleCount;ThreadCount=$Process.Threads.Count;CpuMilliseconds=$Process.TotalProcessorTime.TotalMilliseconds;UptimeSeconds=([DateTime]::Now-$Process.StartTime).TotalSeconds;Responding=$Process.Responding;GdiObjects=$(try{[MoleFeedbackNative]::GdiObjects($Process.Handle)}catch{$null});UserObjects=$(try{[MoleFeedbackNative]::UserObjects($Process.Handle)}catch{$null})} } function Thread-Facts($first, $second, [string]$Instance, [long]$WindowMs) { # Two snapshots over the memory-sample window: which modules own the threads, and # which ones used the CPU in between. Thread ids stay inside this function. $before=@{};foreach($r in $first.Rows){$before[$r.Id]=$r.CpuMs} $rows=@(foreach($r in $second.Rows){ $delta=if($before.ContainsKey($r.Id)){[Math]::Max(0,$r.CpuMs-$before[$r.Id])}else{$r.CpuMs} [pscustomobject]@{Module=$r.Module;Origin=$r.Origin;State=$r.State;WaitReason=$(if([string]$r.WaitReason -match '^[A-Za-z]{1,32}$'){[string]$r.WaitReason}else{$null});Delta=$delta;New=(-not $before.ContainsKey($r.Id))} }) [pscustomobject]@{Kind='ThreadSummary';Instance=$Instance;Status=$second.Status;Threads=$rows.Count;ThreadsBefore=$first.Rows.Count;NewThreads=@($rows|Where-Object New).Count;LoadedModules=$second.Modules;Unresolved=$second.Unresolved;WindowMs=$WindowMs;CpuMsDelta=[Math]::Round(($rows|Measure-Object Delta -Sum).Sum,1)} $groups=@($rows|Group-Object Module|ForEach-Object {[pscustomobject]@{Kind='ThreadModule';Instance=$Instance;Module=$_.Name;Origin=$_.Group[0].Origin;Threads=$_.Count;Waiting=@($_.Group|Where-Object State -eq 'Wait').Count;CpuMsDelta=[Math]::Round(($_.Group|Measure-Object Delta -Sum).Sum,1)}}) $groups|Sort-Object @{e='Threads';Descending=$true},@{e='CpuMsDelta';Descending=$true}|Select-Object -First 24 $groups|Sort-Object Threads -Descending|Select-Object -Skip 24|Where-Object CpuMsDelta -ge 20 # The eight largest CPU deltas, idle ones included, so a quiet window still shows what the threads wait on. $rank=0 $rows|Sort-Object @{e='Delta';Descending=$true},@{e='Module';Descending=$false}|Select-Object -First 8|ForEach-Object {$rank++;[pscustomobject]@{Kind='TopThread';Instance=$Instance;Rank=$rank;Module=$_.Module;Origin=$_.Origin;State=$_.State;WaitReason=$_.WaitReason;CpuMsDelta=[Math]::Round($_.Delta,1)}} } function Child-Processes([int]$ParentId, [string]$Instance) { # Names from a fixed list only; no command lines or paths. $known=@('winget.exe','powershell.exe','pwsh.exe','msiexec.exe','w32tm.exe','ie4uinit.exe','steam.exe','Update.exe','Mole.exe','conhost.exe','cmd.exe','rundll32.exe') $children=@(Get-CimInstance Win32_Process -Filter ("ParentProcessId="+$ParentId) -OperationTimeoutSec 5) foreach($g in @($children|Group-Object {if($_.Name -in $known){$_.Name}else{'other'}})){[pscustomobject]@{Kind='ChildProcess';Instance=$Instance;Name=$g.Name;Count=$g.Count}} if(-not $children.Count){[pscustomobject]@{Kind='ChildProcess';Instance=$Instance;Name=$null;Count=0}} } function Service-AdminCanChange([string]$sddl) { # Mole's ServiceSecurity rule: may an elevated administrator change the start type? A packaged app's service # grants Administrators nothing and Authenticated Users no DC, so Mole lists it locked. Null when unknown. if(-not $sddl -or $sddl -notmatch '^D:'){return $null} if($sddl -match '^D:NO_ACCESS_CONTROL'){return $true} $dacl=($sddl -split '\)S:',2)[0];$allowed=$false $rights=@{GA=0x10000000;GR=2147483648;GW=0x40000000;GX=0x20000000;RC=0x20000;SD=0x10000;WD=0x40000;WO=0x80000;CC=1;DC=2;LC=4;SW=8;RP=0x10;WP=0x20;DT=0x40;LO=0x80;CR=0x100;FA=0x1F01FF;FR=0x120089;FW=0x120116;FX=0x1200A0;KA=0xF003F;KR=0x20019;KW=0x20006;KX=0x20019} foreach($m in [regex]::Matches($dacl,'\(([^()]*)\)')){ $f=$m.Groups[1].Value -split ';' if($f.Count-ne 6){return $null} if($f[1] -cmatch 'IO'){continue} if($f[5] -notin @('BA','S-1-5-32-544','AU','S-1-5-11','WD','S-1-1-0','IU','S-1-5-4','BU','S-1-5-32-545')){continue} $mask=[uint64]0 if($f[2] -match '^0x([0-9A-Fa-f]{1,8})$'){$mask=[Convert]::ToUInt64($Matches[1],16)} elseif($f[2].Length%2-eq 0){for($k=0;$k-lt $f[2].Length;$k+=2){$t=$f[2].Substring($k,2);if(-not $rights.ContainsKey($t)){return $null};$mask=$mask -bor [uint64]$rights[$t]}} else{return $null} if(($mask -band 0x50000002)-eq 0){continue} if($f[0] -ceq 'D'){return $false}elseif($f[0] -ceq 'A'){$allowed=$true}else{return $null} } $allowed } function Crash-Facts([string]$text) { # Round-trip timestamp, exception type and the first Mole frame of each entry in the # last 7 days. Messages and file paths stay behind: they can name a user folder. $lines=$text -split "\r?\n";$entries=New-Object System.Collections.Generic.List[object];$current=$null foreach($line in $lines) { if($line -match '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}[+-]\d{2}:\d{2}$') { $at=[DateTimeOffset]::MinValue if([DateTimeOffset]::TryParse($line,[ref]$at)){$current=[pscustomobject]@{Kind='CrashEntry';Utc=$at.ToUniversalTime().ToString('o');Exception=$null;Inner=$null;Drive=$null;MoleFrame=$null;Trace=$false};$entries.Add($current)} continue } if(-not $current){continue} if(-not $current.Exception -and $line -match '^([A-Za-z_][A-Za-z0-9_.]{0,127}(?:Exception|Error))(?::| \(0x[0-9A-Fa-f]{8}\)|$)'){$current.Exception=$Matches[1];if($line -match ': trace on$'){$current.Trace=$true} # Analyze's walk fault names only its drive letter (AnalyzeWalkFaultException); the fault rides inside. if($Matches[1]-eq 'Mole.Core.DiskScan.AnalyzeWalkFaultException' -and $line -match ': Analyze walk on ([A-Z]:|other) continued past a fault'){$current.Drive=$Matches[1]};continue} if($current.Exception -and -not $current.Inner -and $line -match '^\s*---> ([A-Za-z_][A-Za-z0-9_.]{0,127}(?:Exception|Error))(?::| \(0x[0-9A-Fa-f]{8}\)|$)'){$current.Inner=$Matches[1];continue} if(-not $current.MoleFrame -and $line -match '^\s+at (Mole\.[A-Za-z0-9_.<>`|]{1,200})\('){$current.MoleFrame=$Matches[1]} } $recent=@($entries|Where-Object {-not $_.Trace -and [DateTimeOffset]::Parse($_.Utc) -ge [DateTimeOffset]::UtcNow.AddDays(-7)}) [pscustomobject]@{Kind='CrashLog';Entries=$entries.Count;RecentEntries=$recent.Count} $recent|Select-Object -Last 12|Select-Object Kind,Utc,Exception,Inner,Drive,MoleFrame } function Runtime-CrashFacts([string]$text) { # One .NET Runtime 1026 event, Mole's only: how the runtime ended the process, the .NET version, exception # types and code frames. A worker thread's exception, a fail-fast or a stack overflow lands here and never in # crash.log (0.15.0: Analyze closed a second into its walk with crash.log empty). Messages, paths and line # numbers stay behind. $lines=@($text -split "\r?\n") if(-not @($lines|Where-Object {$_ -match '^Application: Mole\.exe\s*$'}).Count){return} $description=[string]($lines|Where-Object {$_ -match '^Description: '}|Select-Object -First 1) $kind=switch -Regex ($description){'stack overflow'{'stack-overflow';break}'FailFast'{'fail-fast';break}'unhandled exception'{'unhandled-exception';break}default{'other'}} $dotnet=$lines|ForEach-Object {if($_ -match '^\.NET Version: (\d{1,3}\.\d{1,3}\.\d{1,5})\s*$'){$Matches[1]}}|Select-Object -First 1 $exceptions=@($lines|ForEach-Object {if($_ -match '^(?:Exception Info: |\s*---> )([A-Za-z_][A-Za-z0-9_.]{0,127}(?:Exception|Error))(?::| \(0x[0-9A-Fa-f]{8}\)|\s*$)'){$Matches[1]}}|Select-Object -First 4) # Schema 20: a native exception that crossed managed frames reads 'exception code c000027b, exception address ...' # (the runtime's DoReportForUnhandledNativeException) and has no type to list; keep the code, never the address. $nativeCode=$lines|ForEach-Object {if($_ -match '^Exception Info: exception code ([0-9A-Fa-f]{1,8}),'){'0x'+([Convert]::ToUInt32($Matches[1],16)).ToString('X8')}}|Select-Object -First 1 $frames=@($lines|ForEach-Object {if($_ -match '^\s+at ((?:System|Microsoft|Mole|WinRT|ABI|Windows|CommunityToolkit|Velopack)\.[A-Za-z0-9_.<>`|]{1,200})\('){$Matches[1]}}) [pscustomobject]@{Kind='RuntimeCrash';Description=$kind;DotNet=$dotnet;Exceptions=$exceptions;NativeCode=$nativeCode;TopFrame=($frames|Select-Object -First 1);MoleFrames=@($frames|Where-Object {$_ -like 'Mole.*'}|Select-Object -First 4)} } function Path-Id($path) { if ([string]::IsNullOrWhiteSpace($path)) { return $null } try { $path = [IO.Path]::GetFullPath(([string]$path).Trim('"')).TrimEnd('\').ToLowerInvariant() } catch { return 'invalid' } if (-not $script:pathIds.ContainsKey($path)) { $script:pathIds[$path] = 'path-' + ($script:pathIds.Count + 1) } return $script:pathIds[$path] } function Error-Status($record) { if ($record.Exception -is [UnauthorizedAccessException] -or $record.CategoryInfo.Category -eq 'PermissionDenied') { return 'denied' } if ($record.CategoryInfo.Category -eq 'ObjectNotFound') { return 'missing' } # WBEM_S_TIMEDOUT (0x40004) and WinRM's operation timeout are a loaded machine, not a missing provider: # a customer's GPU memory query read 'unavailable' with HRESULT 0x40004 (feedback-6, 2026-10-14). $id=[string]$record.FullyQualifiedErrorId if ($record.Exception -is [TimeoutException] -or $record.CategoryInfo.Category -eq 'OperationTimeout' -or $id -match '^HRESULT 0x(?:40004|80338029)\b' -or $id -match '^(?:[A-Za-z]+)?Time(?:d)?out') { return 'timed-out' } return 'unavailable' } function Event-QueryFailure($record) { # Get-WinEvent throws when a filter matches nothing; that is an empty result, not a failure. if ([string]$record.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') { return [pscustomobject]@{Status='no-matching-events';Error=$null} } [pscustomobject]@{Status=(Error-Status $record);Error=(Error-Class $record)} } function Error-Class($record) { # Type and HResult only: an exception message can carry a path or account name. $e=$record.Exception if(-not $e){return $null} # The error id's first segment names the failing check (NoMatchingEventsFound, a WMI HRESULT) # where the exception type alone was a bare Exception 0x80131500 on two different causes. $id=([string]$record.FullyQualifiedErrorId).Split(',')[0] if($id -notmatch '^[A-Za-z0-9 ._-]{1,80}$'){$id=$null} ('{0} 0x{1:X8} {2}' -f $e.GetType().Name,$e.HResult,$id).TrimEnd() } function Text-ScaleFacts([string]$key) { # Windows writes TextScaleFactor only after the slider moves; its absence is the 100% default. try { $item=Get-Item -LiteralPath $key -ErrorAction Stop $value=$item.GetValue('TextScaleFactor') if($null-eq $value){[pscustomobject]@{Kind='TextScaling';Percent=100;Default=$true}} else{[pscustomobject]@{Kind='TextScaling';Percent=[int]$value;Default=$false}} }catch{[pscustomobject]@{Kind='TextScaling';Status=(Error-Status $_);Error=(Error-Class $_)}} } function Network-AdapterBytes([scriptblock]$ReadStatistics) { # Every adapter's counters in one read, keyed by description. Per-adapter -Name reads failed the # whole list when one up physical adapter had no statistics instance (CmdletizationQuery_NotFound_Name, # a 0.24.1 report of 2026-11-26), and -Name also takes wildcards. $bytes=@{} foreach($t in @(& $ReadStatistics)){ if($null-ne $t -and $t.InterfaceDescription){$bytes[[string]$t.InterfaceDescription]=[int64]$t.ReceivedBytes+[int64]$t.SentBytes} } $bytes } function Network-AdapterFacts([int]$WaitMs=2000, [scriptblock]$ReadStatistics={ Get-NetAdapterStatistics -ErrorAction SilentlyContinue }) { # Physical adapters that are up, with the bytes each moved over one short window, to check # which one the Status network label should name (U53). No alias, MAC or address is read. # An adapter whose counters cannot be read keeps its row with BytesMoved null (unknown). $up=@(Get-NetAdapter -Physical -ErrorAction Stop | Where-Object Status -eq 'Up' | Sort-Object ifIndex) $before=Network-AdapterBytes $ReadStatistics Start-Sleep -Milliseconds $WaitMs $after=Network-AdapterBytes $ReadStatistics $rows=@(for($i=0;$i-lt $up.Count;$i++){ $n=$up[$i];$key=[string]$n.InterfaceDescription $moved=$(if($before.ContainsKey($key) -and $after.ContainsKey($key)){[Math]::Max([int64]0,$after[$key]-$before[$key])}else{$null}) [pscustomobject]@{Kind='NetworkAdapter';Id=('net-'+($i+1));Description=$n.InterfaceDescription;Medium=$(switch([int]$n.NdisPhysicalMedium){9{'Wi-Fi'}14{'Ethernet'}8{'Mobile broadband'}default{'Other '+[int]$n.NdisPhysicalMedium}});LinkSpeed=[string]$n.LinkSpeed;BytesMoved=$moved;WindowMs=$WaitMs;Busiest=$false} }) $top=$rows | Sort-Object BytesMoved -Descending | Select-Object -First 1 if($top -and $top.BytesMoved-gt 0){$top.Busiest=$true} $rows } function KV($text, $name) { $m = [regex]::Match([string]$text, '"' + [regex]::Escape($name) + '"\s*"([^"\r\n]*)"') if ($m.Success) { return $m.Groups[1].Value } return $null } function App-Label($name) { if ($name -match '^QQ(?:\s|$)') { return 'QQ' } if ($name -match '^(WeChat|Weixin|\u5fae\u4fe1)(?:\s|$)') { return 'WeChat' } if ($name -match '^Microsoft Edge$') { return 'Edge' } if ($name -match '^Adobe (Premiere Pro|After Effects|Photoshop|Acrobat|Media Encoder|Audition|Illustrator|Lightroom|Creative Cloud|Bridge|Genuine Service)') { return 'Adobe '+$Matches[1] } if ($name -match '^ChatGPT(?:\s|$)') { return 'ChatGPT' } if ($name -match '^Clash Verge(?:\s|$)') { return 'Clash Verge' } if ($name -match '^FlClash(?:\s|$)') { return 'FlClash' } if ($name -match '^Free Download Manager(?:\s|$)') { return 'Free Download Manager' } if ($name -match '^Zed(?:\s|$)') { return 'Zed' } if ($name -match '^Steam$') { return 'Steam' } if ($name -match '^WARDOGS$') { return 'WARDOGS' } if ($name -match 'ACE COMBAT 8') { return 'ACE COMBAT 8' } if ($name -match 'The Witcher 3|\u5deb\u5e083|\u5deb\u5e2b3') { return 'The Witcher 3' } if ($name -match '^Git(?: version)?(?: \d[0-9A-Za-z.+_-]*)?$') { return 'Git' } if ($name -match '^(Gyan\.)?FFmpeg( |$)') { return 'FFmpeg' } return $null } function Executable-Only($command) { $m = [regex]::Match([string]$command, '^\s*"([^"]+\.exe)"|^\s*(.+?\.exe)(?:\s|,|$)', 'IgnoreCase') if ($m.Groups[1].Success) { return $m.Groups[1].Value } if ($m.Groups[2].Success) { return $m.Groups[2].Value } return $null } function Icon-Facts($raw) { $text=[Environment]::ExpandEnvironmentVariables(([string]$raw).Trim());$index=0 if($text -match ',\s*(-?\d+)\s*$') { if(-not [int]::TryParse($Matches[1],[ref]$index)){return [pscustomobject]@{Status='invalid'}} $text=$text.Substring(0,$text.LastIndexOf(',')) } $path=$text.Trim().Trim('"') if(-not $path){return [pscustomobject]@{Status='missing'}} # Never probe a network path embedded in registration metadata. if($path -notmatch '^[A-Za-z]:\\'){return [pscustomobject]@{Status='non-local'}} try { $volume=New-Object IO.DriveInfo ([IO.Path]::GetPathRoot($path)) if($volume.DriveType-ne [IO.DriveType]::Fixed){return [pscustomobject]@{Status='non-local'}} $parents=New-Object System.Collections.Generic.List[string] $parent=[IO.Path]::GetDirectoryName($path) while($parent){$parents.Add($parent);$parent=[IO.Path]::GetDirectoryName($parent)} for($i=$parents.Count-1;$i-ge 0;$i--){if((Get-Item -LiteralPath $parents[$i] -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){return [pscustomobject]@{Status='refused-reparse'}}} $item=Get-Item -LiteralPath $path -Force -ErrorAction Stop $extension=$item.Extension.ToLowerInvariant() [pscustomobject]@{Status='present';Index=$index;Extension=$(if($extension -in @('.exe','.dll','.ico','.png')){$extension}else{'other'});Reparse=[bool]($item.Attributes -band [IO.FileAttributes]::ReparsePoint)} }catch{[pscustomobject]@{Status=(Error-Status $_);Index=$index}} } function Upgrade-Kind([string]$text) { # Mole's update check is itself 'winget upgrade' with only list options, so the # 'Executing command: upgrade' marker cannot tell a check from an install. Classify # from the logged arguments, which are read here and never emitted. $line=[regex]::Match($text,'(?im)Command line Args:\s*(?:"[^"\r\n]*"|\S+)([^\r\n]*)') if(-not $line.Success){return $(if($text -match '\[CLI\s*\]\s+Executing command: upgrade\b'){'unknown'}else{$null})} $tokens=@([regex]::Matches($line.Groups[1].Value,'"[^"]*"|\S+') | ForEach-Object {$_.Value}) if($tokens.Count-eq 0 -or $tokens[0]-notin @('upgrade','update')){return $null} $valued=@('-s','--source','--scope','-a','--architecture','--locale','-o','--log','--override','--custom','-l','--location','--header','--authentication-mode','--authentication-account','--installer-type','-v','--version') $targets=@('--id','--name','--moniker','-q','--query','-m','--manifest','--all','-r','--recurse','-h','--silent','-i','--interactive','--uninstall-previous') for($i=1;$i-lt $tokens.Count;$i++){ $token=$tokens[$i] if($token -in $targets){return 'install'} if($token -in $valued){$i++;continue} if(-not $token.StartsWith('-')){return 'install'} } 'list' } function Winget-LogFacts([string]$text) { # Only fixed package identifiers and numeric codes leave this parser. Mentions do # not prove the target or that Mole, rather than a terminal, launched the command. $known=@('Tencent.QQ.NT','Tencent.QQ','Tencent.WeChat','Tencent.WeType','Git.Git','ClashVergeRev.ClashVergeRev','chen08209.FlClash','SoftDeluxe.FreeDownloadManager','ZedIndustries.Zed','Microsoft.Edge','OpenAI.ChatGPT','Microsoft.PowerShell','Microsoft.PowerShell.Preview') $mentions=@(foreach($id in $known){if($text -match ('(? installer failed: " (LogInstallerFailure, # the code as an unsigned decimal), never "exit code"; 610 sampled logs in 40 reports up to schema 26 held none. $failures=@([regex]::Matches($text,'(?im)\[CLI\s*\]\s+(\S+) installer failed: (\d{1,10})\b') | ForEach-Object {[pscustomobject]@{Type=$(if($_.Groups[1].Value -in @('ShellExecute','MsiInstallProduct','MSIX','Portable','Font')){$_.Groups[1].Value}else{'other'});Code=$_.Groups[2].Value}} | Select-Object -First 8) $exits=@(@($failures | ForEach-Object {$_.Code}) + @([regex]::Matches($text,'(?im)\[CLI\s*\][^\r\n]*\b(?:exit|return) code[: =]+(-?\d{1,10})\b') | ForEach-Object {$_.Groups[1].Value}) | Select-Object -Unique -First 8) # Stage markers as booleans and the log's own first and last timestamps, so a Mole attempt that # never recorded an end can be matched to how far winget got. No log text leaves the parser. $stamps=@([regex]::Matches($text,'(?m)^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})') | ForEach-Object {$_.Groups[1].Value}) $stages=[pscustomobject]@{Download=[bool]($text -match '(?i)download');HashVerified=[bool]($text -match '(?i)hash (?:verified|matched|match)|installer hash');InstallerStarted=[bool]($text -match "(?i)starting package install|installer (?:start|launch)|ShellExecuteEx|\[CLI\s*\]\s+Starting: '");Elevation=[bool]($text -match '(?i)elevat|requires? admin|run ?as admin');Cancelled=[bool]($text -match '(?i)cancel');Succeeded=[bool]($text -match '(?i)successfully installed|installed successfully|During package install, \d+ changes to ARP were observed')} # Schema 13: Edge's vendor download took exactly ten minutes on a 0.13.0 report (2026-10-16) with nothing to say # whether Delivery Optimization stalled first. The downloader's name and the first and last download line times. # winget writes " downloading from url: " ("WinINet downloading from url", VM 2026-10-16); its own # index refreshes come from cdn.winget.microsoft.com and are not the installer. "Forcing use of wininet" means # Delivery Optimization was skipped (a proxy). The Delivery Optimization line's wording is not yet seen in a log. $installerLines=@([regex]::Matches($text,'(?im)^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})[^\r\n]*?\b(WinINet|DeliveryOptimization|Delivery Optimization|DO)\b downloading from url: (?!https?://cdn\.winget\.microsoft\.com/)')) $downloads=@($installerLines | ForEach-Object {$_.Groups[1].Value}) $downloader=@($installerLines | ForEach-Object {if($_.Groups[2].Value -match '(?i)^wininet$'){'wininet'}else{'delivery-optimization'}} | Select-Object -Unique) [pscustomobject]@{Downloaders=$downloader;DeliveryOptimizationSkipped=[bool]($text -match '(?i)forcing use of wininet');DownloadFirstLocal=$(if($downloads.Count){$downloads[0]}else{$null});DownloadLastLocal=$(if($downloads.Count){$downloads[-1]}else{$null});KnownPackageMentions=$mentions;ObservedHexCodes=$codes;ObservedInstallerCodes=$exits;InstallerFailures=$failures;UpgradeCommandObserved=[bool]($text -match '\[CLI\s*\]\s+Executing command: upgrade\b');UpgradeKind=(Upgrade-Kind $text);FirstLocal=$(if($stamps.Count){$stamps[0]}else{$null});LastLocal=$(if($stamps.Count){$stamps[-1]}else{$null});Stages=$stages} } function Public-PackageId($r) { # Schema 13: an id from a public catalog (winget, msstore) names a package anyone can look up, so it leaves # as is; an id from any other source stays a report-local alias (a 0.13.0 report was all 'other', 2026-10-16). $id=[string]$r.PackageId if([string]$r.Source-ceq 'winget' -and $id.Length-le 96 -and $id -cmatch '^[A-Za-z0-9][A-Za-z0-9_+-]*(\.[A-Za-z0-9_+-]+){1,5}$'){return $id} if([string]$r.Source-ceq 'msstore' -and $id -cmatch '^[A-Z0-9]{12}$'){return $id} $null } function Check-Count($value) { if($null-ne $value -and ([string]$value) -match '^\d{1,6}$'){[int]$value}else{$null} } function Mole-UpdateFacts([string]$text) { $packageIds=@{} $known=@('Tencent.QQ.NT','Tencent.QQ','Tencent.WeChat','Git.Git','ClashVergeRev.ClashVergeRev','chen08209.FlClash','SoftDeluxe.FreeDownloadManager','ZedIndustries.Zed','Microsoft.Edge','Tencent.WeType','Microsoft.PowerShell','Microsoft.PowerShell.Preview') # The whole capped file (128 KiB, about 500 rows): the last 100 rows had lost the first half of an Update All. foreach($line in @($text -split "`n" | Select-Object -Last 600)) { try { $r=$line | ConvertFrom-Json if([string]$r.PackageId -ceq 'mole.check') { # One row per update check: applied, skipped while an update ran, discarded, or unanswered. if($r.Stage -notmatch '^check-(applied|skipped-busy|discarded|unanswered)$' -or [string]$r.State -notin @('User','Silent')){continue} $utc=(Json-Time $r.Utc).ToUniversalTime() if($utc -lt [DateTimeOffset]::UtcNow.AddDays(-7)){continue} [pscustomobject]@{Kind='UpdateCheck';Utc=$utc.ToString('o');Result=([string]$r.Stage).Substring(6);Trigger=([string]$r.State).ToLowerInvariant();Offered=(Check-Count $r.Offered);Disproved=(Check-Count $r.Disproved)} continue } # An update outside the fixed list keeps its stages and timing, under its public winget or msstore id # since schema 13 and under 'other' otherwise: a stuck .NET Runtime attempt was dropped whole, the one # row that would have shown where it stopped (2026-10-11). $public=Public-PackageId $r $package=if($r.PackageId -in $known){$r.PackageId}elseif($public){$public}else{'other'} $identity=[string]$r.PackageId if(-not $packageIds.ContainsKey($identity)){$packageIds[$identity]='app-'+($packageIds.Count+1)} if($r.Stage -notmatch '^(started|finished|readback-unconfirmed|exception|quit-(confirmation|approved|declined|completed|refused)|installer-start|started-after-review|download-(exit|done)|elevation-(requested|started)|cancelled|abandoned|holder-probe|provider-[A-Za-z]+)$'){continue} if($r.State -notmatch '^(Idle|Queued|Running|AppRunning|Done|DoneRestart|Current|Unavailable|Failed|UpdatesItself|Blocked)$'){continue} $utc=(Json-Time $r.Utc).ToUniversalTime() if($utc -lt [DateTimeOffset]::UtcNow.AddDays(-7)){continue} $versions=@(foreach($v in @($r.Version,$r.Available,$r.InstalledVersion)){if($null-ne $v -and $v -cmatch '^[A-Za-z0-9._+-]{1,128}$'){$v}else{$null}}) $row=[pscustomobject]@{Kind='MoleUpdate';AppId=$packageIds[$identity];Utc=$utc.ToString('o');Attempt=([guid]$r.Attempt).ToString();PackageId=$package;Version=$versions[0];Available=$versions[1];InstalledVersion=$versions[2];Stage=$r.Stage;State=$r.State;ExitCode=$(if($null-ne $r.ExitCode){[int]$r.ExitCode}else{$null});Source=$(if([string]$r.Source -in @('winget','msstore')){[string]$r.Source}elseif($r.Source){'other'}else{$null})} # Schema 28, `failed` from 29: a files-in-use lookup's counts (holders found, files enumerated, which cap cut it short or `failed`, Windows would not answer), never names or paths. if($r.Stage -ceq 'holder-probe'){$row|Add-Member -NotePropertyName Holders -NotePropertyValue (Check-Count $r.Holders);$row|Add-Member -NotePropertyName Walked -NotePropertyValue (Check-Count $r.Walked);$row|Add-Member -NotePropertyName Cap -NotePropertyValue $(if([string]$r.Cap -cin @('none','files','time','both','failed')){[string]$r.Cap}else{$null})} $row }catch { } } } function Update-PackageKey($record) { if($record.PackageId-ne 'other'){'p|'+$record.PackageId}else{'a|'+$record.AppId} } function Elevation-WaitSeconds($group) { # Longest wait between asking for UAC consent and the elevated installer starting (one attempt waited 8.7 h). $longest=$null;$asked=$null foreach($r in @($group | Sort-Object {[DateTimeOffset]::Parse($_.Utc)})) { if($r.Stage-eq 'elevation-requested'){$asked=[DateTimeOffset]::Parse($r.Utc)} elseif($r.Stage-eq 'elevation-started' -and $asked){$gap=[int]([DateTimeOffset]::Parse($r.Utc)-$asked).TotalSeconds;if($null-eq $longest -or $gap-gt $longest){$longest=$gap};$asked=$null} } $longest } function Update-AttemptFacts($records) { $groups=@($records | Group-Object Attempt) # The latest time each package (or report-local alias for unlisted packages) finished Done. $doneAt=@{} foreach($r in @($records | Where-Object {$_.Stage-eq 'finished' -and $_.State-eq 'Done'})) { $key=Update-PackageKey $r;$at=[DateTimeOffset]::Parse($r.Utc) if(-not $doneAt.ContainsKey($key) -or $at-gt $doneAt[$key]){$doneAt[$key]=$at} } $unfinished=0;$superseded=0;$longest=$null foreach($group in $groups) { $wait=Elevation-WaitSeconds $group.Group if($null-ne $wait -and ($null-eq $longest -or $wait-gt $longest)){$longest=$wait} $last=$group.Group | Sort-Object {[DateTimeOffset]::Parse($_.Utc)} | Select-Object -Last 1 if(@($group.Group | Where-Object Stage -eq 'finished').Count){continue} $key=Update-PackageKey $last if($doneAt.ContainsKey($key) -and $doneAt[$key]-gt [DateTimeOffset]::Parse($last.Utc)){$state='superseded-by-success';$superseded++} else{$state=if($last.Stage-eq 'abandoned'){'interrupted-on-exit'}else{'completion-unknown'};$unfinished++} [pscustomobject]@{Kind='UnfinishedAttempt';Attempt=$group.Name;AppId=$last.AppId;PackageId=$last.PackageId;Status=$state;LastStage=$last.Stage;LastState=$last.State;ElevationWaitSeconds=$wait;MinutesSinceLast=[int]([DateTimeOffset]::UtcNow-[DateTimeOffset]::Parse($last.Utc)).TotalMinutes} } if($groups.Count){[pscustomobject]@{Kind='UpdateAttemptSummary';Attempts=$groups.Count;Unfinished=$unfinished;Superseded=$superseded;LongestElevationWaitSeconds=$longest}} } function Read-TailText([string]$path, [int]$MaxBytes) { # The newest bytes of a local, non-redirected file, opened for read beside its writer. $path=Local-MetadataPath $path if(-not $path){throw 'Metadata refused'} if((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Metadata refused'} $stream=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)) try { $start=[Math]::Max(0L,$stream.Length-$MaxBytes);[void]$stream.Seek($start,[IO.SeekOrigin]::Begin) $buffer=New-Object byte[] ([int]($stream.Length-$start));$used=0 while($used-lt $buffer.Length){$n=$stream.Read($buffer,$used,$buffer.Length-$used);if($n-le 0){break};$used+=$n} $text=[Text.Encoding]::UTF8.GetString($buffer,0,$used) # A cut first line is dropped rather than parsed. if($start-gt 0){$cut=$text.IndexOf("`n");$text=if($cut-ge 0){$text.Substring($cut+1)}else{''}} [pscustomobject]@{Text=$text;Partial=($start-gt 0)} }finally{$stream.Dispose()} } function Code($value){ if($value-is [string] -and $value-cmatch '^[a-z0-9-]{1,40}$'){$value}else{$null} } function Shader-RuleIds { # Mole's GPU shader cache rules (CleanRule.OptIn, U88); a clean receipt's path Kind is the rule id. @('d3d-shader-cache','dx-pipeline-cache','nvidia-dxcache','nvidia-glcache','nvidia-nvcache','nvidia-optix-cache','nvidia-perdriver-dxcache','nvidia-perdriver-glcache','nvidia-computecache','amd-dxcache','amd-dxccache','amd-glcache','amd-vkcache','intel-shadercache','vulkan-cache','nvidia-nvcache-system','steam-shadercache') } function Shader-CleanFacts($valid) { # What Mole's own cleans removed or left of the shader caches over the whole retained log. Receipts list # paths only since 2026-10-16 and at most 40 per clean, so a run without paths is counted, never read as none. $ids=Shader-RuleIds $runs=0;$withPaths=0;$shaderRuns=0;$last=$null;$bytes=0L;$kinds=[ordered]@{};$left=0;$permanent=0;$recycled=0 foreach($r in $valid){ if($r.Operation-cne 'clean' -or $r.Stage-cne 'finished'){continue} $runs++ if($null-eq $r.Paths){continue} $withPaths++;$hit=$false foreach($p in @($r.Paths)){ if($p-isnot [Management.Automation.PSCustomObject] -or $p.Kind-isnot [string] -or $p.Kind-cnotin $ids){continue} if($p.Result-ceq 'removed'){ $hit=$true;$k=[string]$p.Kind;if(-not $kinds.Contains($k)){$kinds[$k]=0};$kinds[$k]++ if($p.Bytes-is [ValueType] -and $p.Bytes-isnot [bool] -and [long]$p.Bytes-ge 0){$bytes+=[long]$p.Bytes} if($p.Mode-ceq 'recycle'){$recycled++}else{$permanent++} } else {$left++} } if($hit){$shaderRuns++;$last=$r.Utc} } [pscustomobject]@{Kind='ShaderCleans';CleanRuns=$runs;CleanRunsWithPaths=$withPaths;RunsThatRemovedShaderCaches=$shaderRuns;LastRemovedUtc=$last;RemovedBytes=$bytes;RemovedPermanently=$permanent;RemovedToRecycleBin=$recycled;LeftBehind=$left;ByRule=$(if($kinds.Count){[pscustomobject]$kinds}else{$null})} } function Shader-Locations { # Fixed GPU shader cache folders: Mole's own rules plus those it does not clean, so a rebuild can be dated # against Mole's cleans, driver changes and Windows' own cleanup. Ids leave, never the path. $local=$env:LOCALAPPDATA;$roaming=$env:APPDATA;$data=$env:ProgramData;$temp=$env:TEMP $low=if($env:USERPROFILE){Join-Path $env:USERPROFILE 'AppData\LocalLow'}else{$null} @( @('d3d-shader-cache',$local,'D3DSCache',$true), @('dx-pipeline-cache',$local,'Microsoft\DirectX Shader Cache',$true), @('nvidia-dxcache',$local,'NVIDIA\DXCache',$true), @('nvidia-glcache',$local,'NVIDIA\GLCache',$true), @('nvidia-nvcache',$local,'NVIDIA Corporation\NV_Cache',$true), @('nvidia-optix-cache',$local,'NVIDIA\OptixCache',$true), @('nvidia-perdriver',$low,'NVIDIA\PerDriverVersion',$false), @('nvidia-perdriver-dxcache',$low,'NVIDIA\PerDriverVersion\DXCache',$true), @('nvidia-perdriver-glcache',$low,'NVIDIA\PerDriverVersion\GLCache',$true), @('nvidia-computecache',$roaming,'NVIDIA\ComputeCache',$true), @('nvidia-nvcache-system',$data,'NVIDIA Corporation\NV_Cache',$true), @('nvidia-temp-nvcache',$temp,'NVIDIA Corporation\NV_Cache',$false), @('amd-dxcache',$local,'AMD\DXCache',$true), @('amd-dxccache',$local,'AMD\DxcCache',$true), @('amd-glcache',$local,'AMD\GLCache',$true), @('amd-vkcache',$local,'AMD\VkCache',$true), @('intel-shadercache',$local,'Intel\ShaderCache',$true), @('intel-locallow-shadercache',$low,'Intel\ShaderCache',$false), @('vulkan-cache',$local,'VulkanCache',$true) ) | ForEach-Object {[pscustomobject]@{Id=$_[0];Root=$_[1];Relative=$_[2];MoleRule=$_[3]}} } function Shader-CacheFacts { foreach($l in @(Shader-Locations)){ if([string]::IsNullOrWhiteSpace($l.Root)){[pscustomobject]@{Kind='ShaderCache';Id=$l.Id;MoleRule=$l.MoleRule;Status='unavailable'};continue} $path=Join-Path $l.Root $l.Relative $m=[MoleFeedbackNative]::Scan($path,2000,300000) # A clean empties the folder and keeps it; a recreated folder dates whatever removed it whole. $created=$null;if($m.Status-notin @('missing','denied','refused-reparse','refused-root-or-network','refused-nonfixed','unavailable')){try{$created=[IO.Directory]::GetCreationTimeUtc($path).ToString('o')}catch{}} [pscustomobject]@{Kind='ShaderCache';Id=$l.Id;MoleRule=$l.MoleRule;Status=$m.Status;Files=$m.Files;Directories=$m.Directories;Bytes=$m.LogicalBytes;OldestWriteUtc=$m.OldestWriteUtc;NewestWriteUtc=$m.NewestWriteUtc;FolderCreatedUtc=$created} } } function Steam-ShaderFacts { # Each game's steamapps\shadercache\ in every library: the appid is Steam's public id, no game name # or library path leaves. Roots as the Apps section finds them, plus Steam's own registry path. $roots=New-Object System.Collections.Generic.List[string] foreach($key in @('HKCU:\Software\Valve\Steam','HKLM:\SOFTWARE\WOW6432Node\Valve\Steam','HKLM:\SOFTWARE\Valve\Steam')){ try{$k=Get-ItemProperty $key -ErrorAction Stop;foreach($v in @($k.SteamPath,$k.InstallPath)){if($v){$roots.Add(([string]$v).Replace('/','\'))}}}catch{} } foreach($root in @('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*','HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*','HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*')){ foreach($e in @(Get-ItemProperty $root -ErrorAction SilentlyContinue)){ $command=Executable-Only $e.UninstallString if($command-match '\\steam\.exe$'){$roots.Add([IO.Path]::GetDirectoryName($command))} } } $libraries=New-Object System.Collections.Generic.List[string] foreach($root in @(Unique-LocalPaths $roots)){ $libraries.Add($root) try{$vdf=Read-SmallText (Join-Path $root 'steamapps\libraryfolders.vdf') -LocalOnly;foreach($m in [regex]::Matches([string]$vdf,'"path"\s*"([^"\r\n]+)"')){$libraries.Add($m.Groups[1].Value.Replace('\\','\'))}}catch{} } $unique=@(Unique-LocalPaths $libraries|Select-Object -First 16) [pscustomobject]@{Kind='SteamShaderLibraries';Status=$(if($roots.Count){'complete'}else{'no-steam'});Libraries=$unique.Count} foreach($library in $unique){ $id=Path-Id $library try{ $cache=Local-MetadataPath (Join-Path $library 'steamapps\shadercache') if(-not $cache -or -not (Test-Path -LiteralPath $cache -PathType Container)){[pscustomobject]@{Kind='SteamShaderLibrary';LibraryId=$id;Status='missing'};continue} $games=@(Get-ChildItem -LiteralPath $cache -Directory -Force -ErrorAction Stop|Where-Object {$_.Name-match '^\d{1,10}$' -and -not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint)}) $rows=@(foreach($g in @($games|Sort-Object LastWriteTimeUtc -Descending|Select-Object -First 48)){ $m=[MoleFeedbackNative]::Scan($g.FullName,1000,100000) [pscustomobject]@{Kind='SteamShaderCache';LibraryId=$id;AppId=$g.Name;Installed=(Test-Path -LiteralPath (Join-Path $library ('steamapps\appmanifest_'+$g.Name+'.acf')) -PathType Leaf);Status=$m.Status;Files=$m.Files;Bytes=$m.LogicalBytes;OldestWriteUtc=$m.OldestWriteUtc;NewestWriteUtc=$m.NewestWriteUtc;FolderCreatedUtc=$g.CreationTimeUtc.ToString('o')} }) [pscustomobject]@{Kind='SteamShaderLibrary';LibraryId=$id;Status='complete';Games=$games.Count;Listed=$rows.Count} $rows }catch{[pscustomobject]@{Kind='SteamShaderLibrary';LibraryId=$id;Status=(Error-Status $_)}} } } function Gpu-Vendor([string]$instance) { if($instance-match 'VEN_([0-9A-Fa-f]{4})'){switch($Matches[1].ToUpperInvariant()){'10DE'{'nvidia'}'1002'{'amd'}'1022'{'amd'}'8086'{'intel'}'1414'{'microsoft'}'5143'{'qualcomm'}default{'other-pci'}}} elseif($instance-match '^ROOT\\'){'virtual'} else{'other'} } function Driver-Provider([string]$provider) { switch -Regex ($provider){'^$'{$null;break}'NVIDIA'{'nvidia';break}'Intel'{'intel';break}'Advanced Micro Devices|^AMD|ATI Technologies'{'amd';break}'^Microsoft'{'microsoft';break}'Qualcomm'{'qualcomm';break}default{'other'}} } function Gpu-DriverFacts { # The display adapters' current driver and when Windows installed it: a new driver starts every game's # shader caches over, which looks the same to a player as a clean. $devices=@(Get-PnpDevice -Class Display -PresentOnly -ErrorAction Stop) if(-not $devices.Count){[pscustomobject]@{Kind='GpuDriver';Status='no-instances'};return} $i=0 foreach($d in $devices){ $i++;$p=@{} try{foreach($row in @(Get-PnpDeviceProperty -InstanceId $d.InstanceId -KeyName 'DEVPKEY_Device_DriverVersion','DEVPKEY_Device_DriverDate','DEVPKEY_Device_InstallDate','DEVPKEY_Device_FirstInstallDate','DEVPKEY_Device_LastArrivalDate','DEVPKEY_Device_DriverProvider' -ErrorAction Stop)){$p[[string]$row.KeyName]=$row.Data}}catch{} $times=@{};foreach($name in @('InstallDate','FirstInstallDate','LastArrivalDate')){$v=$p['DEVPKEY_Device_'+$name];$times[$name]=$(if($v-is [DateTime] -and $v.Year-ge 2000){$v.ToUniversalTime().ToString('o')}else{$null})} $date=$p['DEVPKEY_Device_DriverDate'] [pscustomobject]@{Kind='GpuDriver';Id=('gpu-'+$i);Vendor=(Gpu-Vendor $d.InstanceId);Provider=(Driver-Provider ([string]$p['DEVPKEY_Device_DriverProvider']));DriverVersion=(Safe-Version $p['DEVPKEY_Device_DriverVersion']);DriverDate=$(if($date-is [DateTime]){$date.ToString('yyyy-MM-dd')}else{$null});InstalledUtc=$times.InstallDate;FirstInstalledUtc=$times.FirstInstallDate;LastArrivalUtc=$times.LastArrivalDate} } } function Driver-ChangeFacts($xmlTexts) { # Kernel-PnP 400 for the Display class: each driver install or reconfiguration with its version and date, # never the device instance path or INF name. foreach($text in @($xmlTexts)){ try{ $x=[xml]$text;$data=@{};foreach($n in @($x.Event.EventData.Data)){$data[[string]$n.Name]=[string]$n.'#text'} if($data['ClassGuid']-ne '{4d36e968-e325-11ce-bfc1-08002be10318}'){continue} $at=[DateTimeOffset]::Parse([string]$x.Event.System.TimeCreated.SystemTime,[Globalization.CultureInfo]::InvariantCulture) $date=$null;$dd=[DateTime]::MinValue if([DateTime]::TryParseExact([string]$data['DriverDate'],'MM/dd/yyyy',[Globalization.CultureInfo]::InvariantCulture,[Globalization.DateTimeStyles]::None,[ref]$dd)){$date=$dd.ToString('yyyy-MM-dd')} [pscustomobject]@{Kind='GpuDriverChange';Utc=$at.ToUniversalTime().ToString('o');Vendor=(Gpu-Vendor $data['DeviceInstanceId']);Provider=(Driver-Provider $data['DriverProvider']);DriverVersion=(Safe-Version $data['DriverVersion']);DriverDate=$date;Inbox=($data['DriverInbox']-eq 'true');DeviceUpdated=($data['DeviceUpdated']-eq 'true');Status=$(if($data['Status']-match '^0x[0-9A-Fa-f]{1,8}$'){$data['Status']}else{$null})} }catch{} } } function Storage-SenseFacts { # Storage Sense runs Disk Cleanup's handlers on its own, the DirectX shader cache among them. function Dword($key,[string]$name){$v=$key.GetValue($name);if($v-is [int]){$v}else{$null}} try{ $k=Get-Item -LiteralPath 'HKCU:\Software\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy' -ErrorAction Stop $on=Dword $k '01';$cadence=Dword $k '2048';$temp=Dword $k '04' [pscustomobject]@{Kind='StorageSense';Enabled=$(if($null-ne $on){$on-eq 1}else{$null});Cadence=$(if($null-eq $cadence){$null}else{switch($cadence){0{'low-disk'}1{'daily'}7{'weekly'}30{'monthly'}default{'other'}}});CleansTemporaryFiles=$(if($null-ne $temp){$temp-eq 1}else{$null})} }catch{[pscustomobject]@{Kind='StorageSense';Status=(Error-Status $_)}} try{ $k=Get-Item -LiteralPath 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\StorageSense' -ErrorAction Stop [pscustomobject]@{Kind='StorageSensePolicy';AllowGlobal=(Dword $k 'AllowStorageSenseGlobal');GlobalCadence=(Dword $k 'ConfigStorageSenseGlobalCadence');AllowTemporaryFilesCleanup=(Dword $k 'AllowStorageSenseTemporaryFilesCleanup')} }catch{[pscustomobject]@{Kind='StorageSensePolicy';Status=(Error-Status $_)}} } function Disk-CleanupFacts { # The DirectX Shader Cache handler: Autorun 1 lets automatic cleanup (SilentCleanup, Storage Sense) empty it. try{ $k=Get-Item -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\D3D Shader Cache' -ErrorAction Stop $auto=$k.GetValue('Autorun') [pscustomobject]@{Kind='DiskCleanupShaderHandler';Autorun=$(if($auto-is [int]){$auto}else{$null});SageSetPresetsSelecting=@($k.GetValueNames()|Where-Object {$_-match '^StateFlags\d{4}$' -and $k.GetValue($_)-eq 2}).Count} }catch{[pscustomobject]@{Kind='DiskCleanupShaderHandler';Status=(Error-Status $_)}} try{ foreach($t in @(Get-ScheduledTask -TaskPath '\Microsoft\Windows\DiskCleanup\' -ErrorAction Stop)){ $info=$t|Get-ScheduledTaskInfo -ErrorAction SilentlyContinue $run=if($info -and $info.LastRunTime-is [DateTime] -and $info.LastRunTime.Year-ge 2000){$info.LastRunTime.ToUniversalTime().ToString('o')}else{$null} [pscustomobject]@{Kind='DiskCleanupTask';Task=$(if($t.TaskName-match '^[A-Za-z]{1,40}$'){$t.TaskName}else{'other'});State=[string]$t.State;LastRunUtc=$run;LastResult=$(if($info){'0x{0:X8}' -f [uint32]$info.LastTaskResult}else{$null});Mode=$(if(@($t.Actions|Where-Object {[string]$_.Arguments-match '/autocleanstoragesense'}).Count){'storage-sense'}elseif(@($t.Actions|Where-Object {[string]$_.Arguments-match '/autoclean'}).Count){'autoclean'}else{'other'})} } }catch{[pscustomobject]@{Kind='DiskCleanupTask';Status=(Error-Status $_)}} try{ # Other scheduled tasks that run cleanmgr (a /sagerun preset, a tool's own schedule): counts only. $others=@(Get-ScheduledTask -ErrorAction Stop|Where-Object {$_.TaskPath-ne '\Microsoft\Windows\DiskCleanup\' -and @($_.Actions|Where-Object {[string]$_.Execute-match 'cleanmgr(\.exe)?"?$'}).Count}) [pscustomobject]@{Kind='CleanmgrTasks';Count=$others.Count;Enabled=@($others|Where-Object {[string]$_.State-ne 'Disabled'}).Count} }catch{[pscustomobject]@{Kind='CleanmgrTasks';Status=(Error-Status $_)}} } function Cleaner-Presence { # Other tools that may empty shader caches or replace the GPU driver: fixed labels, installed or running only. $tools=@( @('CCleaner','^CCleaner',@('CCleaner64','CCleaner')), @('360','^360(?:\s|Total|Safe|\u5b89\u5168|\u6740\u6bd2)',@('360Tray','360sd','ZhuDongFangYu')), @('Tencent PC Manager','\u7535\u8111\u7ba1\u5bb6|Tencent PC Manager',@('QQPCTray','QQPCRTP')), @('Huorong','\u706b\u7ed2',@('HipsTray','HipsDaemon')), @('Wise Care 365','^Wise Care 365',@('WiseCare365')), @('Wise Disk Cleaner','^Wise Disk Cleaner',@('WiseDiskCleaner')), @('BleachBit','^BleachBit',@('bleachbit')), @('Glary Utilities','^Glary Utilities',@()), @('Advanced SystemCare','^Advanced SystemCare',@('ASC')), @('Razer Cortex','^Razer Cortex',@('RazerCortex')), @('Dism++','^Dism\+\+',@('Dism++x64','Dism++ARM64')), @('NVIDIA App','^NVIDIA App',@('NVIDIA app')), @('GeForce Experience','^NVIDIA GeForce Experience',@('NVIDIA GeForce Experience')), @('AMD Software','^AMD Software',@('RadeonSoftware')), @('Intel Driver & Support Assistant','^Intel.{0,4} Driver (?:&|and) Support Assistant',@('DSATray')), @('Driver Booster','^(?:IObit )?Driver Booster',@('DriverBooster')), @('Driver Easy','^Driver Easy',@('DriverEasy')), @('Driver Genius','\u9a71\u52a8\u7cbe\u7075|^Driver Genius',@('DriverGenius')), @('Drive The Life','\u9a71\u52a8\u4eba\u751f',@('DTLAgent')) ) $names=New-Object System.Collections.Generic.List[string] foreach($root in @('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*','HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*','HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*')){ foreach($e in @(Get-ItemProperty $root -ErrorAction SilentlyContinue)){if($e.DisplayName){$names.Add([string]$e.DisplayName)}} } $running=New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) foreach($proc in @(Get-Process -ErrorAction SilentlyContinue)){[void]$running.Add($proc.ProcessName)} $found=0 foreach($t in $tools){ $installed=@($names|Where-Object {$_-match $t[1]}).Count-gt 0 $live=@($t[2]|Where-Object {$running.Contains($_)}).Count-gt 0 if($installed -or $live){$found++;[pscustomobject]@{Kind='OtherCleaner';Tool=$t[0];Installed=$installed;Running=$live}} } if($env:LOCALAPPDATA -and (Test-Path -LiteralPath (Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.MicrosoftPCManager_8wekyb3d8bbwe') -PathType Container)){$found++;[pscustomobject]@{Kind='OtherCleaner';Tool='Microsoft PC Manager';Installed=$true;Running=$running.Contains('MSPCManager')}} [pscustomobject]@{Kind='OtherCleaners';Checked=($tools.Count+1);Found=$found} } function Operation-PathFacts($entry, $aliases) { # A recorded path leaves only as the known folder it sits in, a report-local alias and its depth below # that folder; the rest of the path and any display name stay on the PC. $raw=[string]$entry.Path $role='other';$depth=$null;$alias=$null # Startup rows record a service or task id when there is no program, and End process an image name alone: # GetFullPath would join those to the current folder and give them a made-up role and depth. if(-not [string]::IsNullOrWhiteSpace($raw) -and $raw.Trim('"') -notmatch '^[A-Za-z]:\\') {$role='not-a-path';$raw=$null} if(-not [string]::IsNullOrWhiteSpace($raw)) { try { $full=[IO.Path]::GetFullPath($raw.Trim('"')).TrimEnd('\') $roles=[ordered]@{Temp=$env:TEMP;LocalAppData=$env:LOCALAPPDATA;RoamingAppData=$env:APPDATA;Profile=$env:USERPROFILE;ProgramFilesX86=${env:ProgramFiles(x86)};ProgramFiles=$env:ProgramFiles;ProgramData=$env:ProgramData;Windows=$env:SystemRoot} foreach($name in $roles.Keys){ $root=[string]$roles[$name] if($root.Length-lt 3){continue} $root=$root.TrimEnd('\') if($full.Equals($root,[StringComparison]::OrdinalIgnoreCase) -or $full.StartsWith($root+'\',[StringComparison]::OrdinalIgnoreCase)){ $role=$name;$depth=@($full.Substring($root.Length).Split('\')|Where-Object {$_}).Count;break } } if($role-eq 'other' -and $full -match '^[A-Za-z]:\\'){$role='other-local';$depth=@($full.Substring(3).Split('\')|Where-Object {$_}).Count} $key=$full.ToLowerInvariant() if(-not $aliases.ContainsKey($key)){$aliases[$key]='op-path-'+($aliases.Count+1)} $alias=$aliases[$key] }catch{$role='invalid'} } $bytes=$null;if($entry.Bytes-is [ValueType] -and $entry.Bytes-isnot [bool] -and [long]$entry.Bytes-ge 0){$bytes=[long]$entry.Bytes} [pscustomobject]@{Root=$role;Id=$alias;Depth=$depth;Bytes=$bytes;Kind=(Code $entry.Kind);Result=(Code $entry.Result);Reason=(Code $entry.Reason);Mode=$(if($entry.Mode-cin @('recycle','permanent','mixed')){[string]$entry.Mode}else{$null});ExitCode=$(if($entry.ExitCode-is [ValueType] -and $entry.ExitCode-isnot [bool]){[int]$entry.ExitCode}else{$null});DurationMs=$(if($entry.DurationMs-is [ValueType] -and $entry.DurationMs-isnot [bool] -and [long]$entry.DurationMs-ge 0){[long]$entry.DurationMs}else{$null})} } function Safe-Int($value) { # A number a receipt wrote (an exit code or Win32 error may be negative or large); anything else is unknown. if($null-ne $value -and $value -is [ValueType] -and $value -isnot [bool] -and $value -isnot [char]){try{[int]$value}catch{$null}}else{$null} } function End-Facts($facts) { # Schema 21: why a Status End process did not end the process, as Win32 errors and the target's elevation. if($facts-isnot [Management.Automation.PSCustomObject]){return $null} [pscustomobject]@{OpenError=(Safe-Int $facts.OpenError);TerminateError=(Safe-Int $facts.TerminateError);Elevated=$(if([string]$facts.Elevated -cin @('yes','no','unknown')){[string]$facts.Elevated}else{'unknown'});Respawned=$(if($facts.Respawned-is [bool]){$facts.Respawned}else{$null})} } function Ignored-UpdateFacts([string]$entry, [int]$number) { # An ignore key is `Key`, `Key|Version` or `Key|Name|Version`; Key is a bare winget or Store id, or scoop:, scoop-global:, choco:. $parts=$entry.Split('|');$key=$parts[0];$manager='winget';$id=$key if($key -cmatch '^(scoop-global|scoop|choco):(.+)$'){$manager=$Matches[1];$id=$Matches[2]} $source=$null;$public=$null if($manager-eq 'winget'){ if($id.Length-le 96 -and $id -cmatch '^[A-Za-z0-9][A-Za-z0-9_+-]*(\.[A-Za-z0-9_+-]+){1,5}$'){$public=$id;$source='winget'} elseif($id -cmatch '^[A-Z0-9]{12}$'){$public=$id;$source='msstore'} } $version=if($parts.Count-ge 2 -and $parts[$parts.Count-1] -cmatch '^[A-Za-z0-9._+-]{1,128}$'){$parts[$parts.Count-1]}else{$null} [pscustomobject]@{Kind='IgnoredUpdate';Alias=('ignored-'+$number);Manager=$manager;Source=$source;PackageId=$public;Scope=$(if($parts.Count-ge 3){'row'}elseif($parts.Count-eq 2){'version'}else{'any-version'});Version=$version} } function Operation-Facts([string]$text, [DateTimeOffset]$Now = [DateTimeOffset]::UtcNow) { # The app's operations.jsonl contract, the whole retained log (live file plus its rotated half). Every # field is validated and rebuilt; unknown keys never leave, and paths leave only as Operation-PathFacts. $valid=New-Object System.Collections.Generic.List[object];$lines=0;$invalid=0;$aliases=@{} function Count-OrNull($value,[type]$type){ if($null-eq $value){return $null};if(-not ($value-is [ValueType]) -or $value-is [bool]){throw 'bad'};$n=$value -as $type;if($null-eq $n -or $n-lt 0){throw 'bad'};$n } foreach($line in @($text -split "\r?\n")) { if([string]::IsNullOrWhiteSpace($line)){continue};$lines++ try { $r=$line|ConvertFrom-Json $at=[DateTimeOffset]::MinValue $at=Json-Time $r.Utc;if($null-eq $at){throw 'bad'} if($r.Operation-cnotin @('clean','uninstall','optimize','analyze-recycle','startup','end-process') -or $r.Stage-cnotin @('started','finished')){throw 'bad'} if($null-ne $r.Result -and $r.Result-cnotin @('done','partial','failed','cancelled','refused','abandoned')){throw 'bad'} $attempt=([guid][string]$r.Attempt).ToString() $reasons=$null if($null-ne $r.Reasons) { if($r.Reasons-isnot [Management.Automation.PSCustomObject]){throw 'bad'} $reasons=[ordered]@{} foreach($p in @($r.Reasons.PSObject.Properties|Select-Object -First 16)){ if($p.Name-cmatch '^[a-z0-9-]{1,40}$' -and $p.Value-is [ValueType] -and $p.Value-isnot [bool] -and [long]$p.Value-ge 0){$reasons[$p.Name]=[int]$p.Value} } } # Lines from builds before 2026-10-16 have no Mode, Action or Paths: they read as null. Paths are kept raw # here and turned into facts only for the exported rows below: doing it for every line of a full 4 MiB log # took 27.7 s of the section's 30 s in Windows PowerShell 5.1 (VM, 2026-10-16). $valid.Add([pscustomobject]@{Kind='Operation';Utc=$at.ToUniversalTime().ToString('o');Version=(Safe-Version $r.Version);Operation=[string]$r.Operation;Attempt=$attempt;Stage=[string]$r.Stage;Result=$(if($null-ne $r.Result){[string]$r.Result}else{$null});Items=(Count-OrNull $r.Items ([int]));Succeeded=(Count-OrNull $r.Succeeded ([int]));Failed=(Count-OrNull $r.Failed ([int]));Skipped=(Count-OrNull $r.Skipped ([int]));Bytes=(Count-OrNull $r.Bytes ([long]));Reasons=$(if($null-ne $reasons){[pscustomobject]$reasons}else{$null});DurationMs=(Count-OrNull $r.DurationMs ([long]));Mode=$(if($r.Mode-cin @('recycle','permanent','mixed')){[string]$r.Mode}else{$null});Action=$(if($r.Action-is [string] -and $r.Action-cmatch '^[a-z0-9-]{1,40}$'){[string]$r.Action}else{$null});Paths=$r.Paths;MorePaths=(Count-OrNull $r.MorePaths ([int]));MorePathBytes=(Count-OrNull $r.MorePathBytes ([long]));Holders=$(if($null-ne $r.Holders){,@(@($r.Holders)|Where-Object {$_-is [string] -and $_-cmatch '^[a-z0-9-]{1,40}$'}|Select-Object -First 8)}else{$null});Tasks=$(if($null-ne $r.Tasks){,@(@($r.Tasks)|Select-Object -First 32|Where-Object {$_-is [Management.Automation.PSCustomObject]}|ForEach-Object {[pscustomobject]@{Task=$(if($_.Task-is [string] -and $_.Task-cmatch '^[a-z0-9-]{1,40}$'){$_.Task}else{'other'});Result=$(if($_.Result-cin @('failed','skipped')){$_.Result}else{'other'});Reason=$(if($_.Reason-is [string] -and $_.Reason-cmatch '^[a-z0-9-]{1,40}$'){$_.Reason}else{$null});Stage=$(if($_.Stage-is [string] -and $_.Stage-cmatch '^[a-z0-9-]{1,40}$'){$_.Stage}else{$null});Samples=(Safe-Int $_.Samples);SamplesLost=(Safe-Int $_.SamplesLost);OffsetBucket=$(if($_.OffsetBucket-is [string] -and $_.OffsetBucket-cmatch '^[a-z0-9-]{1,40}$'){$_.OffsetBucket}else{$null});ExitCode=(Safe-Int $_.ExitCode)}})}else{$null});EndFacts=(End-Facts $r.EndFacts)}) }catch{$invalid++} } $rows=@($valid|Select-Object -Last 300) foreach($row in $rows){ $raw=$row.Paths # Uninstall keeps up to 200 paths locally. The export's smaller cap adds to, not replaces, that # receipt's omitted count and known bytes; otherwise 41-200 paths looked complete after export. $omitted=@($raw|Select-Object -Skip 40) if($omitted.Count-gt 0){ $row.MorePaths=[long]$row.MorePaths+$omitted.Count $bytes=[long]$row.MorePathBytes foreach($entry in $omitted){ if($entry-isnot [Management.Automation.PSCustomObject]){continue} try{$size=Count-OrNull $entry.Bytes ([long]);if($null-ne $size){$bytes+=$size}}catch{} } $row.MorePathBytes=$bytes } # One row whose numbers will not convert loses its paths, never the section. try{$row.Paths=if($null-ne $raw){@(@($raw)|Select-Object -First 40|Where-Object {$_-is [Management.Automation.PSCustomObject]}|ForEach-Object {Operation-PathFacts $_ $aliases})}else{$null}}catch{$row.Paths=$null} } [pscustomobject]@{Kind='OperationLog';Status='complete';Lines=$lines;Invalid=$invalid;Recent=$valid.Count;Emitted=$rows.Count;Oldest=$(if($valid.Count){$valid[0].Utc}else{$null})} $rows # Counts per operation and result over the whole retained log, and over the last 7 days for the summary; # a started attempt with no finished line in the file is unfinished. $finished=@{};foreach($r in $valid){if($r.Stage-eq 'finished'){$finished[$r.Attempt]=$true}} $counts=[ordered]@{};$counts7d=[ordered]@{};$since=$Now.AddDays(-7) foreach($r in $valid){ if($r.Stage-eq 'finished'){$result=if($r.Result){$r.Result}else{'unknown'}} elseif(-not $finished.ContainsKey($r.Attempt)){$result='unfinished'} else{continue} $key=$r.Operation+'|'+$result;if(-not $counts.Contains($key)){$counts[$key]=0};$counts[$key]++ if([DateTimeOffset]::Parse($r.Utc)-ge $since){if(-not $counts7d.Contains($key)){$counts7d[$key]=0};$counts7d[$key]++} } function Count-Rows($table){@(foreach($key in $table.Keys){$parts=$key.Split('|');[pscustomobject]@{Operation=$parts[0];Result=$parts[1];Count=$table[$key]}})} [pscustomobject]@{Kind='OperationSummary';Counts=(Count-Rows $counts);Counts7d=(Count-Rows $counts7d)} # Schema 14 (U88): whether Mole's own cleans removed GPU shader caches, and when. Shader-CleanFacts $valid } function StatusStep-Facts([string]$text) { # status-steps.log lines: UTC time, process id, step code, each written through to the disk before the driver # call it names, so a session whose last step is not first.done or a slow pass's end stopped inside that call or # simply closed. Fixed codes and times only; the process id becomes a report-local alias. $codes=@('open.pdh','open.gpu','open.gpu-processes','open.cores','open.cpu-name','open.os','open.gpu-info','battery.open','slow.drive','slow.other-drives','slow.battery-health','slow.storage-open','slow.storage-read','slow.accessories','first.zones','first.battery-rate','first.pdh','first.gpu','first.network','first.processes','first.done') $sessions=[ordered]@{} foreach($line in @($text -split "\r?\n" | Where-Object {$_})) { $f=$line.Split("`t");$at=[DateTimeOffset]::MinValue if($f.Count-ne 3 -or $f[1]-notmatch '^\d{1,10}$' -or -not [DateTimeOffset]::TryParse($f[0],[Globalization.CultureInfo]::InvariantCulture,[Globalization.DateTimeStyles]::AssumeUniversal,[ref]$at)){continue} $step=$f[2];$version=$null if($step-match '^session(?: (.*))?$'){$version=$Matches[1];$step='session'}elseif($step-notin $codes){$step='other'} $key=$f[1] if($step-eq 'session' -or -not $sessions.Contains($key)){$sessions[$key]=[ordered]@{FirstUtc=$at.ToUniversalTime().ToString('o');Version=$null;Steps=0}} $s=$sessions[$key] if($step-eq 'session'){$s.Version=$(if($version-match '^\d+\.\d+\.\d+([.+-][0-9A-Za-z.+-]*)?$'){$version}else{$null});continue} $s.Steps++;$s.LastStep=$step;$s.LastUtc=$at.ToUniversalTime().ToString('o') } $i=0;$keep=@($sessions.Values | Select-Object -Last 12) foreach($s in $keep){$i++;[pscustomobject]@{Kind='StatusStepSession';Session=('status-'+$i);Version=$s.Version;FirstUtc=$s.FirstUtc;LastUtc=$s.LastUtc;LastStep=$s.LastStep;Steps=$s.Steps}} } function License-Facts([string]$text) { # license.log lines: time, then either "METHOD urlmsproxy=..outcome" or a store note. # Only event kinds, endpoint names, HTTP status codes, exception type names and times leave. foreach($line in @($text -split "\r?\n" | Where-Object {$_} | Select-Object -Last 40)) { $f=$line.Split("`t");$at=[DateTimeOffset]::MinValue if(-not [DateTimeOffset]::TryParse($f[0],[ref]$at)){continue} $utc=$at.ToUniversalTime().ToString('o') if($f.Count-ge 5 -and $f[1]-match '^(GET|POST) https://([A-Za-z0-9.-]+)/(\S*)$') { $host_=$Matches[2];$path=$Matches[3];$method=$Matches[1] $endpoint=if($host_-notin @('live.dodopayments.com','test.dodopayments.com','mole.fit')){'other'}elseif($path-match '(^|/)(activate|validate|deactivate|devices)$'){$Matches[2]}else{'other'} $row=[ordered]@{Kind='LicenseEvent';Utc=$utc;Event='request';Method=$method;Endpoint=$endpoint;ElapsedMs=$(if($f[2]-match '^(\d{1,9})ms$'){[int]$Matches[1]}else{$null});Proxy=$(if($f[3]-eq 'proxy=direct'){'direct'}else{'proxy'});Outcome='other';HttpStatus=$null;CloudflareMitigated=$null;Failure=$null} if($f[4]-match '^HTTP (\d{3}) .*cf-mitigated=(yes|no)'){$row.Outcome='http';$row.HttpStatus=[int]$Matches[1];$row.CloudflareMitigated=($Matches[2]-eq 'yes')} elseif($f[4]-match '^TIMEOUT'){$row.Outcome='timeout'} elseif($f[4]-match '^FAIL ([A-Za-z]{1,64})(?: ([A-Za-z]{1,64}))? <- ([A-Za-z]{1,64}):'){$row.Outcome='fail';$row.Failure=(@($Matches[1],$Matches[2],$Matches[3])|Where-Object {$_}) -join '/'} [pscustomobject]$row } elseif($f.Count-eq 2) { $event=switch -Regex ($f[1]){'^license\.dat saved$'{'store-saved';break}'^license\.dat cleared$'{'store-cleared';break}'^license\.dat unreadable: '{'store-unreadable';break}'^license\.dat not saved: '{'store-not-saved';break}default{'other'}} [pscustomobject]@{Kind='LicenseEvent';Utc=$utc;Event=$event;Failure=$(if($f[1]-match ': ([A-Za-z]{1,64}): '){$Matches[1]}else{$null})} } } } function Velopack-Facts([string]$text) { # Velopack lines: "[component:pid] [HH:mm:ss] [Level] message". Times, levels, stage words and numeric # codes only; messages carry install paths and are never copied. $lines=@($text -split "\r?\n" | Where-Object {$_}) $times=@($lines | ForEach-Object {if($_ -match '^\[[a-z-]+:\d+\] \[(\d{2}:\d{2}:\d{2})\]'){$Matches[1]}}) $errors=@($lines | Where-Object {$_ -match '^\[[a-z-]+:\d+\] \[\d{2}:\d{2}:\d{2}\] \[(?:Error|ERROR|Fatal|FATAL|Critical)\]'}) $stage=$null;$from=$null;$to=$null foreach($l in $lines){ if($l -match "Downloading release file 'releases"){$stage='check'} elseif($l -match '(?i)update download complete|Downloading .*\.nupkg'){$stage='download'} elseif($l -match '\[INFO\] Command: Apply|Applying package'){$stage='apply'} elseif($l -match '--veloapp-updated'){$stage='applied'} if($l -match 'Applying package (\S+) to current: (\S+)'){$to=Safe-Version $Matches[1];$from=Safe-Version $Matches[2]} } [pscustomobject]@{Lines=$lines.Count;FirstTime=$(if($times.Count){$times[0]}else{$null});LastTime=$(if($times.Count){$times[-1]}else{$null});Errors=$errors.Count;Warnings=@($lines|Where-Object {$_ -match '\] \[(?:Warning|WARN)\] '}).Count;ErrorTimes=@($errors|Select-Object -Last 5|ForEach-Object {if($_ -match '\] \[(\d{2}:\d{2}:\d{2})\]'){$Matches[1]}});LastStage=$stage;ApplyFrom=$from;ApplyTo=$to;OsErrors=@([regex]::Matches($text,'os error (-?\d{1,10})')|ForEach-Object {$_.Groups[1].Value}|Select-Object -Unique -First 8);HexCodes=@([regex]::Matches($text,'\b0x[0-9A-Fa-f]{8}\b')|ForEach-Object {$_.Value.ToUpperInvariant()}|Select-Object -Unique -First 8)} } function Startup-Approved-Enabled($state) { # StartupScanner.IsEnabled: no value or an even first byte is enabled, an odd first byte disabled. if($state-isnot [byte[]] -or $state.Length-eq 0){return $true} return (($state[0] -band 1)-eq 0) } function Startup-CountFacts([string]$Source, [string[]]$Names, $Approved) { $enabled=0;$disabled=0 # Assigned directly: an if-expression would unroll the byte[] into object[] and read every entry as enabled. foreach($n in $Names){ $s=$null; if($Approved){$s=$Approved[$n]}; if(Startup-Approved-Enabled $s){$enabled++}else{$disabled++} } [pscustomobject]@{Kind='StartupCount';Source=$Source;Entries=$Names.Count;Enabled=$enabled;Disabled=$disabled} } function Registry-Values($key) { $values=@{};if(-not $key){return $values} foreach($n in $key.GetValueNames()){$values[$n]=$key.GetValue($n,$null,[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)} $values } function Antivirus-Facts($product) { # productState: middle byte 0x10 (or 0x11) means enabled, low byte 0x00 means definitions up to date. $state=[int]$product.productState [pscustomobject]@{Kind='Antivirus';Category=$(if([string]$product.displayName -match '^(Windows|Microsoft) Defender'){'defender'}else{'third-party'});Enabled=((($state -shr 8) -band 0xF0)-eq 0x10);UpToDate=(($state -band 0xFF)-eq 0);ProductState=$state} } function Shell-ModificationFacts([string[]]$Images, [string[]]$ExplorerModules, [bool]$ModulesRead) { # Fixed table of shell add-ons that move or restyle the taskbar, tray and Start. Presence only. $table=[ordered]@{ 'mydockfinder'='^(mydock|myfinder|dockmod|mydockfinder)$' 'startallback'='^startallbackcfg$' 'explorerpatcher'='^(ep_dwm|ep_weather_host|ep_setup)$' 'windhawk'='^windhawk$' 'translucenttb'='^translucenttb$' 'roundedtb'='^roundedtb$' 'rainmeter'='^rainmeter$' 'stardock-start11'='^start11(_64|srv)?$' 'stardock-fences'='^fences(srv|menu64)?$' 'stardock-objectdock'='^objectdock$' 'stardock-windowblinds'='^(wb\d{0,2}(srv|config)|windowblinds\d{0,2})$' 'seelen-ui'='^(seelen-ui|slu-service)$' 'nexus-dock'='^(nexus|winstep)$' 'powertoys'='^powertoys$' } # Injected docks and taskbars run inside Explorer; their module names are the evidence. $modules=@{'startallback'='^startallback';'explorerpatcher'='^explorerpatcher\.'} $names=@($Images | ForEach-Object {([string]$_).ToLowerInvariant() -replace '\.exe$',''}) $loaded=@($ExplorerModules | ForEach-Object {([string]$_).ToLowerInvariant()}) foreach($category in $table.Keys) { $present=@($names -match $table[$category]).Count-gt 0 if(-not $present -and $modules.ContainsKey($category)){ $present=if(@($loaded -match $modules[$category]).Count){$true}elseif($ModulesRead){$false}else{$null} } [pscustomobject]@{Kind='ShellModification';Category=$category;Present=$present} } } function Virtual-AdapterCategory([string]$name) { switch -Regex ($name) { 'GameViewer' {'gameviewer';break} 'Parsec' {'parsec';break} 'IddSample' {'idd-sample';break} 'spacedesk' {'spacedesk';break} 'Meta Virtual' {'meta-virtual';break} 'Virtual Display' {'virtual-display';break} default {$null} } } function Monitor-Facts($monitor) { $b=$monitor.Bounds;$w=$monitor.Work;$reserved=@() if($w.Left-gt $b.Left){$reserved+='left'};if($w.Top-gt $b.Top){$reserved+='top'};if($w.Right-lt $b.Right){$reserved+='right'};if($w.Bottom-lt $b.Bottom){$reserved+='bottom'} [pscustomobject]@{Kind='Monitor';Index=$monitor.Index;Primary=$monitor.Primary;Bounds=@($b.Left,$b.Top,$b.Right,$b.Bottom);Work=@($w.Left,$w.Top,$w.Right,$w.Bottom);Dpi=$(if($monitor.Dpi-gt 0){[int]$monitor.Dpi}else{$null});ReservedEdges=$reserved} } function Dos-DeviceKind([string]$target) { # The kind of object behind a drive letter, never its target path. if([string]::IsNullOrEmpty($target)){return $null} if($target -match '^\\\?\?\\'){return 'subst'} if($target -match '^\\Device\\HarddiskVolume\d+$'){return 'harddisk-volume'} if($target -match '^\\Device\\([A-Za-z][A-Za-z0-9]{0,31})(\\|$)'){return 'device:'+$Matches[1]} 'other' } function Drive-TypeName([uint32]$type) { switch($type){2{'removable'}3{'fixed'}4{'network'}5{'cdrom'}6{'ramdisk'}default{'other'}} } function Volume-Facts($rows) { # Report-local aliases: two letters on one volume share an alias, and no GUID or serial leaves. $names=@{};$serials=@{} foreach($r in @($rows)){ if($r.VolumeName -and -not $names.ContainsKey($r.VolumeName)){$names[$r.VolumeName]='v'+($names.Count+1)} if($null-ne $r.Serial -and -not $serials.ContainsKey([string]$r.Serial)){$serials[[string]$r.Serial]='s'+($serials.Count+1)} } foreach($r in @($rows)){ if([string]$r.Letter -notmatch '^[A-Z]$'){continue} $alias=if($r.VolumeName){$names[$r.VolumeName]}else{$null} $serial=if($null-ne $r.Serial){$serials[[string]$r.Serial]}else{$null} $peers=@($rows|Where-Object {$_.Letter-ne $r.Letter -and (($alias -and $_.VolumeName-eq $r.VolumeName) -or ($null-ne $r.Serial -and $_.Serial-eq $r.Serial))}|ForEach-Object {[string]$_.Letter}|Where-Object {$_ -match '^[A-Z]$'}) [pscustomobject]@{Kind='Volume';Letter=[string]$r.Letter;DriveType=(Drive-TypeName $r.DriveType);FileSystem=$(if([string]$r.FileSystem -match '^[A-Za-z0-9]{1,16}$'){[string]$r.FileSystem}elseif($r.FileSystem){'other'}else{$null});LabelPresent=[bool]$r.LabelPresent;VolumeAlias=$alias;SerialAlias=$serial;SharesWith=@($peers);DosDevice=(Dos-DeviceKind $r.DosDevice);VolumeFlags=[uint32]$r.Flags;TotalBytes=$r.TotalBytes;FreeBytes=$r.FreeBytes;UsedBytes=$(if($null-ne $r.TotalBytes -and $null-ne $r.FreeBytes){[long]($r.TotalBytes-$r.FreeBytes)}else{$null});Status=$(if($r.Status -match '^[a-z-]{1,24}$'){[string]$r.Status}else{'error'});BusType=$(if($null-ne $r.BusType){[uint32]$r.BusType}else{$null});DeviceRemovable=$r.DeviceRemovable;EjectList=$(if([string]$r.EjectList -match '^[a-z:-]{1,32}$'){[string]$r.EjectList}else{$null})} } } function Probe-Facts([string]$Target, $probes) { foreach($p in @($probes)){ if([string]$p.Method -notin @('open','id-extd','id-both','find')){continue} [pscustomobject]@{Kind='DirectoryProbe';Target=$Target;Method=[string]$p.Method;Status=$(if([string]$p.Status -match '^[a-z-]{1,24}$'){[string]$p.Status}else{'error'});Error=[int]$p.Error;Entries=[int]$p.Entries;Records=[int]$p.Records;Directories=[int]$p.Directories;Capped=[bool]$p.Capped;ElapsedMs=[long]$p.ElapsedMs} } } function Root-Verdict([string]$Letter, $volume, $probes) { # The question Analyze raises: does Mole's own read see what the other reads see? $by=@{};foreach($p in @($probes)){$by[[string]$p.Method]=$p} $used=if($volume -and $null-ne $volume.TotalBytes -and $null-ne $volume.FreeBytes){[long]($volume.TotalBytes-$volume.FreeBytes)}else{$null} $mole=$by['id-extd'];$both=$by['id-both'];$find=$by['find'] # WindowsDirectoryLister.ReadOpened: only no records (dots included) or an unsupported first # read uses the older class. A permission failure or a failure after any record never does. if($mole -and $null-ne $mole.Records -and $mole.Records-eq 0 -and ($mole.Status-eq 'ok' -or $mole.Error-in @(1,50,87,124))){$mole=$both} $verdict=if(-not $by['open'] -or $by['open'].Status-ne 'ok'){'open-failed'} elseif(-not $mole -or $mole.Status-ne 'ok'){'mole-read-failed'} elseif($mole.Entries-eq 0 -and (($both -and $both.Entries-gt 0) -or ($find -and $find.Entries-gt 0))){'mole-read-empty'} elseif($mole.Entries-eq 0 -and $null-ne $used -and $used-gt 1GB){'empty-with-used-space'} elseif(($find -and [Math]::Abs($find.Entries-$mole.Entries)-gt 0 -and -not $find.Capped -and -not $mole.Capped)){'counts-differ'} else{'ok'} [pscustomobject]@{Kind='AnalyzeRootCheck';Letter=$Letter;Verdict=$verdict;UsedBytes=$used;MoleEntries=$(if($mole){[int]$mole.Entries}else{$null});BothEntries=$(if($both){[int]$both.Entries}else{$null});FindEntries=$(if($find){[int]$find.Entries}else{$null})} } function Snapshot-Facts($row, [string]$SerialAlias, [DateTime]$NowUtc = [DateTime]::UtcNow) { $scanned=$null;$age=$null if($row.ScannedTicks-gt 0 -and $row.ScannedTicks-lt [DateTime]::MaxValue.Ticks){$scanned=New-Object DateTime ([long]$row.ScannedTicks),([DateTimeKind]::Utc);$age=[Math]::Round(($NowUtc-$scanned).TotalHours,1)} [pscustomobject]@{Kind='AnalyzeSnapshot';Status=$(if([string]$row.Status -match '^[a-z-]{1,24}$'){[string]$row.Status}else{'error'});SerialAlias=$SerialAlias;Bytes=[long]$row.Bytes;Schema=[int]$row.Schema;Root=$(if([string]$row.Root -match '^[A-Za-z]:\\$'){([string]$row.Root).ToUpperInvariant()}elseif($row.Root){'other'}else{$null});ScannedUtc=$(if($scanned){$scanned.ToString('o')}else{$null});AgeHours=$age;Directories=[long]$row.Directories;Files=[long]$row.Files;DeniedDirectories=[int]$row.Denied;Truncated=[bool]$row.Truncated;RootAccessDenied=(([int]$row.RootFlags -band 8)-ne 0);RootPartial=[bool]$row.RootPartial;RootAllocatedBytes=[long]$row.RootAllocated;RootFiles=[int]$row.RootFiles;RootChildren=[int]$row.RootChildren} } function Sleep-Category([string]$Provider, [int]$Id) { # Schema 21: the events that say the PC slept or woke, by fixed category; any other provider or id is dropped. switch -regex ($Provider) { '^Microsoft-Windows-Kernel-Power$' { switch($Id){42{return 'sleep'}107{return 'resume'}506{return 'standby-enter'}507{return 'standby-exit'}default{return $null}} } '^Microsoft-Windows-Power-Troubleshooter$' { if($Id-eq 1){return 'wake'}; return $null } default { return $null } } } function Sleep-Facts($events) { # Counts per category over the events read, plus the newest 40 as category and time. No event text leaves. $rows=New-Object System.Collections.Generic.List[object];$counts=[ordered]@{sleep=0;resume=0;'standby-enter'=0;'standby-exit'=0;wake=0} foreach($e in @($events|Sort-Object TimeCreated -Descending)){ $category=Sleep-Category ([string]$e.ProviderName) ([int]$e.Id) if(-not $category){continue} $counts[$category]++ if($rows.Count-lt 40){$rows.Add([pscustomobject]@{Kind='SleepEvent';Category=$category;Utc=([DateTime]$e.TimeCreated).ToUniversalTime().ToString('o')})} } $newest=@($rows|Where-Object Category -in @('sleep','standby-enter')|Select-Object -First 1) $wake=@($rows|Where-Object Category -in @('resume','wake','standby-exit')|Select-Object -First 1) $rows [pscustomobject]@{Kind='SleepSummary';Status='complete';Days=14;Sleeps=$counts.sleep;Resumes=$counts.resume;Wakes=$counts.wake;StandbyEnters=$counts['standby-enter'];StandbyExits=$counts['standby-exit'];LastSleepUtc=$(if($newest){$newest[0].Utc}else{$null});LastResumeUtc=$(if($wake){$wake[0].Utc}else{$null})} } function Sleep-Summary($row) { # Null when the log was not read; otherwise the counts and the newest sleep and resume. if($null-eq $row -or $row.Status-ne 'complete'){return $null} [ordered]@{Sleeps14d=$row.Sleeps;Resumes14d=$row.Resumes;StandbyCycles14d=$row.StandbyEnters;LastSleepUtc=$row.LastSleepUtc;LastResumeUtc=$row.LastResumeUtc} } function Freeze-Category([string]$Provider, [int]$Id) { # Fixed categories for events that explain a whole-PC freeze; any other provider is dropped. switch -regex ($Provider) { '^Microsoft-Windows-Kernel-Power$' { if($Id-eq 41){return 'kernel-power'}; return $null } '^EventLog$' { if($Id-eq 6008){return 'unexpected-shutdown'}; return $null } '^Display$' { if($Id-eq 4101){return 'display-tdr'}; return $null } '^Microsoft-Windows-Resource-Exhaustion-Detector$' { if($Id-eq 2004){return 'memory-exhaustion'}; return $null } '^Microsoft-Windows-WHEA-Logger$' { return 'whea' } '^nvlddmkm$' { return 'gpu-nvidia' } '^(igfx|igfxn|igfxnd|igfxdcm|igdkmd64|igdkmdn64)$' { return 'gpu-intel' } '^(amdkmdag|amdkmdap|amdwddmg)$' { return 'gpu-amd' } '^(iaStorAC|iaStorAVC|iaStorA|iaStorV|iaStorVD)$' { return 'storage-intel-rst' } '^storahci$' { return 'storage-ahci' } '^stornvme$' { return 'storage-nvme' } '^disk$' { return 'disk' } '^(Ntfs|Microsoft-Windows-Ntfs)$' { return 'ntfs' } } $null } function Event-DataText($d) { if($null-eq $d){$null}elseif($d -is [string]){$d}else{[string]$d.'#text'} } function Freeze-EventFacts($event) { # Category, id, level and time; Kernel-Power 41 adds its bugcheck code and whether the power button was held. $category=Freeze-Category ([string]$event.ProviderName) ([int]$event.Id) if(-not $category){return} $row=[ordered]@{Kind='FreezeEvent';Category=$category;Id=[int]$event.Id;Level=[int]$event.Level;Utc=$event.TimeCreated.ToUniversalTime().ToString('o')} if($category-eq 'kernel-power'){ foreach($d in @(([xml]$event.ToXml()).Event.EventData.Data)){ $v=Event-DataText $d if($d.Name-eq 'BugcheckCode' -and $v -match '^\d{1,12}$'){$row.BugcheckCode=[long]$v} if($d.Name-eq 'PowerButtonTimestamp' -and $v -match '^\d{1,20}$'){$row.PowerButtonHeld=($v-ne '0')} if($d.Name-eq 'SleepInProgress' -and $v -match '^\d{1,3}$'){$row.SleepInProgress=($v-ne '0')} } } [pscustomobject]$row } function Application-FreezeFacts($event) { # Windows Error Reporting's LiveKernelEvent (a GPU or driver watchdog: 141, 117, 1a8) by code, and # Application Hang only for Mole, dwm and explorer; no other application name leaves. $data=@(([xml]$event.ToXml()).Event.EventData.Data) $utc=$event.TimeCreated.ToUniversalTime().ToString('o') if($event.ProviderName-eq 'Windows Error Reporting' -and $event.Id-eq 1001){ if((Event-DataText $data[2])-ne 'LiveKernelEvent'){return} $code=[string](Event-DataText $data[5]) [pscustomobject]@{Kind='FreezeEvent';Category='live-kernel-event';Id=1001;Code=$(if($code -match '^[0-9A-Fa-f]{1,8}$'){$code.ToLowerInvariant()}else{'other'});Utc=$utc} } elseif($event.ProviderName-eq 'Application Hang' -and $event.Id-eq 1002){ $image=([string](Event-DataText $data[0])).ToLowerInvariant() if($image -notin @('mole.exe','dwm.exe','explorer.exe')){return} [pscustomobject]@{Kind='FreezeEvent';Category='app-hang';Id=1002;Image=$image;Utc=$utc} } } function Dump-FolderFacts([string]$Root, [string]$Kind, [DateTime]$SinceUtc) { # Dump counts and the newest time per Windows-named folder; never a file name. if(-not [IO.Directory]::Exists($Root)){return [pscustomobject]@{Kind=$Kind;Status='missing'}} try { $folders=@([pscustomobject]@{Name='(root)';Path=$Root})+@(Get-ChildItem -LiteralPath $Root -Directory -ErrorAction Stop|Select-Object -First 32|ForEach-Object {[pscustomobject]@{Name=$(if($_.Name -match '^[A-Za-z0-9_-]{2,32}$'){$_.Name}else{'other'});Path=$_.FullName}}) foreach($f in $folders){ $dumps=@(Get-ChildItem -LiteralPath $f.Path -File -Filter *.dmp -ErrorAction Stop|Where-Object {$_.LastWriteTimeUtc-ge $SinceUtc}) if($dumps.Count-eq 0){continue} [pscustomobject]@{Kind=$Kind;Folder=$f.Name;Dumps=$dumps.Count;NewestUtc=($dumps|Sort-Object LastWriteTimeUtc|Select-Object -Last 1).LastWriteTimeUtc.ToString('o')} } } catch {[pscustomobject]@{Kind=$Kind;Status=(Error-Status $_)}} } function Bus-Word([int]$Bus) { switch($Bus){1{'scsi'}3{'ata'}7{'usb'}8{'raid'}10{'sas'}11{'sata'}17{'nvme'}default{'other'}} } function Location-Shape([string]$Location, [string]$Name, [string]$Publisher) { # What kind of folder an Uninstall entry registers: the app's own, the publisher's (which holds the # vendor's other products), a container, or other. Shape words only, never the path. $loc=([string]$Location).Trim().Trim('"').TrimEnd('\') if(-not $loc){return [pscustomobject]@{Shape='empty';OwnChildPresent=$null}} function Squash($t){ ([string]$t).ToLowerInvariant() -replace '[^\p{L}\p{Nd}]','' } $leaf=Squash ([IO.Path]::GetFileName($loc)) $pub=Squash ($Publisher -replace '\b(inc|incorporated|corp|corporation|ltd|limited|llc|gmbh|co)\b\.?','') $first=Squash (([string]$Publisher).Trim() -split '\s+')[0] $shape=if($leaf-and $leaf-eq (Squash $Name)){'named-for-app'}elseif($leaf-and (($pub-and $leaf-eq $pub) -or ($first.Length-ge 3 -and $leaf-eq $first))){'publisher-folder'}elseif($loc -match '^[A-Za-z]:(\\[^\\]+)?$' -or $leaf -match '^(programfiles|programfilesx86|programdata|appdata|local|roaming|programs)$'){'container'}else{'other'} $own=$null;$children=$null if($shape-eq 'publisher-folder' -and $loc -match '^[A-Za-z]:\\'){ if($Name -match '^[^\\/:*?"<>|]{1,120}$'){ try{$own=[IO.Directory]::Exists((Join-Path $loc $Name.Trim()))}catch{} } try{$children=@([IO.Directory]::EnumerateDirectories($loc)|Select-Object -First 64).Count}catch{} } [pscustomobject]@{Shape=$shape;OwnChildPresent=$own;FolderChildren=$children} } function Filter-DriverFacts { # File system minifilters by service name and load order group, read through the registry API: a # Get-ItemProperty per service key (about a thousand) cost seconds of the shared budget. $rows=@() $services=[Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Services') if(-not $services){return @()} try { foreach($name in $services.GetSubKeyNames()){ $key=$null try { $key=$services.OpenSubKey($name) if(-not $key){continue} $group=[string]$key.GetValue('Group') $start=$key.GetValue('Start') if($group -notmatch '^FSFilter ' -or $start-eq 4){continue} $safe=if($name -match '^[A-Za-z0-9_.-]{1,48}$'){$name}else{'other'} $altitude=$null $instances=$key.OpenSubKey('Instances') if($instances){ try { $default=[string]$instances.GetValue('DefaultInstance') if($default){$instance=$instances.OpenSubKey($default);if($instance){try{$a=[string]$instance.GetValue('Altitude');if($a -match '^[0-9.]{1,12}$'){$altitude=$a}}finally{$instance.Close()}}} } finally {$instances.Close()} } $rows+=[pscustomobject]@{Kind='FileSystemFilter';Name=$safe;Group=($group -replace '^FSFilter ','');Start=[int]$start;Altitude=$altitude} } catch {} finally {if($key){$key.Close()}} } } finally {$services.Close()} @($rows|Sort-Object {[double]$(if($_.Altitude){$_.Altitude}else{0})} -Descending|Select-Object -First 60) } # Schema 24: AI tools' data on this PC, Mole Mac's 17-ai-tools on Windows paths, for building and # supporting AI cleanup. Metadata only: sizes, counts, ages, link kinds, SQLite header numbers and # versions. A transcript is opened only for its first cwd and source fields, which leave as # exists/missing/unknown and a fixed-shape value, never the path or any message. Names a tool does # not choose (projects, worktrees, private models) leave as report-local aliases. function Ai-Alias([string]$s) { if($null-eq $script:aiAliases){$script:aiAliases=@{}} $k=([string]$s).ToLowerInvariant() if(-not $script:aiAliases.ContainsKey($k)){$script:aiAliases[$k]='name-'+($script:aiAliases.Count+1)} $script:aiAliases[$k] } # A name leaves as itself only when a tool chose it: a public package, product, extension or folder name # from these lists, a single lowercase word (a tool's own `logs`, `state_5.sqlite`), or a version. # Anything a person could have typed (a project, a private package, a file they keep there) is an alias. $script:aiPublic=New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) foreach($n in @( '@openai/codex','@openai/codex-sdk','@anthropic-ai/claude-code','@anthropic-ai/claude-agent-sdk','@anthropic-ai/sdk','@google/gemini-cli','@google/jules','opencode-ai','@github/copilot','@qwen-code/qwen-code','@sourcegraph/amp','@iflow-ai/iflow-cli','@kilocode/cli','@augmentcode/auggie','@charmland/crush','@factory/cli','@vibe-kit/grok-cli','@musistudio/claude-code-router','ccusage','@ccusage/codex','@modelcontextprotocol/inspector','@playwright/mcp','@upstash/context7-mcp','mcp-remote','cline','@continuedev/cli','@tencent-ai/codebuddy-code','@zed-industries/claude-code-acp','@agentclientprotocol/claude-agent-acp','@mariozechner/pi-coding-agent','openclaw','task-master-ai','claude-flow', 'aider-chat','llm','open-interpreter','huggingface-hub','kimi-cli','goose-ai','mcp','ollama','vllm','litellm','openai','anthropic','crewai','smolagents','qwen-agent','mlx-lm', 'openai.codex','openai.chatgpt','openai.chatgpt-desktop','anthropic.claude','anthropic.claudecode','ollama.ollama','elementlabs.lmstudio','anysphere.cursor','codeium.windsurf','bytedance.trae','amazon.kiro','google.antigravity','github.copilot','google.geminicli','sst.opencode','charmbracelet.crush','block.goose','nomic.gpt4all','microsoft.copilot','claude','codex','opencode','gemini-cli','lmstudio','cursor','windsurf','aider','crush','goose', 'lm studio','trae','trae cn','kiro','antigravity','qoder','codebuddy','cherrystudio','cherry studio','jan','chatbox','devin','github copilot','ollama app','lms','language_server_windows_x64','language_server_windows_arm64','llama-server','ollama_llama_server','deepseek','kimi','chatgpt', 'cursor-updater','claude-updater','windsurf-updater','trae-updater','kiro-updater','lm-studio-updater','antigravity-updater','qoder-updater','codebuddy-updater', 'registry.ollama.ai','hf.co','huggingface.co', 'nodejs','npm','cmd','bin','scripts','windowsapps','links','shims','current','pnpm', '.tmp','shell-snapshots','file-history','paste-cache','session-env','claude-code','claude-code-vm','local-agent-mode-sessions','archived_sessions','plugins','skills','agents','commands','hooks','todos','projects','sessions','worktrees','packages','visualizations','memories','statsig','telemetry','ide','plans','debug','downloads','update.exe','squirrelsetup.log','claude.exe','codex.exe','.credentials.json','settings.json','settings.local.json','config.toml','config.json','auth.json','history.jsonl','models_cache.json','session-state','session-store.db','marketplaces','bundled-marketplaces','.staging','app-server-daemon','standalone','releases','cache','caches','logs','log','tmp','usage-host-id','userdata')){[void]$script:aiPublic.Add($n)} foreach($n in @('github','anthropic','openai','google','continue','saoudrizwan','rooveterinaryinc','kilocode','codeium','tabnine','amazonwebservices','sourcegraph','augment','ms-vscode','ms-toolsai','ms-windows-ai-studio','anysphere','windsurf','bytedance','marscode','alibaba-cloud','tencent-cloud','qwen','devin','cursor','trae','kiro','qoder','codebuddy')){[void]$script:aiPublic.Add('publisher:'+$n)} # A compound name (`Trae CN`, `.codex-global-state.json`, `logs_2.sqlite-wal`, `vendor_imports`) leaves as # itself only when every word in it is a tool name or a generic word from this list: jasper's report # (2026-11-16) aliased seven of nine AI process images and every hyphenated `.codex` entry, which left a # 370 MB folder unnamed. A word a person chose (a client, a project, `notes`, `plan`) keeps the alias. $script:aiWords=New-Object 'Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) foreach($n in @( 'claude','anthropic','codex','openai','chatgpt','opencode','devin','cursor','copilot','gemini','antigravity','ollama','lmstudio','windsurf','codeium','trae','kiro','qwen','tongyi','lingma','qoder','codebuddy','comate','marscode','doubao','kimi','moonshot','deepseek','zhipu','glm','minimax','hermes','goose','openclaw','aider','cline','roo','kilo','kilocode','augment','auggie','continue','tabnine','factory','droid','grok','iflow','amp','crush','nowledge','huggingface','llama','whisper','mcp','llm','github','google','microsoft','bytedance','tencent','alibaba','cherrystudio','jan','chatbox','pi','jules', 'ai','cn','zh','en','lm','studio','app','apps','cli','code','desktop','helper','server','service','agent','agents','updater','update','setup','installer','launcher','tray','host','worker','native','runner','daemon','gpu','renderer','crashpad','handler','language','windows','win','x64','arm64','x86','sdk','core','web','chat','ext','extension','extensions','bridge','proxy','router','acp','inspector','sandbox','bin','secrets','global','state','vendor','imports','personality','migration','migrations','installation','id','version','ambient','suggestions','internal','storage','control','reconciled','maintenance','lock','locks','writer','thread','threads','history','summaries','reference','capabilities','metadata','oauth','process','manager','realtime','voice','continuity','transcription','dictation','node','repl','computer','use','review','plugin','plugins','skill','skills','memory','memories','session','sessions','rollout','external','import','goals','queue','logs','log','models','model','cache','caches','data','config','settings','local','user','shared','backup','backups','bak','tmp','temp','generated','images','browser','index','auth','hosts','outputs','attachments','automations','pets','status','stats','feedback','jobs','tasks','keybindings','servers','statusline','telemetry','paste','env','dev','last','cleanup','result','downloads','debug','shell','snapshots','file','files','projects','todos','hooks','commands','rules','ide','modules','package','packages','vm','bundles','mode','releases','standalone','current','staging','marketplaces','bundled','sqlite','db','wal','shm','journal','json','jsonl','toml','zst','md','txt','exe','dll','cmd','ps1','sh','v1','v2')){[void]$script:aiWords.Add($n)} function Ai-Words([string]$s) { if($s -notmatch '^[A-Za-z0-9 ._@/-]{1,80}$'){return $false} $parts=@($s -split '[ ._@/-]+'|Where-Object {$_}) if(-not $parts.Count){return $false} foreach($p in $parts){if(-not ($script:aiWords.Contains($p) -or $p -match '^\d{1,4}$')){return $false}} $true } function Ai-Version([string]$s) { if($s -match '^(?:app-|v)?\d+(?:\.\d+){1,3}(?:[-+][A-Za-z0-9_.]+){0,5}$'){$s}else{$null} } function Ai-Name([string]$s) { if([string]::IsNullOrEmpty($s)){return $null} if($script:aiPublic.Contains($s) -or $s -cmatch '^[a-z][a-z0-9_]{0,23}(\.[a-z0-9]{1,8})?$' -or (Ai-Version $s) -or (Ai-Words $s)){return $s} Ai-Alias $s } function Ai-Public([string]$s) { if($script:aiPublic.Contains($s) -or (Ai-Words $s)){$s}else{Ai-Alias $s} } function Ai-Extension([string]$s) { if($s -match '^([a-z0-9-]{1,40})\.[a-z0-9-]{1,60}$' -and $script:aiPublic.Contains('publisher:'+$Matches[1])){$s}else{Ai-Alias $s} } # A session's originator or entrypoint, kept only for a tool's own names (`codex_cli_rs`, `Codex Desktop`, `sdk-ts`). function Ai-Value([string]$s) { if([string]::IsNullOrEmpty($s)){$null}elseif($s -match '^(?i)(?:(?:codex|claude|cursor|copilot|gemini|opencode|devin|vscode|jetbrains|zed)[A-Za-z0-9 _.:+-]{0,24}|cli|sdk|sdk-cli|sdk-ts|sdk-py|exec|mcp|desktop|web|remote)$'){$s}else{'other'} } # The cmdlet join resolves the drive and throws for a missing one or a quoted PATH entry (seen on the VM: # '"C' is not a drive), which ended the whole section; a plain join never throws. function Ai-Join([string]$a,[string]$b) { if([string]::IsNullOrEmpty($a)){return $b};$a.Trim().Trim('"').TrimEnd('\')+'\'+$b.TrimStart('\') } function Ai-Fail([string]$step,$err) { [pscustomobject]@{Kind='AiError';Step=$step;Status=(Error-Status $err)} } function Ai-Left { [int]($script:aiDeadline-$script:aiClock.ElapsedMilliseconds) } function Ai-Ms([int]$want) { [Math]::Max(0,[Math]::Min($want,(Ai-Left)-300)) } function Ai-Utc($t) { if($null-eq $t -or $t-eq [DateTime]::MinValue -or $t-eq [DateTime]::MaxValue){$null}else{([DateTime]$t).ToUniversalTime().ToString('o')} } # Only a fixed local drive is read: a network share blocks each call for tens of seconds offline, outside # the budget checks, and removable or optical drives spin up. DriveType answers without touching the drive. function Ai-Local([string]$p) { if([string]::IsNullOrEmpty($p) -or $p -notmatch '^[A-Za-z]:\\'){return $false} if($null-eq $script:aiDrives){$script:aiDrives=@{}} $l=$p.Substring(0,1).ToUpperInvariant() if(-not $script:aiDrives.ContainsKey($l)){$t=$false;try{$t=(New-Object IO.DriveInfo ($l+':\')).DriveType-eq [IO.DriveType]::Fixed}catch{};$script:aiDrives[$l]=$t} $script:aiDrives[$l] } function Ai-Item([string]$p) { if(-not (Ai-Local $p)){return $null};try{Get-Item -LiteralPath $p -Force -ErrorAction Stop}catch{$null} } function Ai-Children([string]$p,[switch]$Directory,[switch]$File,[string]$Filter) { if(-not (Ai-Local $p)){return @()} $a=@{LiteralPath=$p;Force=$true;ErrorAction='SilentlyContinue'};if($Directory){$a.Directory=$true};if($File){$a.File=$true};if($Filter){$a.Filter=$Filter} @(Get-ChildItem @a) } # Where a path lives, by class only. # A trimmed path whose slashes are turned with Replace('/','\') reads to Defender signature 1.463.357.0 # (2026-11-18) as VirTool:PowerShell/MaleficAms.W and blocks the whole script under irm | iex, even split over # two lines; the separator constants do the same and pass (test_diagnose.py NoAmsiTrigger). function Ai-Backslash([string]$s) { $s.Replace([IO.Path]::AltDirectorySeparatorChar,[IO.Path]::DirectorySeparatorChar) } function Ai-Where([string]$p) { if([string]::IsNullOrWhiteSpace($p)){return $null} $p=Ai-Backslash $p.Trim('"') if($p.StartsWith('\\')){return 'network'} if($p -notmatch '^[A-Za-z]:'){return 'relative'} $r=$script:aiRoots foreach($pair in @(@('appdata-local',$r.Local),@('appdata-roaming',$r.Roaming),@('profile',$r.Home),@('program-files',$env:ProgramFiles),@('program-files',${env:ProgramFiles(x86)}),@('windows',$env:windir))) { $b=[string]$pair[1] if($b -and ($p.Equals($b.TrimEnd('\'),[StringComparison]::OrdinalIgnoreCase) -or $p.StartsWith($b.TrimEnd('\')+'\',[StringComparison]::OrdinalIgnoreCase))){return $pair[0]} } try{$d=New-Object IO.DriveInfo ($p.Substring(0,1)+':\');switch([string]$d.DriveType){'Fixed'{'other-fixed'}'Removable'{'removable'}'Network'{'network'}'NoRootDirectory'{'missing-drive'}default{'other'}}}catch{'missing-drive'} } # A project folder a session names: exists, missing (proven gone on a ready fixed drive) or unknown. function Ai-Workdir([string]$p) { if([string]::IsNullOrWhiteSpace($p)){return 'none'} $p=$p.Replace('/','\') if($p -notmatch '^[A-Za-z]:\\'){return 'unknown'} if(-not (Ai-Local $p)){return 'unknown'} try{if(-not (New-Object IO.DriveInfo ($p.Substring(0,3))).IsReady){return 'unknown'}}catch{return 'unknown'} try{$null=Get-Item -LiteralPath $p -Force -ErrorAction Stop;'exists'}catch{if($_.CategoryInfo.Category-eq 'ObjectNotFound'){'missing'}else{'unknown'}} } function Ai-Link($item) { if(-not $item -or -not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)){return $null} $t=$null;try{$t=@($item.Target)[0]}catch{} $lt=$null;try{$lt=[string]$item.LinkType}catch{} if($t -and -not [IO.Path]::IsPathRooted($t)){try{$t=[IO.Path]::GetFullPath((Ai-Join (Split-Path $item.FullName -Parent) $t))}catch{}} $leaf=$null if($t){$l=Split-Path $t -Leaf;$leaf=if(Ai-Version $l){$l}elseif($l -in @('bin','current')){$l}else{Ai-Alias $l}} [pscustomobject]@{Type=$(if($lt){$lt}else{'reparse'});Where=(Ai-Where $t);Leaf=$leaf;Exists=$(if($t -and (Ai-Local $t)){try{[IO.Directory]::Exists($t) -or [IO.File]::Exists($t)}catch{$null}}else{$null})} } function Ai-Head([string]$path,[int]$max) { if(-not (Ai-Local $path)){return $null} $fs=$null try { # A cloud placeholder (OneDrive and the like) would be downloaded by the read: skip it. $at=[int][IO.File]::GetAttributes($path);if($at -band 0x441000){return $null} $fs=New-Object IO.FileStream($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)) $n=[int][Math]::Min($max,$fs.Length);$buf=New-Object byte[] $n;$got=$fs.Read($buf,0,$n) [Text.Encoding]::UTF8.GetString($buf,0,$got) } catch {$null} finally {if($fs){$fs.Dispose()}} } function Ai-JsonString([string]$text,[string]$key) { if(-not $text){return $null} $m=[regex]::Match($text,'"'+[regex]::Escape($key)+'"\s*:\s*"((?:[^"\\]|\\.)*)"') if(-not $m.Success){return $null} try{[regex]::Unescape($m.Groups[1].Value)}catch{$m.Groups[1].Value} } # Files under a root, metadata only, never through a reparse point. function Ai-Files([string]$root,[string]$filter,[int]$max,[int]$depth) { $list=New-Object 'Collections.Generic.List[IO.FileInfo]';$script:aiTruncated=$false if(-not (Ai-Local $root)){return ,$list} $stack=New-Object 'Collections.Generic.Stack[object]';$stack.Push(@($root,0)) while($stack.Count -and $list.Count-lt $max -and (Ai-Left)-gt 1500) { $pair=$stack.Pop() try{$di=[IO.DirectoryInfo]::new($pair[0])}catch{continue} try{foreach($f in $di.GetFiles($filter)){if(-not ($f.Attributes -band [IO.FileAttributes]::ReparsePoint)){$list.Add($f)}}}catch{} if($pair[1]-ge $depth){continue} try{foreach($s in $di.GetDirectories()){if(-not ($s.Attributes -band [IO.FileAttributes]::ReparsePoint)){$stack.Push(@($s.FullName,($pair[1]+1)))}}}catch{} } # Callers read this right after the call: a cut list must not read as a total. $script:aiTruncated=($stack.Count -gt 0 -or $list.Count-ge $max) ,$list } function Ai-Measure([string]$path,[int]$want) { [MoleFeedbackNative]::Scan($path,(Ai-Ms $want),300000) } function Ai-Entry([string]$homeId,$k,[int]$ms,[switch]$Alias) { $name=if($Alias){Ai-Alias $k.Name}else{Ai-Name $k.Name} if($k.Attributes -band [IO.FileAttributes]::ReparsePoint){$l=Ai-Link (Ai-Item $k.FullName);return [pscustomobject]@{Kind='AiHomeChild';Home=$homeId;Name=$name;Status='link';LinkType=$l.Type;LinkWhere=$l.Where;LinkLeaf=$l.Leaf;LinkExists=$l.Exists}} if($k -is [IO.FileInfo]){return [pscustomobject]@{Kind='AiHomeChild';Home=$homeId;Name=$name;Status='file';Files=1;Bytes=$k.Length;NewestWriteUtc=(Ai-Utc $k.LastWriteTimeUtc)}} if((Ai-Ms $ms)-le 0){return [pscustomobject]@{Kind='AiHomeChild';Home=$homeId;Name=$name;Status='budget'}} $m=Ai-Measure $k.FullName $ms [pscustomobject]@{Kind='AiHomeChild';Home=$homeId;Name=$name;Status=$m.Status;Files=$m.Files;Bytes=$m.LogicalBytes;NewestWriteUtc=$m.NewestWriteUtc;OldestWriteUtc=$m.OldestWriteUtc} } # One AI data root and its first-level children (tool-chosen names, or aliases with -AliasChildren). function Ai-Home([string]$id,[string]$path,[int]$children=40,[int]$want=6000,[switch]$Overridden,[switch]$AliasChildren,[switch]$NoChildren) { $it=Ai-Item $path if(-not $it){$script:aiAbsent.Add($id);return} $l=Ai-Link $it if($l){[pscustomobject]@{Kind='AiHome';Id=$id;Status='link';LinkType=$l.Type;LinkWhere=$l.Where;LinkLeaf=$l.Leaf;LinkExists=$l.Exists;Overridden=[bool]$Overridden};return} if(-not $it.PSIsContainer){[pscustomobject]@{Kind='AiHome';Id=$id;Status='file';Files=1;Bytes=$it.Length;NewestWriteUtc=(Ai-Utc $it.LastWriteTimeUtc);Overridden=[bool]$Overridden};return} if($NoChildren){$m=Ai-Measure $path $want;[pscustomobject]@{Kind='AiHome';Id=$id;Status=$m.Status;Files=$m.Files;Bytes=$m.LogicalBytes;NewestWriteUtc=$m.NewestWriteUtc;Overridden=[bool]$Overridden};return} $kids=@();try{$kids=@(([IO.DirectoryInfo]::new($path)).GetFileSystemInfos()|Sort-Object LastWriteTimeUtc -Descending)}catch{[pscustomobject]@{Kind='AiHome';Id=$id;Status=(Error-Status $_);Overridden=[bool]$Overridden};return} $files=0;[long]$bytes=0;$partial=$false;$n=0;$newest=$null $per=[Math]::Max(400,[int]($want/[Math]::Max(1,[Math]::Min($kids.Count,$children)))) foreach($k in $kids) { if($n-ge $children){$partial=$true;break};$n++ $row=Ai-Entry $id $k $per -Alias:$AliasChildren $row if($row.Bytes){$bytes+=[long]$row.Bytes};if($row.Files){$files+=[int]$row.Files} if($row.NewestWriteUtc -and (-not $newest -or [string]$row.NewestWriteUtc -gt $newest)){$newest=[string]$row.NewestWriteUtc} if($row.Status -notin @('complete','file','link','refused-chat-archive')){$partial=$true} } # Children past the cap still count: a folder's own write time moves only when an entry in it is added, # so `sessions` sorted last on jasper's PC and 20 of the 80 `.codex` entries were never measured. $rest=@($kids|Select-Object -Skip $n) if($rest.Count) { $rf=0;[long]$rb=0;$rdone=0;$restClock=[Diagnostics.Stopwatch]::StartNew() foreach($k in $rest) { if($restClock.ElapsedMilliseconds-gt 1500 -or (Ai-Ms 400)-le 0){break} if($k.Attributes -band [IO.FileAttributes]::ReparsePoint){$rdone++;continue} if($k -is [IO.FileInfo]){$rf++;$rb+=$k.Length}else{$m=Ai-Measure $k.FullName 300;$rf+=[int]$m.Files;$rb+=[long]$m.LogicalBytes;if($m.Status-ne 'complete'){$rdone--}} $rdone++ } [pscustomobject]@{Kind='AiHomeRest';Home=$id;Children=$rest.Count;Measured=$rdone;Files=$rf;Bytes=$rb} if($rdone-eq $rest.Count){$bytes+=$rb;$files+=$rf} } [pscustomobject]@{Kind='AiHome';Id=$id;Status=$(if($partial){'partial'}else{'complete'});Children=$kids.Count;Files=$files;Bytes=$bytes;NewestWriteUtc=$newest;Overridden=[bool]$Overridden} } function Ai-Sqlite([string]$store,[string]$path,[string]$root) { $it=Ai-Item $path if(-not $it -or $it.PSIsContainer){return} # Which folder under the store root holds it: jasper's report had two sets of Codex stores and no way to tell them apart. $folder=if(-not $root -or [string]::Equals($it.DirectoryName.TrimEnd('\'),$root.Trim().Trim('"').TrimEnd('\'),[StringComparison]::OrdinalIgnoreCase)){'.'}else{Ai-Name $it.Directory.Name} $row=[ordered]@{Kind='AiStore';Store=$store;Folder=$folder;Name=(Ai-Name $it.Name);Bytes=$it.Length;NewestWriteUtc=(Ai-Utc $it.LastWriteTimeUtc);PageSize=$null;Pages=$null;FreePages=$null;Journal=$null;WrittenBy=$null;Wal=$null;Shm=$null;OpenElsewhere=$null} $fs=$null try { $fs=New-Object IO.FileStream($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)) $b=New-Object byte[] 100 if($fs.Read($b,0,100)-eq 100 -and [Text.Encoding]::ASCII.GetString($b,0,15)-eq 'SQLite format 3') { $be={param($i,$n) $v=[long]0;for($j=0;$j-lt $n;$j++){$v=($v -shl 8) -bor $b[$i+$j]};$v} $ps=& $be 16 2;if($ps-eq 1){$ps=65536} $ver=& $be 96 4 $row.PageSize=$ps;$row.Pages=& $be 28 4;$row.FreePages=& $be 36 4 $row.Journal=$(if($b[18]-eq 2){'wal'}else{'rollback'}) $row.WrittenBy=('{0}.{1}.{2}' -f [Math]::Floor($ver/1000000),[Math]::Floor(($ver%1000000)/1000),($ver%1000)) } else {$row.Journal='not-sqlite'} } catch {$row.Journal='unreadable'} finally {if($fs){$fs.Dispose()}} $w=Ai-Item ($path+'-wal');if($w){$row.Wal=$w.Length} $s=Ai-Item ($path+'-shm');if($s){$row.Shm=$s.Length} # Windows SQLite opens without delete sharing, so an exclusive open fails while a tool holds the store. try{$x=New-Object IO.FileStream($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::None);$x.Dispose();$row.OpenElsewhere=$false}catch{$row.OpenElsewhere=$true} [pscustomobject]$row } function Ai-Stores([string]$store,[string]$dir,[string]$pattern,[int]$depth=0) { if(-not (Ai-Item $dir)){return} foreach($f in (Ai-Files $dir '*' 400 $depth)){if($f.Name -match $pattern){Ai-Sqlite $store $f.FullName $dir}} } # Session files by age and by whether the project they name still exists. function Ai-SessionRows([string]$store,$files,[string]$cwdKey,[string]$sourceKey,[string]$versionKey,[int]$headBytes=65536,[int]$readMax=300,[bool]$Truncated=$false) { $now=[DateTime]::UtcNow;[long]$bytes=0;$u15=0;$u30=0;$u90=0;$u120=0;$old=0;$newest=[DateTime]::MinValue;$oldest=[DateTime]::MaxValue;$zst=0;[long]$zstBytes=0 foreach($f in $files) { if($f.Name -match '\.zst$'){$zst++;$zstBytes+=$f.Length} $bytes+=$f.Length;$t=$f.LastWriteTimeUtc;$age=($now-$t).TotalDays if($age-le 15){$u15++}elseif($age-le 30){$u30++}elseif($age-le 90){$u90++}elseif($age-le 120){$u120++}else{$old++} if($t-gt $newest){$newest=$t};if($t-lt $oldest){$oldest=$t} } $wd=@{exists=0;missing=0;unknown=0;none=0};$sources=@{};$read=0;$version=$null if($cwdKey) { # A compressed transcript (Codex writes `.jsonl.zst`) has no readable head; it counts by age only. foreach($f in @($files|Where-Object {$_.Name -notmatch '\.zst$'}|Sort-Object LastWriteTimeUtc -Descending|Select-Object -First $readMax)) { if((Ai-Left)-lt 2500){break} $h=Ai-Head $f.FullName $headBytes;$read++ $c=Ai-JsonString $h $cwdKey $state=Ai-Workdir $c;$wd[$state]++ if($state-eq 'exists'){[void]$script:aiWorkdirs.Add($c.Replace('/','\'))} if($sourceKey){$v=Ai-Value (Ai-JsonString $h $sourceKey);if(-not $v){$v='none'};$sources[$v]=1+[int]$sources[$v]} if($versionKey -and -not $version){$version=Ai-Version (Ai-JsonString $h $versionKey)} } } [pscustomobject]@{Kind='AiSessions';Store=$store;Files=@($files).Count;Truncated=$Truncated;Bytes=$bytes;Days0To15=$u15;Days15To30=$u30;Days30To90=$u90;Days90To120=$u120;Over120Days=$old;NewestWriteUtc=(Ai-Utc $newest);OldestWriteUtc=(Ai-Utc $oldest);Compressed=$zst;CompressedBytes=$zstBytes;Read=$read;WorkdirExists=$wd.exists;WorkdirMissing=$wd.missing;WorkdirUnknown=$wd.unknown;WorkdirNone=$wd.none;NewestVersion=$version} foreach($k in $sources.Keys){[pscustomobject]@{Kind='AiSessionSource';Store=$store;Value=$k;Count=$sources[$k]}} } function Ai-FileMatch([string]$a,[string]$b) { $ia=Ai-Item $a;$ib=Ai-Item $b if(-not $ia -or -not $ib -or $ia.PSIsContainer -or $ib.PSIsContainer){return $null} if($ia.Length-ne $ib.Length){return 'different-size'} # No content hash: a launcher and its version file are each 100 MB or more, and hashing them did not fit # the budget on a slow disk. Size and the version resource are enough to say which build it is. $va=Ai-FileVersion $a;$vb=Ai-FileVersion $b if($va -and $vb){if($va-eq $vb){'same-size-same-version'}else{'same-size-different-version'}}else{'same-size'} } function Ai-FileVersion([string]$p) { try{$v=[Diagnostics.FileVersionInfo]::GetVersionInfo($p);Safe-Version $(if($v.ProductVersion){$v.ProductVersion}else{$v.FileVersion})}catch{$null} } # Versioned install folders (old builds a cleanup could remove) and which one the launcher runs. function Ai-Versions([string]$id,[string]$dir,[string]$launcher,[string]$inner,[string]$currentLeaf) { if($launcher) { $l=Ai-Item $launcher if($l){$lk=Ai-Link $l;$hard=$false;try{$hard=([string]$l.LinkType)-eq 'HardLink'}catch{};[pscustomobject]@{Kind='AiLauncher';Id=$id;Status='present';Bytes=$(if(-not $l.PSIsContainer){$l.Length}else{$null});FileVersion=$(if(-not $l.PSIsContainer){Ai-FileVersion $launcher}else{$null});HardLink=$hard;LinkType=$lk.Type;LinkLeaf=$lk.Leaf;NewestWriteUtc=(Ai-Utc $l.LastWriteTimeUtc)}} else{[pscustomobject]@{Kind='AiLauncher';Id=$id;Status='missing'}} } if(-not (Ai-Item $dir)){return} $kids=@();try{$kids=@(([IO.DirectoryInfo]::new($dir)).GetFileSystemInfos()|Sort-Object LastWriteTimeUtc -Descending|Select-Object -First 30)}catch{return} foreach($k in $kids) { $e=Ai-Entry $id $k 2500 $exe=$null if($k -is [IO.FileInfo]){$exe=$k.FullName}elseif($inner){$c=Ai-Join $k.FullName $inner;if([IO.File]::Exists($c)){$exe=$c}} [pscustomobject]@{Kind='AiVersion';Id=$id;Name=$(if(Ai-Version $k.Name){$k.Name}else{$e.Name});Status=$e.Status;Bytes=$e.Bytes;NewestWriteUtc=$e.NewestWriteUtc;FileVersion=$(if($exe){Ai-FileVersion $exe}else{$null});Current=$(if($currentLeaf){$k.Name-eq $currentLeaf}else{$null});LauncherMatch=$(if($exe -and $launcher){Ai-FileMatch $launcher $exe}else{$null})} } } function Ai-Worktree([string]$root,[string]$dir) { $it=Ai-Item $dir if(-not $it){return} $row=[ordered]@{Kind='AiWorktree';Root=$root;Name=(Ai-Alias $it.Name);Git='none';GitDirRelative=$null;GitDirSlash=$null;GitDirExists=$null;Locked=$null;IndexLock=$null;BackPointer=$null;TopLinks=0;Status=$null;Files=$null;Bytes=$null;NewestWriteUtc=$null} $g=Ai-Item (Ai-Join $dir '.git') if($g -and $g.PSIsContainer){$row.Git='directory'} elseif($g) { $line=([string](Ai-Head $g.FullName 4096) -split "`r?`n")[0] if($line -match '^gitdir:\s*(.+)$') { $gd=$Matches[1].Trim();$abs=$gd $rel=-not ($gd -match '^[A-Za-z]:' -or $gd.StartsWith('/') -or $gd.StartsWith('\\')) if($rel){try{$abs=[IO.Path]::GetFullPath((Ai-Join $dir $gd))}catch{}} $abs=$abs.Replace('/','\') $row.Git='file';$row.GitDirRelative=$rel;$row.GitDirSlash=$gd.Contains('/') if(-not (Ai-Local $abs)){$row.GitDirExists=$null;$row.Git='file-not-local'}else{ $row.GitDirExists=[IO.Directory]::Exists($abs);$row.Locked=[IO.File]::Exists((Ai-Join $abs 'locked'));$row.IndexLock=[IO.File]::Exists((Ai-Join $abs 'index.lock')) $back=Ai-Head (Ai-Join $abs 'gitdir') 4096 if($back){$row.BackPointer=((Ai-Backslash $back.Trim()).TrimEnd('\') -ieq (Ai-Join $dir '.git'))}} } else {$row.Git='other-file'} } foreach($c in (Ai-Children $dir)) { if($c.Attributes -band [IO.FileAttributes]::ReparsePoint){$row.TopLinks++} elseif($c.PSIsContainer -and $c.Name-eq 'node_modules'){$row.TopLinks+=@(Ai-Children $c.FullName|Where-Object {$_.Attributes -band [IO.FileAttributes]::ReparsePoint}).Count} } $m=Ai-Measure $dir 2000 $row.Status=$m.Status;$row.Files=$m.Files;$row.Bytes=$m.LogicalBytes;$row.NewestWriteUtc=$m.NewestWriteUtc [pscustomobject]$row } function Ai-Matches([string]$s) { $s -match '(?i)(?@:" from .NET Runtime 1026, the crashes crash.log cannot hear. RuntimeCrashes=$(if((Rows 'AppEvents' 'RuntimeCrashQuery'|Where-Object {$_.Status-in @('complete','no-matching-events')})){,@(Rows 'AppEvents' 'RuntimeCrash'|ForEach-Object {$(if(@($_.Exceptions).Count){[string](@($_.Exceptions)[0])}else{[string]$_.NativeCode})+'@'+$(if(@($_.MoleFrames).Count){[string](@($_.MoleFrames)[0])}else{[string]$_.Description})}|Group-Object|Sort-Object Name|ForEach-Object {$_.Name+':'+$_.Count})}else{$null}) UnfinishedUpdateAttempts=$(if($attempts){$attempts.Unfinished}elseif($updateLog.Status-in @('complete','none-recorded')){0}else{$null}) ElevationWaitSeconds=$(if($attempts){$attempts.LongestElevationWaitSeconds}else{$null}) # Schema 21: sleeps and resumes in 14 days, so a long UAC wait can be told from a PC that slept. SleepWake=(Sleep-Summary (Rows 'System' 'SleepSummary'|Select-Object -First 1)) TraySecondaryEchoes=$(if($trayAvailable){@(Rows 'Status' 'TrayEvent'|Where-Object {$_.Event-eq 'secondary-echo'}).Count}else{$null}) PanelExternalMoves=$(if($panelAvailable){@(Rows 'Status' 'PanelPlacement'|Where-Object {$_.Moved-eq $true}).Count}else{$null}) FreezeSignals=$(if((Complete 'Freeze') -and -not @(Rows 'Freeze' 'FreezeEvents'|Where-Object {$_.Status-ne 'no-matching-events'}).Count){,@(Rows 'Freeze' 'FreezeEvent'|ForEach-Object {[string]$_.Category+$(if($_.Code){':'+$_.Code}elseif($_.Image){':'+$_.Image}else{''})}|Group-Object|Sort-Object Name|ForEach-Object {$_.Name+':'+$_.Count})}else{$null}) # Schema 14 (U88). ShaderCaches=(Shader-Summary $Sections) AnalyzeSuspectRoots=$(if(Complete 'Analyze'){,@(Rows 'Analyze' 'AnalyzeRootCheck'|Where-Object {$_.Verdict-ne 'ok'}|ForEach-Object {[string]$_.Letter+':'+[string]$_.Verdict})}else{$null}) OperationFailures7d=$(if($operationSummary){$week=if($operationSummary.PSObject.Properties['Counts7d']){$operationSummary.Counts7d}else{$operationSummary.Counts};[int](($week|Where-Object Result -eq 'failed'|Measure-Object Count -Sum).Sum)}elseif($operationLog.Status-eq 'none-recorded'){0}else{$null}) # Schema 21: started operations a killed process never finished, closed by the next start. OperationsAbandoned7d=$(if($operationSummary){$wk=if($operationSummary.PSObject.Properties['Counts7d']){$operationSummary.Counts7d}else{$operationSummary.Counts};[int](($wk|Where-Object Result -eq 'abandoned'|Measure-Object Count -Sum).Sum)}else{$null}) TimedOutOrFailed=@($problems) } } function Crash-Module([string]$value) { switch -Regex ($value.ToLowerInvariant()) { '^(mole\.exe|mole\.dll)$' {'mole';break} '^(ntdll|kernelbase|kernel32|combase|ucrtbase)\.dll$' {'windows';break} '^(microsoft\.ui\.xaml|microsoft\.windowsappsdk[^\\/]*)\.dll$' {'windows-app-sdk';break} '^(nvwgf2umx|nvwgf2um|atidxx64|atidxx32|igd10iumd64|igd10iumd32)\.dll$' {'graphics-driver';break} default {'other'} } } function Read-LogSample([string]$path) { $path=Local-MetadataPath $path if(-not $path){throw 'Metadata refused'} $item=Get-Item -LiteralPath $path -Force if($item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Metadata refused'} $stream=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)) try { $buffer=New-Object byte[] 65536 $count=$stream.Read($buffer,0,$buffer.Length);$head=[Text.Encoding]::UTF8.GetString($buffer,0,$count) if($stream.Length-le $buffer.Length){return $head} [void]$stream.Seek([Math]::Max($stream.Position,$stream.Length-$buffer.Length),[IO.SeekOrigin]::Begin) $count=$stream.Read($buffer,0,$buffer.Length);$tail=[Text.Encoding]::UTF8.GetString($buffer,0,$count) return $head+"`n"+$tail }finally{$stream.Dispose()} } function Initialize-MetadataWalker { if ('MoleFeedbackNative' -as [type]) { return } # The parent compiles once and hands workers the assembly: five workers each running csc took longer # than the collection itself once they ran side by side. $compiled=$env:MOLE_FEEDBACK_NATIVE if($compiled -and [IO.File]::Exists($compiled)){ try { Add-Type -Path $compiled; return } catch {} } Add-Type -TypeDefinition (MetadataWalker-Source) } function MetadataWalker-Source { @' using System; using System.IO; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; public static class MoleFeedbackNative { public sealed class ProcessRow { public int Pid, Parent; public long Created, Cpu, PrivateWorkingSet; public string Image; } [DllImport("ntdll.dll")] static extern int NtQuerySystemInformation(int kind, IntPtr buffer, int length, out int needed); public static List Processes() { int size=524288; while(size<=8388608) { IntPtr buffer=Marshal.AllocHGlobal(size); try { int needed; int status=NtQuerySystemInformation(5,buffer,size,out needed); if(status==unchecked((int)0xC0000004)){size=Math.Max(size*2,needed+65536);continue;} if(status!=0)throw new InvalidOperationException("Process snapshot unavailable"); var rows=new List(); for(int offset=0;offset+104<=size;) { IntPtr p=IntPtr.Add(buffer,offset);int next=Marshal.ReadInt32(p); long name=Marshal.ReadInt64(p,64);int length=(ushort)Marshal.ReadInt16(p,56); string image=""; if(name>=buffer.ToInt64() && name+length<=buffer.ToInt64()+size && length%2==0)image=Marshal.PtrToStringUni(new IntPtr(name),length/2); rows.Add(new ProcessRow{Pid=(int)Marshal.ReadInt64(p,80),Parent=(int)Marshal.ReadInt64(p,88),Created=Marshal.ReadInt64(p,32),Cpu=Marshal.ReadInt64(p,40)+Marshal.ReadInt64(p,48),PrivateWorkingSet=Marshal.ReadInt64(p,8),Image=image}); if(next==0)break;if(next<104 || offset+next>size)throw new InvalidOperationException("Invalid process snapshot");offset+=next; } return rows; }finally{Marshal.FreeHGlobal(buffer);} } throw new InvalidOperationException("Process snapshot limit"); } [DllImport("kernel32.dll")] public static extern ulong GetTickCount64(); [StructLayout(LayoutKind.Sequential)] public struct Rect { public int Left, Top, Right, Bottom; } [DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect); [DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window); [DllImport("user32.dll")] public static extern bool IsZoomed(IntPtr window); [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); [DllImport("user32.dll")] public static extern uint GetDoubleClickTime(); [DllImport("user32.dll")] public static extern int GetSystemMetrics(int index); [DllImport("user32.dll", EntryPoint = "SystemParametersInfoW")] static extern bool ReadBoolParameter(uint action, uint param, out int value, uint flags); // SM_REMOTESESSION, and SPI_GETCLIENTAREAANIMATION: null when Windows would not answer. public static bool RemoteSession() { return GetSystemMetrics(0x1000) != 0; } public static bool? ClientAreaAnimation() { int on; if (!ReadBoolParameter(0x1042, 0, out on, 0)) return null; return on != 0; } [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr window); [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window); [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint process); [DllImport("user32.dll")] static extern uint GetGuiResources(IntPtr process, uint flags); public static uint GdiObjects(IntPtr process) { return GetGuiResources(process, 0); } public static uint UserObjects(IntPtr process) { return GetGuiResources(process, 1); } [DllImport("user32.dll")] static extern IntPtr MonitorFromWindow(IntPtr window, uint flags); [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct MonitorInfoEx { public int cbSize; public Rect monitor, work; public uint flags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string device; } [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool GetMonitorInfoW(IntPtr monitor, ref MonitorInfoEx info); [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct DevMode { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string deviceName; public short specVersion, driverVersion, size, driverExtra; public int fields; public int positionX, positionY, orientation, fixedOutput; public short color, duplex, yResolution, ttOption, collate; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string formName; public short logPixels; public int bitsPerPel, pelsWidth, pelsHeight, displayFlags, displayFrequency; public int icmMethod, icmIntent, mediaType, ditherType, reserved1, reserved2, panningWidth, panningHeight; } [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool EnumDisplaySettingsW(string device, int mode, ref DevMode devMode); // The refresh rate of the monitor the window is on, which WMI's video controller rows leave empty on some PCs. public static int RefreshRate(IntPtr window) { var info = new MonitorInfoEx(); info.cbSize = Marshal.SizeOf(typeof(MonitorInfoEx)); if (!GetMonitorInfoW(MonitorFromWindow(window, 2), ref info)) return 0; var mode = new DevMode(); mode.size = (short)Marshal.SizeOf(typeof(DevMode)); return EnumDisplaySettingsW(info.device, -1, ref mode) ? mode.displayFrequency : 0; } [DllImport("kernel32.dll")] static extern IntPtr OpenThread(uint access, bool inherit, uint id); [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle); [DllImport("ntdll.dll")] static extern int NtQueryInformationThread(IntPtr thread, int infoClass, out IntPtr info, int size, IntPtr returned); public sealed class ThreadRow { public int Id; public string Module; public string Origin; public double CpuMs; public string State; public string WaitReason; } // System CPU without WMI: perf providers time out on a loaded PC (WBEM_S_TIMEDOUT, feedback-6). Kernel time includes idle. [DllImport("kernel32.dll")] static extern bool GetSystemTimes(out long idle, out long kernel, out long user); public sealed class CpuTimes { public long Idle, Kernel, User; } public static CpuTimes SystemTimes() { long idle, kernel, user; if (!GetSystemTimes(out idle, out kernel, out user)) throw new InvalidOperationException("System times unavailable"); return new CpuTimes { Idle = idle, Kernel = kernel, User = user }; } [StructLayout(LayoutKind.Sequential)] public struct MemoryStatus { public uint Length, Load; public ulong TotalPhys, AvailPhys, TotalPageFile, AvailPageFile, TotalVirtual, AvailVirtual, AvailExtendedVirtual; } [DllImport("kernel32.dll", SetLastError=true)] static extern bool GlobalMemoryStatusEx(ref MemoryStatus status); public static MemoryStatus Memory() { var s = new MemoryStatus(); s.Length = (uint)Marshal.SizeOf(typeof(MemoryStatus)); if (!GlobalMemoryStatusEx(ref s)) throw new InvalidOperationException("Memory status unavailable"); return s; } // PDH as Mole reads it: English paths, one query, two collects, the same format flags (Mole-App#3: the CPU // tile read 0% with no speed or limit while Task Manager showed 16%). Status codes and numbers only. [DllImport("pdh.dll", CharSet=CharSet.Unicode)] static extern uint PdhOpenQueryW(string source, IntPtr user, out IntPtr query); [DllImport("pdh.dll", CharSet=CharSet.Unicode)] static extern uint PdhAddEnglishCounterW(IntPtr query, string path, IntPtr user, out IntPtr counter); [DllImport("pdh.dll")] static extern uint PdhCollectQueryData(IntPtr query); [DllImport("pdh.dll")] static extern uint PdhCloseQuery(IntPtr query); [StructLayout(LayoutKind.Explicit)] struct PdhValue { [FieldOffset(0)] public uint CStatus; [FieldOffset(8)] public double Double; } [DllImport("pdh.dll")] static extern uint PdhGetFormattedCounterValue(IntPtr counter, uint format, IntPtr type, out PdhValue value); [DllImport("pdh.dll", CharSet=CharSet.Unicode)] static extern uint PdhGetFormattedCounterArrayW(IntPtr counter, uint format, ref uint size, out uint count, IntPtr buffer); public sealed class PdhCounterRow { public string Id; public uint AddStatus; public uint FormatStatus; public uint ValueStatus; public double Value; public bool HasValue; public uint Instances; public uint ArrayStatus; public string[] Names; public double[] Values; } public sealed class PdhSession { public IntPtr Query; public uint OpenStatus; public uint FirstCollect; public uint SecondCollect; public PdhCounterRow[] Rows; public IntPtr[] Counters; public bool[] Wildcard; } public static PdhSession PdhStart(string[] ids, string[] paths) { var session = new PdhSession { Rows = new PdhCounterRow[paths.Length], Counters = new IntPtr[paths.Length], Wildcard = new bool[paths.Length] }; session.OpenStatus = PdhOpenQueryW(null, IntPtr.Zero, out session.Query); for (int i = 0; i < paths.Length; i++) { var row = new PdhCounterRow { Id = ids[i] }; session.Wildcard[i] = paths[i].Contains("(*)"); if (session.OpenStatus == 0) row.AddStatus = PdhAddEnglishCounterW(session.Query, paths[i], IntPtr.Zero, out session.Counters[i]); session.Rows[i] = row; } if (session.OpenStatus == 0) session.FirstCollect = PdhCollectQueryData(session.Query); return session; } public static PdhSession PdhFinish(PdhSession session) { if (session.OpenStatus != 0) return session; try { session.SecondCollect = PdhCollectQueryData(session.Query); for (int i = 0; i < session.Rows.Length; i++) { var row = session.Rows[i]; if (row.AddStatus != 0) continue; if (session.Wildcard[i]) { uint size = 0, count; row.ArrayStatus = PdhGetFormattedCounterArrayW(session.Counters[i], 0x8200, ref size, out count, IntPtr.Zero); row.Instances = count; // GPU engines and thermal zones need each instance's name and value. PDH_FMT_COUNTERVALUE_ITEM_W is a name pointer, then // the value's status at 8 and its double at 16 (the union is 8-aligned), 24 bytes a row on x86 and x64. if (row.ArrayStatus == 0x800007D2 && (row.Id.StartsWith("gpu-") || row.Id.StartsWith("thermal-")) && size > 0 && size < 16777216) { IntPtr buffer = Marshal.AllocHGlobal((int)size); try { row.ArrayStatus = PdhGetFormattedCounterArrayW(session.Counters[i], 0x8200, ref size, out count, buffer); if (row.ArrayStatus == 0) { row.Instances = count; row.Names = new string[count]; row.Values = new double[count]; for (int k = 0; k < count; k++) { IntPtr item = IntPtr.Add(buffer, k * 24); row.Names[k] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(item)); uint status = (uint)Marshal.ReadInt32(item, 8); row.Values[k] = status == 0 || status == 1 ? BitConverter.Int64BitsToDouble(Marshal.ReadInt64(item, 16)) : double.NaN; } } } finally { Marshal.FreeHGlobal(buffer); } } continue; } PdhValue value; row.FormatStatus = PdhGetFormattedCounterValue(session.Counters[i], 0x8200, IntPtr.Zero, out value); row.ValueStatus = value.CStatus; if (row.FormatStatus == 0 && (value.CStatus == 0 || value.CStatus == 1)) { row.Value = value.Double; row.HasValue = true; } } } finally { PdhCloseQuery(session.Query); session.Query = IntPtr.Zero; } return session; } // Monitors and the taskbar in physical pixels: the thread is made per-monitor aware for these calls only. public sealed class MonitorRow { public int Index; public bool Primary; public Rect Bounds, Work; public uint Dpi; } delegate bool MonitorProc(IntPtr monitor, IntPtr hdc, IntPtr rect, IntPtr data); [DllImport("user32.dll")] static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr clip, MonitorProc proc, IntPtr data); [StructLayout(LayoutKind.Sequential)] struct MonitorInfo { public int cbSize; public Rect monitor, work; public uint flags; } [DllImport("user32.dll")] static extern bool GetMonitorInfoW(IntPtr monitor, ref MonitorInfo info); [DllImport("shcore.dll")] static extern int GetDpiForMonitor(IntPtr monitor, int type, out uint x, out uint y); public static List Monitors() { var rows = new List(); var previous = SetThreadDpiAwarenessContext(new IntPtr(-4)); try { MonitorProc proc = (IntPtr m, IntPtr hdc, IntPtr r, IntPtr d) => { var info = new MonitorInfo(); info.cbSize = Marshal.SizeOf(typeof(MonitorInfo)); if (!GetMonitorInfoW(m, ref info)) return true; uint dx = 0, dy = 0; if (GetDpiForMonitor(m, 0, out dx, out dy) != 0) dx = 0; rows.Add(new MonitorRow { Index = rows.Count, Primary = (info.flags & 1) == 1, Bounds = info.monitor, Work = info.work, Dpi = dx }); return rows.Count < 16; }; EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, proc, IntPtr.Zero); GC.KeepAlive(proc); } finally { if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous); } return rows; } [StructLayout(LayoutKind.Sequential)] struct AppBarData { public int cbSize; public IntPtr hWnd; public uint callback, edge; public Rect rect; public IntPtr lParam; } [DllImport("shell32.dll")] static extern UIntPtr SHAppBarMessage(uint message, ref AppBarData data); public sealed class TaskbarInfo { public bool Found; public uint Edge; public Rect Rect; public uint State; } public static TaskbarInfo Taskbar() { var t = new TaskbarInfo(); var previous = SetThreadDpiAwarenessContext(new IntPtr(-4)); try { var data = new AppBarData(); data.cbSize = Marshal.SizeOf(typeof(AppBarData)); t.Found = SHAppBarMessage(5, ref data) != UIntPtr.Zero; if (t.Found) { t.Edge = data.edge; t.Rect = data.rect; } var state = new AppBarData(); state.cbSize = Marshal.SizeOf(typeof(AppBarData)); t.State = (uint)SHAppBarMessage(4, ref state).ToUInt64(); } finally { if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous); } return t; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct DisplayDevice { public int cb; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string name; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string description; public int flags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string id; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string key; } [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool EnumDisplayDevicesW(string device, uint index, ref DisplayDevice data, uint flags); // Adapter names stay in the worker, which reduces them to fixed categories. public static List DisplayAdapters() { var names = new List(); for (uint i = 0; i < 32; i++) { var d = new DisplayDevice(); d.cb = Marshal.SizeOf(typeof(DisplayDevice)); if (!EnumDisplayDevicesW(null, i, ref d, 0)) break; if (!string.IsNullOrEmpty(d.description) && !names.Contains(d.description)) names.Add(d.description); } return names; } public sealed class ThreadSnapshot { public string Status = "complete"; public int Modules, Unresolved; public List Rows = new List(); } // Module file names only: a thread's Win32 start address resolved against the loaded modules // tells driver, WinUI, thread-pool and runtime threads apart without paths or stacks. // Where a module was loaded from, as a category only: Mole's own folder, Windows, a driver store package // (GPU user-mode drivers live there), or anything else. static string ModuleOrigin(string file, string appDir) { if (string.IsNullOrEmpty(file)) return "unknown"; var windows = Environment.GetFolderPath(Environment.SpecialFolder.Windows).TrimEnd('\\') + "\\"; if (file.StartsWith(windows + "System32\\DriverStore\\", StringComparison.OrdinalIgnoreCase)) return "driver"; if (file.StartsWith(windows, StringComparison.OrdinalIgnoreCase)) return "windows"; if (!string.IsNullOrEmpty(appDir) && file.StartsWith(appDir, StringComparison.OrdinalIgnoreCase)) return "mole"; return "other"; } static string ModuleName(string file) { var name = Path.GetFileName(file ?? ""); foreach (var c in name) if (!(char.IsLetterOrDigit(c) && c < 128) && c != '.' && c != '_' && c != '-') return "other"; return name.Length == 0 || name.Length > 64 ? "other" : name; } public static ThreadSnapshot Threads(int pid) { var s = new ThreadSnapshot(); try { using (var p = Process.GetProcessById(pid)) { var starts = new List(); var ends = new List(); var names = new List(); var origins = new List(); try { string appDir = null; try { appDir = Path.GetDirectoryName(p.MainModule.FileName).TrimEnd('\\') + "\\"; } catch { } foreach (ProcessModule m in p.Modules) { long b = m.BaseAddress.ToInt64(); starts.Add(b); ends.Add(b + m.ModuleMemorySize); names.Add(ModuleName(m.FileName)); origins.Add(ModuleOrigin(m.FileName, appDir)); m.Dispose(); } } catch { s.Status = "modules-unavailable"; } s.Modules = names.Count; foreach (ProcessThread t in p.Threads) { var row = new ThreadRow(); row.Id = t.Id; row.Module = "(unresolved)"; row.Origin = "unknown"; IntPtr h = OpenThread(0x0040, false, (uint)t.Id); if (h == IntPtr.Zero) h = OpenThread(0x0800, false, (uint)t.Id); if (h != IntPtr.Zero) { try { IntPtr start; if (NtQueryInformationThread(h, 9, out start, IntPtr.Size, IntPtr.Zero) == 0) { long a = start.ToInt64(); for (int i = 0; i < starts.Count; i++) if (a >= starts[i] && a < ends[i]) { row.Module = names[i]; row.Origin = origins[i]; break; } } } finally { CloseHandle(h); } } if (row.Module == "(unresolved)") s.Unresolved++; try { row.CpuMs = t.TotalProcessorTime.TotalMilliseconds; } catch { } try { row.State = t.ThreadState == System.Diagnostics.ThreadState.Wait ? "Wait" : t.ThreadState == System.Diagnostics.ThreadState.Running ? "Running" : "Other"; } catch { row.State = "Unknown"; } // An enum name (UserRequest, EventPairLow...), valid only while the thread waits. if (row.State == "Wait") { try { row.WaitReason = t.WaitReason.ToString(); } catch { } } s.Rows.Add(row); t.Dispose(); } } } catch { s.Status = "unavailable"; } return s; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct Entry { public uint attributes; public System.Runtime.InteropServices.ComTypes.FILETIME creation, access, write; public uint high, low, tag, reserved; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)] public string name; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)] public string alternate; } [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr FindFirstFileW(string path, out Entry entry); [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool FindNextFileW(IntPtr handle, out Entry entry); [DllImport("kernel32.dll")] static extern bool FindClose(IntPtr handle); public sealed class Summary { public string Status = "complete"; public long Files, Directories, LongPaths, MaxPathCharacters, ReparseSkipped, ArchivesSkipped, Errors, ElapsedMs; public long? LogicalBytes; // Schema 14: the oldest and newest file write under the root, so a cache rebuild can be dated. public string OldestWriteUtc, NewestWriteUtc; public string Accounting = "logical bytes; hard links counted per name; no file contents read"; } public static Summary Scan(string root, int milliseconds, int maxEntries) { var r = new Summary(); var clock = Stopwatch.StartNew(); long oldest = long.MaxValue, newest = 0; try { root = Path.GetFullPath(root).TrimEnd('\\'); if (root.Length < 4 || root[1] != ':' || root[2] != '\\') { r.Status="refused-root-or-network"; return r; } foreach (var archive in new[]{@"\.codex\sessions", @"\.claude\projects"}) { var at=root.IndexOf(archive,StringComparison.OrdinalIgnoreCase); if(at>=0 && (at+archive.Length==root.Length || root[at+archive.Length]=='\\')) {r.Status="refused-chat-archive";return r;} } var drive = new DriveInfo(Path.GetPathRoot(root)); if (drive.DriveType != DriveType.Fixed) { r.Status="refused-nonfixed"; return r; } for (var p = new DirectoryInfo(root); p != null; p = p.Parent) { if ((File.GetAttributes(p.FullName) & FileAttributes.ReparsePoint) != 0) { r.Status="refused-reparse"; return r; } } if (!Directory.Exists(root)) { r.Status="missing"; return r; } r.LogicalBytes=0; var pending = new Stack(); pending.Push(root); while (pending.Count != 0) { if (clock.ElapsedMilliseconds >= milliseconds || r.Files+r.Directories >= maxEntries) { r.Status="partial-limit"; break; } var dir = pending.Pop(); Entry e; // Recheck every queued directory. Never enter known junctions or cloud placeholders. if ((File.GetAttributes("\\\\?\\"+dir) & FileAttributes.ReparsePoint) != 0) { r.ReparseSkipped++; continue; } var h = FindFirstFileW("\\\\?\\"+dir+"\\*", out e); if (h == new IntPtr(-1)) { var err=Marshal.GetLastWin32Error(); if(err!=2) r.Errors++; continue; } try { while (true) { if (e.name != "." && e.name != "..") { var path=dir+"\\"+e.name; var len=path.Length; r.MaxPathCharacters=Math.Max(r.MaxPathCharacters,len); if(len>=260) r.LongPaths++; if ((e.attributes & (0x400u|0x1000u|0x40000u|0x400000u)) != 0) r.ReparseSkipped++; else if ((e.attributes & 0x10) != 0) { r.Directories++; // Chat archives are not a cache and are outside this diagnostic's scope. if (!(dir.EndsWith("\\.codex",StringComparison.OrdinalIgnoreCase) && e.name.Equals("sessions",StringComparison.OrdinalIgnoreCase)) && !(dir.EndsWith("\\.claude",StringComparison.OrdinalIgnoreCase) && e.name.Equals("projects",StringComparison.OrdinalIgnoreCase))) pending.Push(path); else r.ArchivesSkipped++; } else { r.Files++; r.LogicalBytes += ((long)e.high<<32)+e.low; long written = ((long)(uint)e.write.dwHighDateTime<<32) | (uint)e.write.dwLowDateTime; if (written > 0) { if (written < oldest) oldest = written; if (written > newest) newest = written; } } } if (clock.ElapsedMilliseconds >= milliseconds || r.Files+r.Directories >= maxEntries) { r.Status="partial-limit"; break; } if (!FindNextFileW(h,out e)) { if(Marshal.GetLastWin32Error()!=18) r.Errors++; break; } } } finally { FindClose(h); } if (r.Status=="partial-limit") break; } if(r.Status=="complete" && (r.Errors>0 || r.ReparseSkipped>0 || r.ArchivesSkipped>0)) r.Status="partial-skipped"; } catch (UnauthorizedAccessException) { r.Status="denied"; } catch (DirectoryNotFoundException) { r.Status="missing"; } catch (FileNotFoundException) { r.Status="missing"; } catch { r.Status="unavailable"; } finally { r.ElapsedMs=clock.ElapsedMilliseconds; if (newest > 0) { try { r.OldestWriteUtc=DateTime.FromFileTimeUtc(oldest).ToString("o"); r.NewestWriteUtc=DateTime.FromFileTimeUtc(newest).ToString("o"); } catch { } } } return r; } // Analyze: the app's own listing calls, side by side with the Win32 enumeration, so a filter // driver that answers one and not the other shows as a difference instead of an empty drive. [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template); [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetFileInformationByHandleEx(Microsoft.Win32.SafeHandles.SafeFileHandle file, int infoClass, byte[] buffer, uint size); [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr FindFirstFileExW(string name, int level, out Entry data, int search, IntPtr filter, int flags); [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool GetVolumeNameForVolumeMountPointW(string mount, System.Text.StringBuilder name, int length); [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern int QueryDosDeviceW(string device, char[] target, int length); [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool GetVolumeInformationW(string root, System.Text.StringBuilder label, int labelLength, out uint serial, out uint maxComponent, out uint flags, System.Text.StringBuilder fileSystem, int fileSystemLength); [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern uint GetDriveTypeW(string root); [DllImport("kernel32.dll", EntryPoint="DeviceIoControl", SetLastError=true)] static extern bool DeviceIoControl(Microsoft.Win32.SafeHandles.SafeFileHandle device, uint code, byte[] input, uint inputSize, byte[] output, uint outputSize, out uint returned, IntPtr overlapped); [StructLayout(LayoutKind.Sequential)] struct DeviceInterfaceData { public int Size; public Guid InterfaceClassGuid; public uint Flags; public IntPtr Reserved; } [StructLayout(LayoutKind.Sequential)] struct DevInfoData { public int Size; public Guid ClassGuid; public uint DevInst; public IntPtr Reserved; } [DllImport("setupapi.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr SetupDiGetClassDevsW(ref Guid classGuid, string enumerator, IntPtr parent, uint flags); [DllImport("setupapi.dll", SetLastError=true)] static extern bool SetupDiEnumDeviceInterfaces(IntPtr set, IntPtr devInfo, ref Guid interfaceClass, uint index, ref DeviceInterfaceData data); [DllImport("setupapi.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool SetupDiGetDeviceInterfaceDetailW(IntPtr set, ref DeviceInterfaceData data, IntPtr detail, int detailSize, out int required, ref DevInfoData info); [DllImport("setupapi.dll", SetLastError=true)] static extern bool SetupDiDestroyDeviceInfoList(IntPtr set); [DllImport("cfgmgr32.dll")] static extern uint CM_Get_DevNode_Registry_PropertyW(uint devInst, uint property, IntPtr type, out uint buffer, ref int length, uint flags); [DllImport("cfgmgr32.dll")] static extern uint CM_Get_Parent(out uint parent, uint devInst, uint flags); [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool GetDiskFreeSpaceExW(string root, out ulong available, out ulong total, out ulong free); [DllImport("kernel32.dll")] static extern uint SetErrorMode(uint mode); public sealed class DirectoryProbe { public string Method; public string Status = "ok"; public int Error; public int Entries; public int Records; public int Directories; public bool Capped; public long ElapsedMs; } public static string ErrorStatus(int error) { switch (error) { case 0: return "ok"; case 5: return "denied"; case 2: case 3: return "not-found"; case 87: return "invalid-parameter"; case 1: return "invalid-function"; case 50: return "not-supported"; case 21: return "not-ready"; case 32: return "sharing"; case 1117: return "io-error"; case 1392: return "corrupt"; case 124: return "invalid-level"; default: return "error"; } } static bool IsDots(byte[] buffer, int at, int length) { if (length == 2) return buffer[at] == '.' && buffer[at+1] == 0; return length == 4 && buffer[at] == '.' && buffer[at+1] == 0 && buffer[at+2] == '.' && buffer[at+3] == 0; } static DirectoryProbe ReadClass(Microsoft.Win32.SafeHandles.SafeFileHandle handle, int restart, int next, int nameOffset, string method, int maxEntries) { var p = new DirectoryProbe { Method = method }; var clock = Stopwatch.StartNew(); var buffer = new byte[65536]; var infoClass = restart; while (true) { if (!GetFileInformationByHandleEx(handle, infoClass, buffer, (uint)buffer.Length)) { var error = Marshal.GetLastWin32Error(); if (error != 18) { p.Error = error; p.Status = ErrorStatus(error); } break; } infoClass = next; for (int offset = 0; offset + nameOffset <= buffer.Length;) { int step = BitConverter.ToInt32(buffer, offset), length = BitConverter.ToInt32(buffer, offset + 60); uint attributes = BitConverter.ToUInt32(buffer, offset + 56); p.Records++; if (length >= 0 && offset + nameOffset + length <= buffer.Length && !IsDots(buffer, offset + nameOffset, length)) { p.Entries++; if ((attributes & 0x10) != 0) p.Directories++; } if (step <= 0) break; offset += step; } if (p.Entries >= maxEntries) { p.Capped = true; break; } } p.ElapsedMs = clock.ElapsedMilliseconds; return p; } static Microsoft.Win32.SafeHandles.SafeFileHandle OpenListing(string path) { // The app's flags: list-directory, all sharing, backup semantics, the reparse point itself. return CreateFileW(path, 1, 7, IntPtr.Zero, 3, 0x02000000 | 0x00200000, IntPtr.Zero); } public static List ProbeDirectory(string path, int maxEntries) { var rows = new List(); var full = path.StartsWith(@"\\?\") ? path : @"\\?\" + path; var old = SetErrorMode(0x8001); try { var clock = Stopwatch.StartNew(); using (var handle = OpenListing(full)) { var open = new DirectoryProbe { Method = "open", ElapsedMs = clock.ElapsedMilliseconds }; if (handle.IsInvalid) { open.Error = Marshal.GetLastWin32Error(); open.Status = ErrorStatus(open.Error); } rows.Add(open); // FileIdExtdDirectoryInfo: what Mole's scanner reads; its name starts at 88. if (!handle.IsInvalid) rows.Add(ReadClass(handle, 0x14, 0x13, 88, "id-extd", maxEntries)); } using (var handle = OpenListing(full)) { // FileIdBothDirectoryInfo, the older class most filter drivers implement; name at 104. if (!handle.IsInvalid) rows.Add(ReadClass(handle, 0x0B, 0x0A, 104, "id-both", maxEntries)); } var find = new DirectoryProbe { Method = "find" }; clock.Restart(); Entry e; var h = FindFirstFileExW(full.TrimEnd('\\') + @"\*", 1, out e, 0, IntPtr.Zero, 2); if (h == new IntPtr(-1)) { var error = Marshal.GetLastWin32Error(); if (error != 2 && error != 18) { find.Error = error; find.Status = ErrorStatus(error); } } else { try { while (true) { find.Records++; if (e.name != "." && e.name != "..") { find.Entries++; if ((e.attributes & 0x10) != 0) find.Directories++; } if (find.Entries >= maxEntries) { find.Capped = true; break; } if (!FindNextFileW(h, out e)) { var error = Marshal.GetLastWin32Error(); if (error != 18) { find.Error = error; find.Status = ErrorStatus(error); } break; } } } finally { FindClose(h); } } find.ElapsedMs = clock.ElapsedMilliseconds; rows.Add(find); } finally { SetErrorMode(old); } return rows; } public sealed class VolumeRow { public string Letter; public uint DriveType; public string FileSystem; public bool LabelPresent; public uint? Serial; public string VolumeName; public string DosDevice; public ulong? TotalBytes, FreeBytes; public uint Flags; public string Status = "ok"; public uint? BusType; public bool? DeviceRemovable; public string EjectList; } // What the tray's Eject list decides for this letter (DriveEject.List and IsExternalFixedDisk in the app). public static string EjectVerdict(uint driveType, bool isSystem, bool substituted, bool? sameDiskAsSystem, uint? bus, bool? deviceRemovable) { if (driveType == 2) return "offered"; if (driveType != 3) return null; if (isSystem) return "no:startup-disk"; if (substituted) return "no:substituted"; if (sameDiskAsSystem == null) return "no:unreadable"; if (sameDiskAsSystem.Value) return "no:startup-disk"; if (bus == null) return "no:unreadable"; if (bus == 7 || bus == 4 || bus == 0xC || bus == 0xD) return "offered"; if (bus == 0x11) return deviceRemovable == true ? "offered" : "no:nvme-not-removable"; return "no:bus"; } static uint? DiskNumber(string path) { using (var handle = CreateFileW(path, 0, 3, IntPtr.Zero, 3, 0, IntPtr.Zero)) { if (handle.IsInvalid) return null; var output = new byte[12]; uint returned; if (!DeviceIoControl(handle, 0x2D1080, null, 0, output, (uint)output.Length, out returned, IntPtr.Zero) || returned < 8) return null; return BitConverter.ToUInt32(output, 4); } } static uint? DiskBus(string path) { using (var handle = CreateFileW(path, 0, 3, IntPtr.Zero, 3, 0, IntPtr.Zero)) { if (handle.IsInvalid) return null; var output = new byte[64]; uint returned; if (!DeviceIoControl(handle, 0x2D1400, new byte[12], 12, output, (uint)output.Length, out returned, IntPtr.Zero) || returned < 32) return null; return BitConverter.ToUInt32(output, 28); } } // The disk's device node or a parent carries CM_DEVCAP_REMOVABLE; a Thunderbolt NVMe disk has it only on a parent. static bool? DiskChainRemovable(uint disk) { var diskClass = new Guid("53f56307-b6bf-11d0-94f2-00a0c91efb8b"); var set = SetupDiGetClassDevsW(ref diskClass, null, IntPtr.Zero, 0x12); if (set == new IntPtr(-1)) return null; try { var iface = new DeviceInterfaceData(); iface.Size = Marshal.SizeOf(typeof(DeviceInterfaceData)); for (uint i = 0; SetupDiEnumDeviceInterfaces(set, IntPtr.Zero, ref diskClass, i, ref iface); i++) { var info = new DevInfoData(); info.Size = Marshal.SizeOf(typeof(DevInfoData)); int needed; SetupDiGetDeviceInterfaceDetailW(set, ref iface, IntPtr.Zero, 0, out needed, ref info); if (needed <= 0) continue; var detail = Marshal.AllocHGlobal(needed); try { Marshal.WriteInt32(detail, IntPtr.Size == 8 ? 8 : 6); if (!SetupDiGetDeviceInterfaceDetailW(set, ref iface, detail, needed, out needed, ref info)) continue; var number = DiskNumber(Marshal.PtrToStringUni(detail + 4)); if (number != disk) continue; var node = info.DevInst; for (var depth = 0; depth < 16; depth++) { uint flags; var size = 4; uint parent; if (CM_Get_DevNode_Registry_PropertyW(node, 0x10, IntPtr.Zero, out flags, ref size, 0) == 0 && (flags & 4) != 0) return true; if (CM_Get_Parent(out parent, node, 0) != 0) return false; node = parent; } return false; } finally { Marshal.FreeHGlobal(detail); } } return null; } finally { SetupDiDestroyDeviceInfoList(set); } } static void ReadEjectFacts(VolumeRow row, string systemLetter) { try { var path = @"\\.\" + row.Letter + ":"; var isSystem = string.Equals(row.Letter, systemLetter, StringComparison.OrdinalIgnoreCase); var substituted = row.DosDevice != null && row.DosDevice.StartsWith(@"\??\", StringComparison.Ordinal); var number = DiskNumber(path); var system = DiskNumber(@"\\.\" + systemLetter + ":"); row.BusType = DiskBus(path); if (row.BusType == 0x11 && number != null) row.DeviceRemovable = DiskChainRemovable(number.Value); bool? same = number == null || system == null ? (bool?)null : number == system; row.EjectList = EjectVerdict(row.DriveType, isSystem, substituted, same, row.BusType, row.DeviceRemovable); } catch (Exception) { row.EjectList = "no:unreadable"; } } public static List Volumes() { var rows = new List(); var old = SetErrorMode(0x8001); try { foreach (var letter in "CDEFGHIJKLMNOPQRSTUVWXYZAB") { var root = letter + @":\"; var type = GetDriveTypeW(root); if (type <= 1) continue; var row = new VolumeRow { Letter = letter.ToString(), DriveType = type }; var target = new char[1024]; if (QueryDosDeviceW(letter + ":", target, target.Length) > 0) row.DosDevice = new string(target, 0, Math.Max(0, Array.IndexOf(target, '\0'))); // Network, CD and RAM drives can block on a dead link; only their type is recorded. if (type == 3 || type == 2) { var name = new System.Text.StringBuilder(64); if (GetVolumeNameForVolumeMountPointW(root, name, name.Capacity)) row.VolumeName = name.ToString(); var label = new System.Text.StringBuilder(261); var fs = new System.Text.StringBuilder(261); uint serial, max, flags; if (GetVolumeInformationW(root, label, label.Capacity, out serial, out max, out flags, fs, fs.Capacity)) { row.Serial = serial; row.FileSystem = fs.ToString(); row.LabelPresent = label.Length > 0; row.Flags = flags; } else row.Status = ErrorStatus(Marshal.GetLastWin32Error()); ulong available, total, free; if (GetDiskFreeSpaceExW(root, out available, out total, out free)) { row.TotalBytes = total; row.FreeBytes = free; } ReadEjectFacts(row, (Environment.GetEnvironmentVariable("SystemDrive") ?? "C:").TrimEnd(':')); } rows.Add(row); } } finally { SetErrorMode(old); } return rows; } public sealed class SnapshotRow { public string Status = "ok"; public long Bytes; public int Schema; public long ScannedTicks; public string Root; public string FileSystem; public long Directories, Files; public int Denied; public bool Truncated; public int RootFlags; public bool RootPartial; public long RootAllocated, RootLogical; public int RootFiles, RootChildren; } static ulong Varint(BinaryReader reader) { ulong value = 0; for (int shift = 0; shift < 70; shift += 7) { var b = reader.ReadByte(); value |= (ulong)(b & 0x7F) << shift; if ((b & 0x80) == 0) return value; } throw new InvalidDataException(); } // DiskSnapshot.Schema this reader follows field by field (test_diagnose.py locks it to DiskSnapshot.cs). // Schema 5 (0.16.0) added the used-bytes header and the per-directory deduped bytes; the schema 4 layout // this reader kept read the used bytes as the root's name, threw past its catches and failed the whole // Analyze section for everyone who had mapped a drive. const int KnownSnapshotSchema = 5; public static SnapshotRow Snapshot(string file) { var r = new SnapshotRow(); try { r.Bytes = new FileInfo(file).Length; using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new BinaryReader(stream, System.Text.Encoding.UTF8)) { var magic = reader.ReadBytes(8); if (System.Text.Encoding.ASCII.GetString(magic) != "MOLEDSK1") { r.Status = "unrecognized"; return r; } r.Schema = reader.ReadInt32(); if (r.Schema != KnownSnapshotSchema) { r.Status = "other-schema"; return r; } r.ScannedTicks = reader.ReadInt64(); reader.ReadInt64(); r.Root = reader.ReadString(); r.FileSystem = reader.ReadString(); reader.ReadUInt32(); r.Directories = reader.ReadInt64(); r.Files = reader.ReadInt64(); r.Denied = reader.ReadInt32(); r.Truncated = reader.ReadBoolean(); if (Varint(reader) == 0) reader.ReadString(); r.RootFlags = reader.ReadByte(); r.RootPartial = reader.ReadBoolean(); reader.ReadInt64(); r.RootAllocated = (long)Varint(reader); r.RootLogical = (long)Varint(reader); Varint(reader); Varint(reader); Varint(reader); Varint(reader); Varint(reader); r.RootFiles = checked((int)Varint(reader)); for (int i = 0; i < r.RootFiles; i++) { reader.ReadString(); Varint(reader); Varint(reader); reader.ReadInt64(); reader.ReadByte(); } r.RootChildren = checked((int)Varint(reader)); } } catch (EndOfStreamException) { r.Status = "truncated"; } catch (InvalidDataException) { r.Status = "unrecognized"; } catch (IOException) { r.Status = "unreadable"; } catch (UnauthorizedAccessException) { r.Status = "denied"; } // Anything else is this one file's problem, never the section's. catch (Exception) { r.Status = "error"; } return r; } } '@ } } $sections = [ordered]@{ System = { Initialize-MetadataWalker [pscustomobject]@{ Kind='Clock'; TickMilliseconds=[MoleFeedbackNative]::GetTickCount64(); TimeZoneOffsetMinutes=[DateTimeOffset]::Now.Offset.TotalMinutes } $os = Get-CimInstance Win32_OperatingSystem -OperationTimeoutSec 8 [pscustomobject]@{ Kind='Windows'; Version=$os.Version; Build=$os.BuildNumber; LastBootUtc=$os.LastBootUpTime.ToUniversalTime().ToString('o'); CimUptimeSeconds=((Get-Date)-$os.LastBootUpTime).TotalSeconds; MemoryKiB=$os.TotalVisibleMemorySize; FreeMemoryKiB=$os.FreePhysicalMemory; Architecture=$env:PROCESSOR_ARCHITECTURE; Locale=(Get-UICulture).Name } try { $fast=(Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Power' -Name HiberbootEnabled).HiberbootEnabled [pscustomobject]@{ Kind='FastStartupConfiguration'; Enabled=($fast-eq 1); Note='Configuration does not prove the last boot type' } } catch { [pscustomobject]@{ Kind='FastStartupConfiguration'; Status=(Error-Status $_) } } foreach($provider in @('Microsoft-Windows-Kernel-Boot','Microsoft-Windows-Power-Troubleshooter')) { try { $ids=if($provider -eq 'Microsoft-Windows-Kernel-Boot') { @(27) } else { @(1) } # XPath timediff, never a StartTime: on a Windows 10 19045 (zh-CN) PC every StartTime query failed with DateTimeExpected. Get-WinEvent -LogName System -FilterXPath "*[System[Provider[@Name='$provider'] and ($(($ids|ForEach-Object {"EventID=$_"}) -join ' or ')) and TimeCreated[timediff(@SystemTime) <= 1209600000]]]" -MaxEvents 8 | ForEach-Object { $x=[xml]$_.ToXml(); $boot=$null foreach($d in $x.Event.EventData.Data) { if($d.Name -eq 'BootType') { $boot=[string]$d.'#text' } } [pscustomobject]@{ Kind='PowerEvent'; Provider=$provider; Id=$_.Id; Utc=$_.TimeCreated.ToUniversalTime().ToString('o'); BootType=$boot } } } catch { $failure=Event-QueryFailure $_; [pscustomobject]@{ Kind='PowerEvents'; Provider=$provider; Status=$failure.Status; Error=$failure.Error } } } # Schema 21: Kernel-Power 42/107, Power-Troubleshooter 1 and Modern Standby 506/507 over 14 days. try { $sleepQuery="*[System[((Provider[@Name='Microsoft-Windows-Kernel-Power'] and (EventID=42 or EventID=107 or EventID=506 or EventID=507)) or (Provider[@Name='Microsoft-Windows-Power-Troubleshooter'] and EventID=1)) and TimeCreated[timediff(@SystemTime) <= 1209600000]]]" Sleep-Facts @(Get-WinEvent -LogName System -FilterXPath $sleepQuery -MaxEvents 600 -ErrorAction Stop) } catch { $failure=Event-QueryFailure $_; if($failure.Status-eq 'no-matching-events'){ Sleep-Facts @() } else { [pscustomobject]@{ Kind='SleepSummary'; Status=$failure.Status; Error=$failure.Error } } } try { $log=Get-Service EventLog; [pscustomobject]@{ Kind='EventLogService'; Status=[string]$log.Status; StartType=[string]$log.StartType } } catch { [pscustomobject]@{ Kind='EventLogService'; Status=(Error-Status $_) } } # Shell settings Mole's tray and theme depend on: values only, no paths. $shell=[ordered]@{Kind='Shell';DoubleClickMs=[MoleFeedbackNative]::GetDoubleClickTime();DisplayVersion=$null;SystemLightTheme=$null;AppsLightTheme=$null;TrayPromoted=$null} try{$cv=Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction Stop; if([string]$cv.DisplayVersion -match '^[0-9A-Za-z]{2,6}$'){$shell.DisplayVersion=[string]$cv.DisplayVersion}}catch{} try{$theme=Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -ErrorAction Stop; $shell.SystemLightTheme=($theme.SystemUsesLightTheme -eq 1); $shell.AppsLightTheme=($theme.AppsUseLightTheme -eq 1)}catch{} try{foreach($icon in @(Get-ChildItem 'HKCU:\Control Panel\NotifyIconSettings' -ErrorAction Stop)){$v=Get-ItemProperty $icon.PSPath; if([string]$v.ExecutablePath -match '\\Mole\.exe$'){$shell.TrayPromoted=($v.IsPromoted -eq 1)}}}catch{} [pscustomobject]$shell try{foreach($b in @(Get-CimInstance Win32_Battery -OperationTimeoutSec 5)){[pscustomobject]@{Kind='Battery';ChargePercent=$b.EstimatedChargeRemaining;Status=$b.BatteryStatus}}}catch{} Get-CimInstance Win32_Processor -OperationTimeoutSec 8 | Select-Object @{n='Kind';e={'CPU'}},Name,NumberOfCores,NumberOfLogicalProcessors Get-CimInstance Win32_VideoController -OperationTimeoutSec 8 | Select-Object @{n='Kind';e={'GPU'}},Name,DriverVersion,@{n='DriverDate';e={if($_.DriverDate){$_.DriverDate.ToString('yyyy-MM-dd')}}},CurrentRefreshRate,MaxRefreshRate,CurrentHorizontalResolution,CurrentVerticalResolution try { Network-AdapterFacts } catch { [pscustomobject]@{ Kind='NetworkAdapters'; Status=(Error-Status $_); Error=(Error-Class $_) } } } Mole = { Initialize-MetadataWalker $exe=Join-Path $env:LOCALAPPDATA 'Tw93.Mole\current\Mole.exe' $channel=$null try { $manifest=Read-SmallText (Join-Path $env:LOCALAPPDATA 'Tw93.Mole\current\sq.version'); if([string]$manifest -match '(win-(?:x64|arm64)(?:-beta)?)'){$channel=$Matches[1]} } catch {} [pscustomobject]@{ Kind='Installed'; Exists=(Test-Path -LiteralPath $exe); Version=$(if(Test-Path -LiteralPath $exe){Safe-Version (Get-Item -LiteralPath $exe).VersionInfo.ProductVersion}else{$null}); Channel=$channel } # Launch layer (Mole Mac e95a7e485): what can stop an installed Mole from starting before any of its code runs. if(Test-Path -LiteralPath $exe) { $update=Join-Path $env:LOCALAPPDATA 'Tw93.Mole\Update.exe' foreach($pair in @(@('app',$exe),@('updater',$update))) { try { if(Test-Path -LiteralPath $pair[1]){Signature-Facts $pair[0] (Get-AuthenticodeSignature -LiteralPath $pair[1])}else{Signature-Facts $pair[0] $null} } catch { [pscustomobject]@{Kind='LaunchSignature';Role=$pair[0];Status=(Error-Status $_)} } } $zone=$null;$zoneStatus='none' try { $zone=Zone-Id ((Get-Content -LiteralPath $exe -Stream 'Zone.Identifier' -ErrorAction Stop) -join "`n");$zoneStatus=$(if($null-ne $zone){'complete'}else{'unreadable'}) } catch { if([string]$_.FullyQualifiedErrorId -notlike '*GetContentReaderFileNotFoundError*' -and $_.Exception -isnot [IO.FileNotFoundException]){$zoneStatus=(Error-Status $_)} } $sac=$null try { $value=(Get-ItemProperty -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Control\CI\Policy' -Name 'VerifiedAndReputablePolicyState' -ErrorAction Stop).VerifiedAndReputablePolicyState; $sac=$(if($value-eq 0){'off'}elseif($value-eq 1){'on'}elseif($value-eq 2){'evaluation'}else{'other'}) } catch { $sac=$null } [pscustomobject]@{Kind='Launch';ZoneId=$zone;ZoneStatus=$zoneStatus;SmartAppControl=$sac} try { Defender-LaunchFacts @(Get-CimInstance -Namespace 'root/Microsoft/Windows/Defender' -ClassName 'MSFT_MpThreatDetection' -OperationTimeoutSec 5 -ErrorAction Stop) | Select-Object -First 8; [pscustomobject]@{Kind='LaunchDefenderQuery';Status='complete'} } catch { [pscustomobject]@{Kind='LaunchDefenderQuery';Status=(Error-Status $_);Error=(Error-Class $_)} } try { CodeIntegrity-LaunchFacts @(Get-WinEvent -LogName 'Microsoft-Windows-CodeIntegrity/Operational' -FilterXPath '*[System[(EventID=3033 or EventID=3077 or EventID=3089) and TimeCreated[timediff(@SystemTime) <= 1209600000]]]' -MaxEvents 200 -ErrorAction Stop) | Select-Object -First 8; [pscustomobject]@{Kind='LaunchCodeIntegrityQuery';Status='complete'} } catch { $failure=Event-QueryFailure $_; [pscustomobject]@{Kind='LaunchCodeIntegrityQuery';Status=$failure.Status;Error=$failure.Error} } } else { [pscustomobject]@{Kind='Launch';Status='not-installed'} } try { Clean-ScanFacts (Read-SmallText (Join-Path $env:LOCALAPPDATA 'Mole\clean-scan-summary.json') -LocalOnly) ([DateTime]::UtcNow) } catch { [pscustomobject]@{Kind='CleanScan';Status=(Error-Status $_)} } $ps=@(Get-Process -Name Mole -ErrorAction SilentlyContinue) foreach($p in $ps) { [pscustomobject]@{ Kind='Running'; Version=(Safe-Version $p.ProductVersion); WorkingSetBytes=$p.WorkingSet64; PrivateBytes=$p.PrivateMemorySize64; HandleCount=$p.HandleCount; ThreadCount=$p.Threads.Count; Responding=$p.Responding; HasWindow=($p.MainWindowHandle -ne 0) } if($p.MainWindowHandle-ne 0) { $previous=[MoleFeedbackNative]::SetThreadDpiAwarenessContext([IntPtr]::new(-4)) try { $rect=New-Object MoleFeedbackNative+Rect if([MoleFeedbackNative]::GetClientRect($p.MainWindowHandle,[ref]$rect)) { $fgPid=[uint32]0;[void][MoleFeedbackNative]::GetWindowThreadProcessId([MoleFeedbackNative]::GetForegroundWindow(),[ref]$fgPid) [pscustomobject]@{Kind='Window';ClientWidthPx=$rect.Right-$rect.Left;ClientHeightPx=$rect.Bottom-$rect.Top;Dpi=[MoleFeedbackNative]::GetDpiForWindow($p.MainWindowHandle);Maximized=[MoleFeedbackNative]::IsZoomed($p.MainWindowHandle);Minimized=[MoleFeedbackNative]::IsIconic($p.MainWindowHandle);Visible=[MoleFeedbackNative]::IsWindowVisible($p.MainWindowHandle);Foreground=($fgPid-eq $p.Id);RefreshHz=$(try{[MoleFeedbackNative]::RefreshRate($p.MainWindowHandle)}catch{$null})} } }finally{if($previous-ne [IntPtr]::Zero){[void][MoleFeedbackNative]::SetThreadDpiAwarenessContext($previous)}} } } # Three samples distinguish a single large working set from short-term growth. # Stable aliases correlate rows without exporting PIDs or executable paths. $sampled=@($ps | Select-Object -First 4) $threadsBefore=@{};$threadClock=[Diagnostics.Stopwatch]::StartNew() for($sample=0;$sample-lt 3 -and $sampled.Count-gt 0;$sample++) { if($sample-gt 0){Start-Sleep -Seconds 2} for($i=0;$i-lt $sampled.Count;$i++) { try {Memory-Sample $sampled[$i] $sample ('mole-'+($i+1))} catch {[pscustomobject]@{Kind='MemorySample';Instance=('mole-'+($i+1));Index=$sample;Status=(Error-Status $_)}} if($sample-eq 0){$threadsBefore[$i]=[MoleFeedbackNative]::Threads($sampled[$i].Id)} if($sample-eq 2){try{Thread-Facts $threadsBefore[$i] ([MoleFeedbackNative]::Threads($sampled[$i].Id)) ('mole-'+($i+1)) $threadClock.ElapsedMilliseconds}catch{[pscustomobject]@{Kind='ThreadSummary';Instance=('mole-'+($i+1));Status=(Error-Status $_);Error=(Error-Class $_)}}} } } for($i=0;$i-lt $sampled.Count;$i++) { try {Child-Processes $sampled[$i].Id ('mole-'+($i+1))}catch{[pscustomobject]@{Kind='ChildProcess';Instance=('mole-'+($i+1));Status=(Error-Status $_)}} } try { $crash=Local-MetadataPath (Join-Path $env:LOCALAPPDATA 'Mole\logs\crash.log') if($crash -and (Test-Path -LiteralPath $crash -PathType Leaf)){Crash-Facts (Read-LogSample $crash)}else{[pscustomobject]@{Kind='CrashLog';Entries=0;RecentEntries=0}} }catch{[pscustomobject]@{Kind='CrashLog';Status=(Error-Status $_)}} try { $license=Join-Path $env:LOCALAPPDATA 'Mole\logs\license.log' if(Test-Path -LiteralPath $license -PathType Leaf){$tail=Read-TailText $license 131072;$events=@(License-Facts $tail.Text);[pscustomobject]@{Kind='LicenseLog';Status='complete';Partial=$tail.Partial;Events=$events.Count};$events} else{[pscustomobject]@{Kind='LicenseLog';Status='none-recorded'}} }catch{[pscustomobject]@{Kind='LicenseLog';Status=(Error-Status $_)}} try { # Schema 19: the Status sampler's breadcrumb, the newest 64 KiB (the app keeps at most that). $steps=Join-Path $env:LOCALAPPDATA 'Mole\logs\status-steps.log' if(Test-Path -LiteralPath $steps -PathType Leaf){$tail=Read-TailText $steps 65536;$rows=@(StatusStep-Facts $tail.Text);[pscustomobject]@{Kind='StatusSteps';Status='complete';Partial=$tail.Partial;Sessions=$rows.Count};$rows} else{[pscustomobject]@{Kind='StatusSteps';Status='none-recorded'}} }catch{[pscustomobject]@{Kind='StatusSteps';Status=(Error-Status $_)}} try { # The whole retained log: the rotated half (operations.1.jsonl) first, then the live file, each at most 2 MiB. $operations=Join-Path $env:LOCALAPPDATA 'Mole\operations.jsonl';$rotated=Join-Path $env:LOCALAPPDATA 'Mole\operations.1.jsonl' $parts=@(foreach($file in @($rotated,$operations)){if(Test-Path -LiteralPath $file -PathType Leaf){(Read-TailText $file 3145728).Text}}) if($parts.Count){Operation-Facts ($parts -join "`n")} else{[pscustomobject]@{Kind='OperationLog';Status='none-recorded'};Shader-CleanFacts @()} }catch{[pscustomobject]@{Kind='OperationLog';Status=(Error-Status $_)}} # One read of the class for every sampled process, with a longer timeout: a filtered query per process timed out at # 3 s on a loaded PC (0.15.0 report), and the provider walks every instance for a filter anyway. $gpuMemory=$null;$gpuMemoryError=$null if($sampled.Count){try{$gpuMemory=@(Get-CimInstance Win32_PerfRawData_GPUPerformanceCounters_GPUProcessMemory -OperationTimeoutSec 10)}catch{$gpuMemoryError=$_}} for($i=0;$i-lt $sampled.Count;$i++) { try { if($gpuMemoryError){throw $gpuMemoryError} $memory=@($gpuMemory | Where-Object {([string]$_.Name).StartsWith(('pid_'+$sampled[$i].Id+'_'),[StringComparison]::OrdinalIgnoreCase)}) $dedicated=0L;$shared=0L;$committed=0L foreach($m in $memory){$dedicated+=[long]$m.DedicatedUsage;$shared+=[long]$m.SharedUsage;$committed+=[long]$m.TotalCommitted} [pscustomobject]@{Kind='GpuMemory';Instance=('mole-'+($i+1));Status=$(if($memory.Count){'complete'}else{'no-counters'});DedicatedBytes=$(if($memory.Count){$dedicated}else{$null});SharedBytes=$(if($memory.Count){$shared}else{$null});CommittedBytes=$(if($memory.Count){$committed}else{$null});CounterCount=$memory.Count} }catch{[pscustomobject]@{Kind='GpuMemory';Instance=('mole-'+($i+1));Status=(Error-Status $_);Error=(Error-Class $_)}} } if($ps.Count-eq 0){[pscustomobject]@{Kind='Running';Status='not-running'}} Text-ScaleFacts 'HKCU:\Software\Microsoft\Accessibility' $settings=Read-SmallText (Join-Path $env:LOCALAPPDATA 'Mole\settings.json') if($settings){ # Behaviour switches only, each a bool or an enum word; shortcuts, ignored app names and license data stay behind. $s=$settings|ConvertFrom-Json function Flag($value){ if($value -is [bool]){$value}elseif([string]$value -match '^[A-Za-z]{1,32}$'){[string]$value}else{$null} } [pscustomobject]@{Kind='Settings'; Language=$(if([string]$s.Language -match '^[a-z]{2}(-[A-Za-z]{2,4})?$'){$s.Language}else{$null}); TrayIcon=(Flag $s.TrayIcon); CloseAction=(Flag $s.CloseAction); SwapTrayClicks=(Flag $s.SwapTrayClicks); LaunchAtLogin=(Flag $s.LaunchAtLogin); BetaUpdates=(Flag $s.BetaUpdates); ProcessSort=(Flag $s.ProcessSort); CacheRemoval=(Flag $s.CacheRemoval); UninstallIncludesAppData=(Flag $s.UninstallIncludesAppData); IgnoredUpdates=@($s.IgnoredUpdates | Where-Object { $_ }).Count; Note='Behaviour switches and a count only; no shortcuts, app names, license or logs'} # Schema 21 (Mac bf659af81): the updates hidden with Ignore, so a missing row is not read as a missed update. # The id leaves only when public (winget shape or a Store product id); every other id is a report-local alias, # and the display name in a row-level key never leaves. $ignored=0 foreach($entry in @($s.IgnoredUpdates | Where-Object { $_ -is [string] } | Select-Object -First 64)) { Ignored-UpdateFacts $entry (++$ignored) } } } Apps = { Initialize-MetadataWalker $script:pathIds=@{}; $rows=New-Object System.Collections.Generic.List[object]; $roots=New-Object System.Collections.Generic.List[string] foreach($hive in @([Microsoft.Win32.RegistryHive]::LocalMachine,[Microsoft.Win32.RegistryHive]::CurrentUser)) { foreach($view in @([Microsoft.Win32.RegistryView]::Registry64,[Microsoft.Win32.RegistryView]::Registry32)) { $base=$null;$un=$null try { $base=[Microsoft.Win32.RegistryKey]::OpenBaseKey($hive,$view); $un=$base.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall') if(-not $un){continue} foreach($key in $un.GetSubKeyNames()) { $k=$un.OpenSubKey($key); if(-not $k){continue} try { $label=App-Label $k.GetValue('DisplayName'); if(-not $label){continue} $loc=[string]$k.GetValue('InstallLocation'); $command=Executable-Only $k.GetValue('UninstallString'); $icon=Executable-Only $k.GetValue('DisplayIcon') $id=if($key-match '^Steam App (\d+)$'){$Matches[1]}else{$null} $estimate=$k.GetValue('EstimatedSize'); $size=if(($estimate-is [int] -or $estimate-is [long]) -and $estimate-ge 0){[long]$estimate*1024}else{$null} $row=[pscustomobject]@{Kind='Registration'; App=$label; Hive=[string]$hive; View=[string]$view; AppId=$id; Version=(Safe-Version $k.GetValue('DisplayVersion')); EstimatedBytes=$size; InstallPathId=(Path-Id $loc); UninstallerPathId=(Path-Id $command); UninstallerFolderId=$(if($command){Path-Id ([IO.Path]::GetDirectoryName($command))}else{$null}); UninstallerIsSteam=($command -match '\\steam\.exe$'); IconPathId=(Path-Id $icon); InstallLocationPresent=(-not [string]::IsNullOrWhiteSpace($loc))} $shape=Location-Shape $loc ([string]$k.GetValue('DisplayName')) ([string]$k.GetValue('Publisher')); $row|Add-Member InstallLocationShape $shape.Shape; $row|Add-Member OwnChildPresent $shape.OwnChildPresent; $row|Add-Member PublisherFolderChildren $shape.FolderChildren $row; $rows.Add([pscustomobject]@{App=$label;AppId=$id;Location=$loc}) [pscustomobject]@{Kind='IconRegistration';App=$label;Hive=[string]$hive;View=[string]$view;Icon=(Icon-Facts $k.GetValue('DisplayIcon'));Note='Registration only; not proof of Mole row matching or icon decoding'} if($label-eq 'Steam' -and $loc){$roots.Add($loc)} if($command-match '\\steam\.exe$'){$roots.Add([IO.Path]::GetDirectoryName($command))} } finally {$k.Dispose()} } } catch {[pscustomobject]@{Kind='RegistrationRead';Hive=[string]$hive;View=[string]$view;Status=(Error-Status $_)}} finally {if($un){$un.Dispose()};if($base){$base.Dispose()}} } } try { $steam=(Get-ItemProperty 'HKCU:\Software\Valve\Steam' -Name SteamPath).SteamPath; if($steam){$roots.Add($steam.Replace('/','\'))} } catch {} $libraries=New-Object System.Collections.Generic.List[string] foreach($root in @(Unique-LocalPaths $roots)) { $libraries.Add($root) try { $vdf=Read-SmallText (Join-Path $root 'steamapps\libraryfolders.vdf') -LocalOnly; foreach($m in [regex]::Matches([string]$vdf,'"path"\s*"([^"\r\n]+)"')){$libraries.Add($m.Groups[1].Value.Replace('\\','\'))} } catch {[pscustomobject]@{Kind='SteamLibraries';RootId=(Path-Id $root);Status=(Error-Status $_)}} } $matched=0 $uniqueLibraries=@(Unique-LocalPaths $libraries) foreach($library in @($uniqueLibraries|Select-Object -First 16)) { try { $steamApps=Local-MetadataPath (Join-Path $library 'steamapps') if(-not $steamApps){throw 'Metadata refused'} $common=Join-Path $steamApps 'common' $manifests=@(Get-ChildItem -LiteralPath $steamApps -Filter 'appmanifest_*.acf' -File | Select-Object -First 1024) foreach($file in $manifests) { $acf=Read-SmallText $file.FullName -LocalOnly; $label=App-Label (KV $acf 'name'); if($label-notin @('WARDOGS','ACE COMBAT 8','The Witcher 3')){continue} $appid=KV $acf 'appid'; if($appid-notmatch '^\d+$'){continue}; $leaf=KV $acf 'installdir' if(-not $leaf -or $leaf.IndexOfAny([IO.Path]::GetInvalidFileNameChars())-ge 0 -or $leaf-in @('.','..')){continue} $game=Local-MetadataPath (Join-Path $common $leaf);if(-not $game){continue}; $raw=KV $acf 'SizeOnDisk';$bytes=if($raw-match '^\d{1,18}$'){[long]$raw}else{$null};$matched++ [pscustomobject]@{Kind='SteamManifest';App=$label;AppId=$appid;LibraryId=(Path-Id $library);CommonId=(Path-Id $common);GameId=(Path-Id $game);ManifestBytes=$bytes; GameDirectoryExists=(Test-Path -LiteralPath $game -PathType Container); DirectoryMeasurement=[MoleFeedbackNative]::Scan($game,2000,50000)} foreach($row in @($rows|Where-Object App -eq $label)) { $loc=$row.Location.TrimEnd('\'); [pscustomobject]@{Kind='Ownership';App=$label; AppIdMatches=($row.AppId-eq $appid);RegisteredLocationIsGame=($loc-eq $game);RegisteredLocationIsLibrary=($loc-eq $library.TrimEnd('\'));RegisteredLocationIsCommon=($loc-eq $common)} } } }catch{[pscustomobject]@{Kind='SteamManifests';LibraryId=(Path-Id $library);Status=(Error-Status $_)}} } # Rows with neither an install folder nor an icon cannot be shown in Explorer; only their count leaves. $unlocated=0;$unlocatedMsi=0 foreach($root in @('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*','HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*','HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*')){ foreach($e in @(Get-ItemProperty $root -ErrorAction SilentlyContinue)){ if(-not $e.DisplayName -or $e.SystemComponent -eq 1 -or $e.InstallLocation -or $e.DisplayIcon){continue} $unlocated++; if($e.WindowsInstaller -eq 1){$unlocatedMsi++} } } [pscustomobject]@{Kind='UnlocatedRegistrations';Count=$unlocated;WindowsInstaller=$unlocatedMsi} foreach($package in @(Get-AppxPackage -ErrorAction SilentlyContinue | Where-Object {-not $_.IsFramework -and $_.Name -match 'ChatGPT|OpenAI'})){ $readable=$false; try{$null=Get-ChildItem -LiteralPath $package.InstallLocation -ErrorAction Stop | Select-Object -First 1; $readable=$true}catch{} [pscustomobject]@{Kind='Packaged';App='ChatGPT';SignatureKind=[string]$package.SignatureKind;InstallPathId=(Path-Id $package.InstallLocation);InstallFolderReadable=$readable} } [pscustomobject]@{Kind='SteamSummary';MatchingManifests=$matched;LibraryRoots=$uniqueLibraries.Count;Note='Path IDs are local to this section. Metadata is not Mole runtime size or allocated disk usage.'} } Status = { Initialize-MetadataWalker # Same raw process fields as the product, paired over one measured window. $cores=[int](Get-CimInstance Win32_ComputerSystem -OperationTimeoutSec 3).NumberOfLogicalProcessors $before=@{};$firstUtc=[DateTime]::UtcNow;$clock=[Diagnostics.Stopwatch]::StartNew() $cpuBefore=$null;try{$cpuBefore=[MoleFeedbackNative]::SystemTimes()}catch{} # Mole's own PDH counters over the same window, by fixed id: a CPU tile stuck at 0% (Mole-App#3). $pdhIds=@('cpu-utility-total','cpu-time-total','cpu-utility-cores','cpu-performance','cpu-frequency','cpu-limit','processor-time-total','disk-read-total','memory-modified','gpu-engine','thermal-zone') $pdhPaths=@('\Processor Information(_Total)\% Processor Utility','\Processor Information(_Total)\% Processor Time','\Processor Information(*)\% Processor Utility','\Processor Information(_Total)\% Processor Performance','\Processor Information(_Total)\Processor Frequency','\Processor Information(_Total)\% Performance Limit','\Processor(_Total)\% Processor Time','\PhysicalDisk(_Total)\Disk Read Bytes/sec','\Memory\Modified Page List Bytes','\GPU Engine(*)\Utilization Percentage','\Thermal Zone Information(*)\Temperature') $pdh=$null;try{$pdh=[MoleFeedbackNative]::PdhStart([string[]]$pdhIds,[string[]]$pdhPaths)}catch{} foreach($p in [MoleFeedbackNative]::Processes()){$before[$p.Pid]=$p} $snapshots=New-Object System.Collections.Generic.List[object] foreach($p in @(Get-Process -Name Mole -ErrorAction SilentlyContinue|Select-Object -First 2)){foreach($row in @(Read-MoleStatus $p.Id)){$snapshots.Add($row)}} Start-Sleep -Milliseconds 2000 $second=@([MoleFeedbackNative]::Processes());$seconds=$clock.Elapsed.TotalSeconds;$lastUtc=[DateTime]::UtcNow # System CPU from GetSystemTimes over the same window, so it exists whether or not Mole is sampling. try { if(-not $cpuBefore){throw 'System times unavailable'} $cpuAfter=[MoleFeedbackNative]::SystemTimes() $idle=$cpuAfter.Idle-$cpuBefore.Idle;$total=($cpuAfter.Kernel-$cpuBefore.Kernel)+($cpuAfter.User-$cpuBefore.User) [pscustomobject]@{Kind='SystemCpu';Source='GetSystemTimes';Utc=$lastUtc.ToString('o');WindowMs=[Math]::Round($seconds*1000);BusyPercent=$(if($total-gt 0){[Math]::Round([Math]::Min(100,[Math]::Max(0,(1-$idle/$total)*100)),1)}else{$null})} }catch{[pscustomobject]@{Kind='SystemCpu';Source='GetSystemTimes';Status=(Error-Status $_)}} try { if(-not $pdh){throw 'PDH unavailable'} $pdh=[MoleFeedbackNative]::PdhFinish($pdh) [pscustomobject]@{Kind='PdhQuery';OpenStatus=(Pdh-Code $pdh.OpenStatus);FirstCollect=(Pdh-Code $pdh.FirstCollect);SecondCollect=(Pdh-Code $pdh.SecondCollect)} foreach($r in $pdh.Rows){Pdh-CounterRow $r ($pdh.OpenStatus-eq 0)} # Schema 17: each ACPI thermal zone's reading at the end of the window (U58, CPU temperature). Rows only from # a successful array read; whether no row means no zone is Thermal-Summary's call, from the counter's statuses. Thermal-ZoneFacts (@($pdh.Rows|Where-Object {$_.Id-eq 'thermal-zone' -and $_.AddStatus-eq 0 -and $_.ArrayStatus-eq 0})|Select-Object -First 1) $gpuPdh=@($pdh.Rows|Where-Object {$_.Id-eq 'gpu-engine' -and $_.AddStatus-eq 0 -and $_.ArrayStatus-eq 0 -and $null-ne $_.Names})|Select-Object -First 1 }catch{[pscustomobject]@{Kind='PdhQuery';Status=(Error-Status $_)}} try { $perf=[ordered]@{Kind='PerfCounterSettings'} foreach($svc in @('PerfOS','PerfProc','PerfDisk','PerfNet')){ $value=$null;$key="HKLM:\SYSTEM\CurrentControlSet\Services\$svc\Performance" if(Test-Path -LiteralPath $key){$item=Get-ItemProperty -LiteralPath $key -Name 'Disable Performance Counters' -ErrorAction SilentlyContinue;if($item){$value=[int]$item.'Disable Performance Counters'}} $perf[$svc+'Disabled']=$value } $lib=Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib' -ErrorAction SilentlyContinue $perf.LastCounter=$(if($lib){[int]$lib.'Last Counter'}else{$null}) $perf.LastHelp=$(if($lib){[int]$lib.'Last Help'}else{$null}) $strings=$null;try{$strings=@((Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009' -Name Counter -ErrorAction Stop).Counter).Count}catch{} $perf.EnglishCounterStrings=$strings [pscustomobject]$perf }catch{[pscustomobject]@{Kind='PerfCounterSettings';Status=(Error-Status $_)}} try { $m=[MoleFeedbackNative]::Memory() [pscustomobject]@{Kind='SystemMemory';Source='GlobalMemoryStatusEx';LoadPercent=[int]$m.Load;TotalBytes=[long]$m.TotalPhys;AvailableBytes=[long]$m.AvailPhys;CommitTotalBytes=[long]($m.TotalPageFile-$m.AvailPageFile);CommitLimitBytes=[long]$m.TotalPageFile} }catch{[pscustomobject]@{Kind='SystemMemory';Source='GlobalMemoryStatusEx';Status=(Error-Status $_)}} [pscustomobject]@{Kind='ProcessWindow';StartUtc=$firstUtc.ToString('o');EndUtc=$lastUtc.ToString('o');WindowMs=[Math]::Round($seconds*1000);LogicalProcessors=$cores;TotalProcesses=$second.Count;Limit=256} foreach($p in @($second|Where-Object {(Known-ProcessImage $_.Image)-ne 'other'}|Select-Object -First 256)) { $old=$before[$p.Pid];$delta=$null if($old -and $old.Created-eq $p.Created -and $p.Cpu-ge $old.Cpu){$delta=$p.Cpu-$old.Cpu} [pscustomobject]@{Kind='ProcessSample';Image=(Known-ProcessImage $p.Image);ProcessId=$p.Pid;ParentProcessId=$p.Parent;CreatedUtc=([DateTime]::FromFileTimeUtc($p.Created).ToString('o'));CpuTime100ns=$p.Cpu;CpuDelta100ns=$delta;CpuPercent=$(if($null-ne $delta -and $cores-gt 0){$delta/($seconds*10000000)*100/$cores}else{$null});PrivateWorkingSetBytes=$p.PrivateWorkingSet} } foreach($p in @(Get-Process -Name Mole -ErrorAction SilentlyContinue|Select-Object -First 2)){foreach($row in @(Read-MoleStatus $p.Id)){$snapshots.Add($row)}} Unique-Events $snapshots # Schema 13: GPU engines come from the PDH query above, over the same two seconds; the WMI class timed out on a # PC at 80% memory load (0x40004, 2026-10-16) and stays only as the fallback when PDH gave no array. if($gpuPdh) { $named=@(for($k=0;$k-lt $gpuPdh.Names.Count;$k++){if(-not [double]::IsNaN($gpuPdh.Values[$k])){[pscustomobject]@{Name=[string]$gpuPdh.Names[$k];UtilizationPercentage=$gpuPdh.Values[$k]}}}) $groups=@($named|Where-Object {$_.Name-match 'luid_[0-9a-fx]+_[0-9a-fx]+_phys_\d+_eng_\d+'}|Group-Object {[regex]::Match($_.Name,'luid_[0-9a-fx]+_[0-9a-fx]+_phys_\d+_eng_\d+','IgnoreCase').Value}) $index=0;foreach($g in $groups|Select-Object -First 64){ $parts=[regex]::Match($g.Name,'luid_0x([0-9a-f]+)_0x([0-9a-f]+)_phys_(\d+)_eng_(\d+)','IgnoreCase') if(-not $parts.Success){continue} $luid=([long][Convert]::ToUInt32($parts.Groups[1].Value,16) -shl 32) -bor [long][Convert]::ToUInt32($parts.Groups[2].Value,16) [pscustomobject]@{Kind='GpuEngine';Index=$index++;AdapterLuid=$luid;PhysicalAdapter=[int]$parts.Groups[3].Value;Engine=[int]$parts.Groups[4].Value;UsagePercent=[Math]::Round(($g.Group|Measure-Object UtilizationPercentage -Sum).Sum,1)} } [pscustomobject]@{Kind='GpuCounters';Source='pdh';Status=$(if($groups.Count){'complete'}else{'no-counters'});Engines=$groups.Count;Utc=[DateTime]::UtcNow.ToString('o')} } else { try { $engines=@(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUEngine -OperationTimeoutSec 3) $groups=@($engines|Where-Object {$_.Name-match 'luid_[0-9a-fx]+_[0-9a-fx]+_phys_\d+_eng_\d+'}|Group-Object {[regex]::Match($_.Name,'luid_[0-9a-fx]+_[0-9a-fx]+_phys_\d+_eng_\d+','IgnoreCase').Value}) $index=0;foreach($g in $groups|Select-Object -First 64){ $parts=[regex]::Match($g.Name,'luid_0x([0-9a-f]+)_0x([0-9a-f]+)_phys_(\d+)_eng_(\d+)','IgnoreCase') if(-not $parts.Success){continue} $luid=([long][Convert]::ToUInt32($parts.Groups[1].Value,16) -shl 32) -bor [long][Convert]::ToUInt32($parts.Groups[2].Value,16) [pscustomobject]@{Kind='GpuEngine';Index=$index++;AdapterLuid=$luid;PhysicalAdapter=[int]$parts.Groups[3].Value;Engine=[int]$parts.Groups[4].Value;UsagePercent=($g.Group|Measure-Object UtilizationPercentage -Sum).Sum} } [pscustomobject]@{Kind='GpuCounters';Source='wmi';Status=$(if($groups.Count){'complete'}else{'no-counters'});Engines=$groups.Count;Utc=[DateTime]::UtcNow.ToString('o')} }catch{[pscustomobject]@{Kind='GpuCounters';Source='wmi';Status=(Error-Status $_);Error=(Error-Class $_)}} } $receipt=Join-Path $env:LOCALAPPDATA 'Mole\startup-diagnostic.json' Startup-Facts (Read-SmallText $receipt -LocalOnly) # Read only matching service configuration; no start, stop or write. try { foreach($s in @(Get-CimInstance Win32_Service -Filter "Name LIKE '%ChatGPT%' OR DisplayName LIKE '%ChatGPT%'" -OperationTimeoutSec 3|Select-Object -First 8)) { $sddl=$null;try{$sddl=(@(& sc.exe sdshow $s.Name 2>$null)|Where-Object {$_ -match '^D:'}|Select-Object -First 1)}catch{} [pscustomobject]@{Kind='StartupService';App='ChatGPT';StartMode=$(if($s.StartMode -in @('Auto','Manual','Disabled')){$s.StartMode}else{'unknown'});State=$(if($s.State -in @('Running','Stopped','Start Pending','Stop Pending')){$s.State}else{'unknown'});ExitCode=[int]$s.ExitCode;Packaged=([string]$s.PathName -match '\\WindowsApps\\');AdminCanChange=(Service-AdminCanChange $sddl)} }}catch{[pscustomobject]@{Kind='StartupService';Status=(Error-Status $_)}} } Layout = { Add-Type -AssemblyName UIAutomationClient,UIAutomationTypes $timer=[Diagnostics.Stopwatch]::StartNew();$visited=0;$scrolls=0 foreach($process in @(Get-Process -Name Mole -ErrorAction SilentlyContinue)) { if($process.MainWindowHandle-eq 0){continue} $root=[Windows.Automation.AutomationElement]::FromHandle($process.MainWindowHandle) $queue=New-Object System.Collections.Queue;$queue.Enqueue($root) $walker=[Windows.Automation.TreeWalker]::ControlViewWalker while($queue.Count-gt 0 -and $visited-lt 500 -and $timer.ElapsedMilliseconds-lt 5000) { $node=$queue.Dequeue();$visited++;$pattern=$null try { # Fixed automation ids name the open tab and Apps segment without reading UI text. $automationId=[string]$node.Current.AutomationId;$selection=$null if($automationId -match '^(tab|software\.segment)\.[a-z]{1,16}$' -and $node.TryGetCurrentPattern([Windows.Automation.SelectionItemPattern]::Pattern,[ref]$selection)) { [pscustomobject]@{Kind='Selection';Id=$automationId;Selected=$selection.Current.IsSelected} } if($node.TryGetCurrentPattern([Windows.Automation.ScrollPattern]::Pattern,[ref]$pattern)) { $state=$pattern.Current;$rect=$node.Current.BoundingRectangle;$scrolls++ [pscustomobject]@{Kind='Scroll';Index=$scrolls;VerticalScrollable=$state.VerticallyScrollable;VerticalPercent=$state.VerticalScrollPercent;VerticalViewPercent=$state.VerticalViewSize;WidthPx=$rect.Width;HeightPx=$rect.Height;Offscreen=$node.Current.IsOffscreen} } $child=$walker.GetFirstChild($node) while($child -and ($visited+$queue.Count)-lt 500 -and $timer.ElapsedMilliseconds-lt 5000){$queue.Enqueue($child);$child=$walker.GetNextSibling($child)} }catch{[pscustomobject]@{Kind='LayoutRead';Status=(Error-Status $_)}} } } [pscustomobject]@{Kind='LayoutCoverage';Visited=$visited;Scrolls=$scrolls;Partial=($visited-ge 500 -or $timer.ElapsedMilliseconds-ge 5000);Note='Current Mole window only. No UI text, file names, control invocation or scrolling.'} } Updates = { $pkg=Get-AppxPackage -Name Microsoft.DesktopAppInstaller | Select-Object -First 1 [pscustomobject]@{Kind='WingetProvider'; AppInstallerVersion=$(if($pkg){[string]$pkg.Version}else{$null}); Present=[bool]$pkg; Note='No winget command, update or network query is executed'} # The Git/FFmpeg/Scoop (U32) and Edge updater (feedback-5) probes were retired once those cases closed. $c=Get-Command winget -ErrorAction SilentlyContinue | Select-Object -First 1 [pscustomobject]@{Kind='Command';Name='winget';Found=[bool]$c;FileVersion=$(if($c -and $c.CommandType-eq 'Application'){Safe-Version (Get-Item -LiteralPath $c.Source).VersionInfo.ProductVersion}else{$null})} foreach($name in @('winget','msiexec')) { [pscustomobject]@{Kind='ProcessCount';Name=$name;Count=@(Get-Process -Name $name -ErrorAction SilentlyContinue).Count} } $mole=@(Get-Process Mole -ErrorAction SilentlyContinue | ForEach-Object {$_.Id}) $installers=@('MicrosoftEdgeUpdate.exe','setup.exe','elevation_service.exe','AppInstallerCLI.exe','WindowsPackageManagerServer.exe','winget.exe','msiexec.exe') $running=@(Get-CimInstance Win32_Process -OperationTimeoutSec 5 | Where-Object {$_.Name -in $installers}) foreach($g in @($running | Group-Object Name)){[pscustomobject]@{Kind='InstallerProcess';Name=$g.Name;Count=$g.Count;ChildOfMole=@($g.Group | Where-Object {$_.ParentProcessId -in $mole}).Count}} [pscustomobject]@{Kind='Limits';Note='Historical clicks, active Mole OperationGate and queue contents are not available to an external script'} } UpdateLogs = { $moleLog=Local-MetadataPath (Join-Path $env:LOCALAPPDATA 'Mole\update-diagnostics.jsonl') if($moleLog -and (Test-Path -LiteralPath $moleLog -PathType Leaf)) { try { $parent=Get-Item -LiteralPath ([IO.Path]::GetDirectoryName($moleLog)) -Force $item=Get-Item -LiteralPath $moleLog -Force if(($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)){throw 'Refused redirected diagnostic'} if($item.Length -le 139264){ $records=@(Mole-UpdateFacts ([IO.File]::ReadAllText($moleLog))) $records Update-AttemptFacts @($records|Where-Object Kind -eq 'MoleUpdate') [pscustomobject]@{Kind='MoleUpdateLog';Status='complete'} } else {[pscustomobject]@{Kind='MoleUpdateLog';Status='limit'}} }catch {[pscustomobject]@{Kind='MoleUpdateLog';Status='unavailable'}} } else {[pscustomobject]@{Kind='MoleUpdateLog';Status=$(if($moleLog){'none-recorded'}else{'refused-metadata-path'})}} # Mole's own updater: the newest few Velopack logs, last 64 KiB each. Other apps' Velopack logs are only counted. try { $found=@(foreach($pattern in @((Join-Path $env:LOCALAPPDATA 'velopack\*.log'),(Join-Path ([IO.Path]::GetTempPath()) 'velopack*.log'))){Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue}) $own=@($found|Where-Object {$_.Name-in @('velopack.log','velopack_Tw93.Mole.log')}|Sort-Object LastWriteTimeUtc -Descending|Select-Object -First 3) foreach($file in $own){ try { $tail=Read-TailText $file.FullName 65536 [pscustomobject]@{Kind='VelopackLog';Location=$(if($file.DirectoryName-like '*\velopack'){'local-velopack'}else{'temp'});File=$(if($file.Name-eq 'velopack.log'){'shared'}else{'mole'});ModifiedUtc=$file.LastWriteTimeUtc.ToString('o');Bytes=$file.Length;Partial=$tail.Partial;Facts=(Velopack-Facts $tail.Text)} }catch{[pscustomobject]@{Kind='VelopackLog';Status=(Error-Status $_)}} } [pscustomobject]@{Kind='VelopackLogs';Status=$(if($own.Count){'complete'}else{'none-recorded'});Sampled=$own.Count;OtherAppLogs=@($found|Where-Object {$_.Name-notin @('velopack.log','velopack_Tw93.Mole.log')}).Count} }catch{[pscustomobject]@{Kind='VelopackLogs';Status=(Error-Status $_)}} $root=Local-MetadataPath (Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\LocalState\DiagOutputDir') if(-not $root){[pscustomobject]@{Kind='Logs';Status='refused-metadata-path'};return} if(-not (Test-Path -LiteralPath $root -PathType Container)){[pscustomobject]@{Kind='Logs';Status='missing-default-location'};return} if((Get-Item -LiteralPath $root -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){[pscustomobject]@{Kind='Logs';Status='refused-reparse'};return} $all=@(Get-ChildItem -LiteralPath $root -Filter 'WinGet-*.log' -File | Where-Object LastWriteTimeUtc -ge ([DateTime]::UtcNow.AddDays(-7)) | Sort-Object LastWriteTimeUtc -Descending) foreach($file in @($all | Select-Object -First 20)) { try {[pscustomobject]@{Kind='WingetLog';Picked='newest';ModifiedUtc=$file.LastWriteTimeUtc.ToString('o');Bytes=$file.Length;Partial=($file.Length-gt 131072);Facts=(Winget-LogFacts (Read-LogSample $file.FullName))}} catch {[pscustomobject]@{Kind='WingetLog';Picked='newest';Status=(Error-Status $_)}} } # Schema 27: every update check Mole runs writes a list log, so a failed install a few checks back left the newest 20 # (282 of 610 sampled logs were lists). Up to 12 older logs of the week whose installer failed are kept as well. $examined=0;$added=0 foreach($file in @($all | Select-Object -Skip 20 -First 200)) { if($added-ge 12){break} $examined++ try { $text=Read-LogSample $file.FullName if($text -notmatch '(?im)\[CLI\s*\]\s+\S+ installer failed: \d'){continue} $added++ [pscustomobject]@{Kind='WingetLog';Picked='failed-install';ModifiedUtc=$file.LastWriteTimeUtc.ToString('o');Bytes=$file.Length;Partial=($file.Length-gt 131072);Facts=(Winget-LogFacts $text)} } catch {[pscustomobject]@{Kind='WingetLog';Picked='failed-install';Status=(Error-Status $_)}} } [pscustomobject]@{Kind='Limits';FilesSampled=[Math]::Min(20,$all.Count)+$added;LogsInWeek=$all.Count;OlderExamined=$examined;FailedInstallsAdded=$added;Note='Latest 20 logs in 7 days plus up to 12 older ones of the week whose installer failed (200 examined at most), first/last 64 KiB each. Codes and fixed package mentions only. Logs may be from outside Mole; absence of codes is not success.'} } AppEvents = { # Crash and Restart Manager events stay filtered to this list; its per-case live process counts were retired. $images=@('msedge','clash-verge','Clash for Windows','FlClash','qq','wechat','weixin','WeixinExt','WeChatAppEx','steam','steamwebhelper','git','fdm','zed','Mole') try { $events=@(Get-WinEvent -LogName Application -FilterXPath "*[System[Provider[@Name='Application Error'] and (EventID=1000) and TimeCreated[timediff(@SystemTime) <= 604800000]]]" -MaxEvents 100) $matchingEvents=0 foreach($event in $events) { $xml=[xml]$event.ToXml();$fields=@{} foreach($field in $xml.Event.EventData.Data){if($field.Name){$fields[[string]$field.Name]=[string]$field.'#text'}} $name=[IO.Path]::GetFileNameWithoutExtension([string]$fields['AppName']) if($name -notin $images){continue};$matchingEvents++ $code=[string]$fields['ExceptionCode'] [pscustomobject]@{Kind='AppCrash';Version=(Safe-Version ([string]$fields['AppVersion']));Module=(Crash-Module ([string]$fields['ModuleName']));Image=($images|Where-Object {$_-eq $name}|Select-Object -First 1);Utc=$event.TimeCreated.ToUniversalTime().ToString('o');ExceptionCode=$(if($code-match '^(?:0x)?[0-9A-Fa-f]{8}$'){$code}else{$null})} } [pscustomobject]@{Kind='CrashQuery';Status='complete';EventsExamined=$events.Count;MatchingEvents=$matchingEvents;LimitReached=($events.Count-eq 100)} }catch{$failure=Event-QueryFailure $_;[pscustomobject]@{Kind='CrashQuery';Status=$failure.Status;Error=$failure.Error}} try { # Schema 15: the runtime's own account of a Mole crash, 14 days (Runtime-CrashFacts). $events=@(Get-WinEvent -LogName Application -FilterXPath "*[System[Provider[@Name='.NET Runtime'] and (EventID=1026) and TimeCreated[timediff(@SystemTime) <= 1209600000]]]" -MaxEvents 100) $matchingEvents=0 foreach($event in $events) { $xml=[xml]$event.ToXml() $text=@($xml.Event.EventData.Data|ForEach-Object {if($_ -is [string]){$_}else{[string]$_.'#text'}}) -join "`n" $facts=Runtime-CrashFacts $text if(-not $facts){continue};$matchingEvents++ $facts|Add-Member -NotePropertyName Utc -NotePropertyValue $event.TimeCreated.ToUniversalTime().ToString('o') $facts } [pscustomobject]@{Kind='RuntimeCrashQuery';Status='complete';EventsExamined=$events.Count;MatchingEvents=$matchingEvents;LimitReached=($events.Count-eq 100)} }catch{$failure=Event-QueryFailure $_;[pscustomobject]@{Kind='RuntimeCrashQuery';Status=$failure.Status;Error=$failure.Error}} try { # These provider templates carry FullPath and numeric Status. Never return # DisplayName, affected files, PID, session identifiers or formatted messages. $events=@(Get-WinEvent -LogName Application -FilterXPath "*[System[Provider[@Name='Microsoft-Windows-RestartManager'] and (EventID=10002 or EventID=10010) and TimeCreated[timediff(@SystemTime) <= 604800000]]]" -MaxEvents 100) $matchingEvents=0 foreach($event in $events) { $xml=[xml]$event.ToXml();$fields=@{} foreach($field in $xml.Event.EventData.Data){if($field.Name){$fields[[string]$field.Name]=[string]$field.'#text'}} $name=[IO.Path]::GetFileNameWithoutExtension([string]$fields['FullPath']) if($name -notin $images){continue};$matchingEvents++;$status=0L [pscustomobject]@{Kind='RestartManagerApp';Image=($images|Where-Object {$_-eq $name}|Select-Object -First 1);Id=$event.Id;Utc=$event.TimeCreated.ToUniversalTime().ToString('o');StatusCode=$(if([long]::TryParse([string]$fields['Status'],[ref]$status)){$status}else{$null})} } [pscustomobject]@{Kind='RestartManagerQuery';Status='complete';EventsExamined=$events.Count;MatchingEvents=$matchingEvents;LimitReached=($events.Count-eq 100)} }catch{$failure=Event-QueryFailure $_;[pscustomobject]@{Kind='RestartManagerQuery';Status=$failure.Status;Error=$failure.Error}} [pscustomobject]@{Kind='Limits';Note='Current counts and recent crash events cannot identify who closed an app. No process command lines, browser data or raw event messages are collected.'} } Freeze = { # Whole-PC freezes (only the pointer moves, a power-button restart): the events Windows wrote around # them, by fixed category, for 14 days. Dumps by Windows-named folder and the system disk's bus. $since='TimeCreated[timediff(@SystemTime) <= 1209600000]' $queries=[ordered]@{ system="*[System[((Provider[@Name='Microsoft-Windows-Kernel-Power'] and EventID=41) or (Provider[@Name='EventLog'] and EventID=6008) or (Provider[@Name='Display'] and EventID=4101) or (Provider[@Name='Microsoft-Windows-Resource-Exhaustion-Detector'] and EventID=2004) or (Provider[@Name='Microsoft-Windows-WHEA-Logger'] and (Level=1 or Level=2 or Level=3))) and $since]]" drivers="*[System[Provider[@Name='nvlddmkm' or @Name='igfx' or @Name='igfxn' or @Name='igfxnd' or @Name='igfxdcm' or @Name='amdkmdag' or @Name='amdkmdap' or @Name='amdwddmg' or @Name='iaStorAC' or @Name='iaStorAVC' or @Name='iaStorA' or @Name='iaStorV' or @Name='iaStorVD' or @Name='storahci' or @Name='stornvme' or @Name='disk' or @Name='Ntfs' or @Name='Microsoft-Windows-Ntfs'] and (Level=1 or Level=2 or Level=3) and $since]]" } foreach($q in $queries.Keys){ try { Get-WinEvent -LogName System -FilterXPath $queries[$q] -MaxEvents 60 -ErrorAction Stop | ForEach-Object { Freeze-EventFacts $_ } } catch { $failure=Event-QueryFailure $_; [pscustomobject]@{Kind='FreezeEvents';Query=$q;Status=$failure.Status;Error=$failure.Error} } } try { Get-WinEvent -LogName Application -FilterXPath "*[System[((Provider[@Name='Windows Error Reporting'] and EventID=1001) or (Provider[@Name='Application Hang'] and EventID=1002)) and $since]]" -MaxEvents 200 -ErrorAction Stop | ForEach-Object { Application-FreezeFacts $_ } | Select-Object -First 40 } catch { $failure=Event-QueryFailure $_; [pscustomobject]@{Kind='FreezeEvents';Query='application';Status=$failure.Status;Error=$failure.Error} } # Graphics settings behind TDRs and flicker: numbers and one allowlisted channel word only. $g=[ordered]@{Kind='GraphicsConfig';TdrLevel=$null;TdrDelay=$null;HwSchMode=$null;MpoDisabled=$null;TransparencyEffects=$null;InsiderBranch=$null} try{$k=Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers' -ErrorAction Stop; foreach($n in 'TdrLevel','TdrDelay','HwSchMode'){ if($null-ne $k.$n -and [string]$k.$n -match '^\d{1,6}$'){$g[$n]=[int]$k.$n} }}catch{} try{$d=Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\Dwm' -ErrorAction Stop; $g.MpoDisabled=($d.OverlayTestMode-eq 5)}catch{} try{$t=Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -ErrorAction Stop; if($null-ne $t.EnableTransparency){$g.TransparencyEffects=($t.EnableTransparency-eq 1)}}catch{} try{$b=[string](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\WindowsSelfHost\Applicability' -ErrorAction Stop).BranchName; if($b -match '^[A-Za-z0-9_]{1,40}$'){$g.InsiderBranch=$b}}catch{} [pscustomobject]$g $cutoff=[DateTime]::UtcNow.AddDays(-14) Dump-FolderFacts (Join-Path $env:WINDIR 'LiveKernelReports') 'LiveKernelReport' $cutoff Dump-FolderFacts (Join-Path $env:WINDIR 'Minidump') 'Minidump' $cutoff try { $letter=([string]$env:SystemDrive).Substring(0,1) $part=Get-CimInstance -Namespace root/Microsoft/Windows/Storage -ClassName MSFT_Partition -Filter "DriveLetter='$letter'" -OperationTimeoutSec 5 -ErrorAction Stop|Select-Object -First 1 $disk=Get-CimInstance -Namespace root/Microsoft/Windows/Storage -ClassName MSFT_PhysicalDisk -OperationTimeoutSec 5 -ErrorAction Stop|Where-Object {[string]$_.DeviceId-eq [string]$part.DiskNumber}|Select-Object -First 1 [pscustomobject]@{Kind='SystemDisk';BusType=$(if($disk){Bus-Word ([int]$disk.BusType)}else{$null});MediaType=$(if($disk){switch([int]$disk.MediaType){3{'hdd'}4{'ssd'}5{'scm'}default{'unspecified'}}}else{$null})} } catch {[pscustomobject]@{Kind='SystemDisk';Status=(Error-Status $_)}} } Analyze = { Initialize-MetadataWalker $volumes=@([MoleFeedbackNative]::Volumes()) $facts=@(Volume-Facts $volumes) $facts foreach($v in @($volumes|Where-Object {$_.DriveType-in @(2,3) -and $_.Status-eq 'ok'})){ $probes=@([MoleFeedbackNative]::ProbeDirectory(([string]$v.Letter+':\'),20000)) Probe-Facts ('root:'+$v.Letter) $probes # Analyze offers fixed drives only; a FAT stick refusing the newer class is not an Analyze problem. if($v.DriveType-eq 3){Root-Verdict ([string]$v.Letter) $v $probes} } # Folders every system drive has, by role; their paths and child names are never exported. $system=[string]$env:SystemDrive $roles=[ordered]@{Windows=$env:SystemRoot;Users=(Join-Path $system '\Users');ProgramFiles=$env:ProgramFiles;ProgramData=$env:ProgramData;Profile=$env:USERPROFILE;LocalAppData=$env:LOCALAPPDATA} foreach($role in $roles.Keys){ if($roles[$role]){ Probe-Facts ('system:'+$role) @([MoleFeedbackNative]::ProbeDirectory($roles[$role],20000)) } } $store=Join-Path $env:LOCALAPPDATA 'Mole\analyze' if([IO.Directory]::Exists($store)){ $serials=@{};foreach($r in $volumes){if($null-ne $r.Serial){$serials[('{0:X8}' -f [uint32]$r.Serial)]=($facts|Where-Object {$_.Letter-eq $r.Letter}|Select-Object -First 1).SerialAlias}} $files=@(Get-ChildItem -LiteralPath $store -Filter '*.snapshot' -File -ErrorAction SilentlyContinue|Select-Object -First 16) if(-not $files.Count){[pscustomobject]@{Kind='AnalyzeSnapshot';Status='none'}} foreach($f in $files){$id=[IO.Path]::GetFileNameWithoutExtension($f.Name);Snapshot-Facts ([MoleFeedbackNative]::Snapshot($f.FullName)) $(if($serials.ContainsKey($id)){$serials[$id]}else{'other'})} } else {[pscustomobject]@{Kind='AnalyzeSnapshot';Status='none'}} Filter-DriverFacts } Storage = { Initialize-MetadataWalker Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' -OperationTimeoutSec 8 | Select-Object @{n='Kind';e={'Disk'}},DeviceID,FileSystem,Size,FreeSpace $paths=[ordered]@{LocalTemp=(Join-Path $env:LOCALAPPDATA 'Temp');Npm=(Join-Path $env:LOCALAPPDATA 'npm-cache');Pip=(Join-Path $env:LOCALAPPDATA 'pip\Cache');Nuget=(Join-Path $env:USERPROFILE '.nuget\packages');Gradle=(Join-Path $env:USERPROFILE '.gradle\caches');Cargo=(Join-Path $env:USERPROFILE '.cargo\registry')} foreach($name in $paths.Keys){[pscustomobject]@{Kind='KnownDirectory';Name=$name;Measurement=[MoleFeedbackNative]::Scan($paths[$name],2000,25000)}} [pscustomobject]@{Kind='Limits';Note='Occupancy is not safe-to-delete space. No whole-profile, drive-root, registry-cleaning or project scan.'} } RecycleTarget = { $explicit=-not [string]::IsNullOrWhiteSpace($args[0]) $targets=@() # Only a folder support names (-TargetPath or -ChooseFolder) is measured; the routine run measures none. if($explicit){$targets=@($args[0])} else {[pscustomobject]@{Kind='Target';Status='not-selected'}} Initialize-MetadataWalker $index=0 foreach($target in $targets) { $measurement=[MoleFeedbackNative]::Scan($target,[int](15000/$targets.Count),[int](150000/$targets.Count)) [pscustomobject]@{Kind='Target';Index=$index++;Source=$(if($explicit){'explicit'}else{'reported-folder'});Measurement=$measurement;Note='Read-only metadata scan time is not the previous recycle operation time'} try { $path=[IO.Path]::GetFullPath($target);$drive=New-Object IO.DriveInfo ([IO.Path]::GetPathRoot($path)) [pscustomobject]@{Kind='TargetVolume';Type=[string]$drive.DriveType;FileSystem=$drive.DriveFormat} } catch {[pscustomobject]@{Kind='TargetVolume';Status=(Error-Status $_)}} } try { # Values only. Volume GUIDs and user SIDs never leave the worker. $key='HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\BitBucket\Volume' $index=0 if(Test-Path $key){Get-ChildItem $key|Select-Object -First 16|ForEach-Object{$v=Get-ItemProperty $_.PSPath;[pscustomobject]@{Kind='RecyclePolicy';Index=$index++;MaxCapacityMiB=$v.MaxCapacity;NukeOnDelete=$v.NukeOnDelete;Note='Unmapped volume policy, not proof of target recoverability'}}} } catch {[pscustomobject]@{Kind='RecyclePolicy';Status=(Error-Status $_)}} } Shaders = { # Schema 14 (U88): GPU shader caches with their write range, Steam's per-game caches, the GPU drivers and # their changes, and Windows' own cleanup, so a game recompiling its shaders can be traced to Mole's # clean, a driver change or something else that emptied the cache. Initialize-MetadataWalker $script:pathIds=@{} try{Gpu-DriverFacts}catch{[pscustomobject]@{Kind='GpuDriver';Status=(Error-Status $_);Error=(Error-Class $_)}} $oldest=$null try{ $log='Microsoft-Windows-Kernel-PnP/Configuration' # How far back the log reaches, since it is small and an older driver change may have rolled out of it. $oldest=$null;$first=Get-WinEvent -LogName $log -Oldest -MaxEvents 1 -ErrorAction Stop;$oldest=$first.TimeCreated.ToUniversalTime().ToString('o') # 180 days; XPath timediff, never a StartTime (a zh-CN Windows 10 failed every StartTime query). $events=@(Get-WinEvent -LogName $log -FilterXPath '*[System[EventID=400 and TimeCreated[timediff(@SystemTime) <= 15552000000]]]' -MaxEvents 600 -ErrorAction Stop) $changes=@(Driver-ChangeFacts @($events|ForEach-Object {$_.ToXml()})|Sort-Object Utc -Descending|Select-Object -First 40) [pscustomobject]@{Kind='GpuDriverChanges';Status='complete';Events=$changes.Count;LogOldestUtc=$oldest} $changes }catch{$f=Event-QueryFailure $_;[pscustomobject]@{Kind='GpuDriverChanges';Status=$f.Status;Error=$f.Error;LogOldestUtc=$oldest}} Storage-SenseFacts Disk-CleanupFacts Cleaner-Presence # The folder walks last: a slow disk or a large Steam library that runs the section out of time then # costs cache rows, never the driver and Windows cleanup facts above. Shader-CacheFacts Steam-ShaderFacts } AI = { # Schema 24: AI tools' data (Mole Mac's 17-ai-tools on Windows paths), within its own 20 s so worker # start-up and the slowest single call still fit the section's 30 s timeout; rows leave as they are found, so a slow PC keeps the first tools. Initialize-MetadataWalker AI-Facts $env:USERPROFILE $env:LOCALAPPDATA $env:APPDATA 20000 -UseEnvironment } Environment = { Initialize-MetadataWalker # Display and taskbar topology in physical pixels: where the tray panel can and cannot be placed. try { $monitors=@([MoleFeedbackNative]::Monitors()) foreach($m in $monitors){Monitor-Facts $m} $bar=[MoleFeedbackNative]::Taskbar() $on=$null if($bar.Found){$cx=($bar.Rect.Left+$bar.Rect.Right)/2;$cy=($bar.Rect.Top+$bar.Rect.Bottom)/2;$on=($monitors|Where-Object {$cx-ge $_.Bounds.Left -and $cx-lt $_.Bounds.Right -and $cy-ge $_.Bounds.Top -and $cy-lt $_.Bounds.Bottom}|Select-Object -First 1).Index} [pscustomobject]@{Kind='Taskbar';Found=$bar.Found;Edge=$(if($bar.Found){@('left','top','right','bottom')[[Math]::Min(3,[int]$bar.Edge)]}else{$null});Rect=$(if($bar.Found){@($bar.Rect.Left,$bar.Rect.Top,$bar.Rect.Right,$bar.Rect.Bottom)}else{$null});MonitorIndex=$on;AutoHide=(($bar.State -band 1)-ne 0);AlwaysOnTop=(($bar.State -band 2)-ne 0)} }catch{[pscustomobject]@{Kind='Displays';Status=(Error-Status $_)}} # A Remote Desktop session turns off "Animate controls and elements inside windows", and WinUI then skips # implicit show and hide animations: an overlay that never appeared is read against these two facts. try {[pscustomobject]@{Kind='Session';Remote=[MoleFeedbackNative]::RemoteSession();ClientAreaAnimation=[MoleFeedbackNative]::ClientAreaAnimation()}}catch{[pscustomobject]@{Kind='Session';Status=(Error-Status $_)}} try { $adapters=@([MoleFeedbackNative]::DisplayAdapters()) $virtual=@($adapters|ForEach-Object {Virtual-AdapterCategory $_}|Where-Object {$_}) [pscustomobject]@{Kind='DisplayAdapters';Adapters=$adapters.Count;VirtualAdapters=$virtual.Count;VirtualCategories=@($virtual|Select-Object -Unique)} }catch{[pscustomobject]@{Kind='DisplayAdapters';Status=(Error-Status $_)}} try { $images=@([MoleFeedbackNative]::Processes()|ForEach-Object {$_.Image}) $modules=@();$read=$false try {$explorer=Get-Process -Name explorer -ErrorAction Stop|Select-Object -First 1;$modules=@($explorer.Modules|ForEach-Object {$_.ModuleName});$read=$true}catch{} Shell-ModificationFacts $images $modules $read }catch{[pscustomobject]@{Kind='ShellModifications';Status=(Error-Status $_)}} # Startup entries per source, counted the way Mole and Task Manager decide enabled (StartupApproved). $approvedPath='SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\' foreach($spec in @(@('UserRun','CurrentUser','Registry64','Run'),@('MachineRun','LocalMachine','Registry64','Run'),@('MachineRun32','LocalMachine','Registry32','Run32'))) { $base=$null;$run=$null;$approved=$null;$approvedBase=$null try { $base=[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::($spec[1]),[Microsoft.Win32.RegistryView]::($spec[2])) $run=$base.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Run') $values=Registry-Values $run $names=@($values.Keys|Where-Object {$_ -and $values[$_]-is [string] -and -not [string]::IsNullOrWhiteSpace($values[$_])}) $approvedBase=[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::($spec[1]),[Microsoft.Win32.RegistryView]::Registry64) $approved=$approvedBase.OpenSubKey($approvedPath+$spec[3]) Startup-CountFacts $spec[0] $names (Registry-Values $approved) }catch{[pscustomobject]@{Kind='StartupCount';Source=$spec[0];Status=(Error-Status $_)}} finally{foreach($k in @($approved,$approvedBase,$run,$base)){if($k){$k.Dispose()}}} } foreach($spec in @(@('UserStartupFolder','Startup','CurrentUser'),@('CommonStartupFolder','CommonStartup','LocalMachine'))) { $base=$null;$approved=$null try { $folder=[Environment]::GetFolderPath($spec[1]) $names=@(if($folder -and [IO.Directory]::Exists($folder)){[IO.Directory]::GetFiles($folder)|ForEach-Object {[IO.Path]::GetFileName($_)}|Where-Object {$_-ne 'desktop.ini'}}) $base=[Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::($spec[2]),[Microsoft.Win32.RegistryView]::Registry64) $approved=$base.OpenSubKey($approvedPath+'StartupFolder') Startup-CountFacts $spec[0] $names (Registry-Values $approved) }catch{[pscustomobject]@{Kind='StartupCount';Source=$spec[0];Status=(Error-Status $_)}} finally{foreach($k in @($approved,$base)){if($k){$k.Dispose()}}} } # Antivirus by category and decoded state only; product names never leave. try { $products=@(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct -OperationTimeoutSec 5|Select-Object -First 8) if($products.Count){foreach($av in $products){Antivirus-Facts $av}} else{[pscustomobject]@{Kind='Antivirus';Status='no-instances'}} } catch{[pscustomobject]@{Kind='Antivirus';Status=(Error-Status $_)}} try { # Get-MpPreference's own class, read with a timeout. $mp=Get-CimInstance -Namespace root/Microsoft/Windows/Defender -ClassName MSFT_MpPreference -OperationTimeoutSec 5 if($null-eq $mp){[pscustomobject]@{Kind='ControlledFolderAccess';Status='no-instances';State=$null}} elseif($null-eq $mp.EnableControlledFolderAccess){[pscustomobject]@{Kind='ControlledFolderAccess';Status='unavailable';State=$null}} else { $cfa=[int]$mp.EnableControlledFolderAccess [pscustomobject]@{Kind='ControlledFolderAccess';State=$(switch($cfa){0{'off'}1{'on'}2{'audit'}default{'other'}})} } }catch{[pscustomobject]@{Kind='ControlledFolderAccess';Status=(Error-Status $_)}} } } # Schema 13: the PowerShell that ran the collector, since pwsh 7 and Windows PowerShell 5.1 read JSON times differently. $report=[ordered]@{Schema='mole-windows-feedback-29';CollectedUtc=[DateTime]::UtcNow.ToString('o');ElapsedMs=$null;Host=[ordered]@{Edition=$(if([string]$PSVersionTable.PSEdition -in @('Desktop','Core')){[string]$PSVersionTable.PSEdition}else{'Desktop'});Version=('{0}.{1}' -f $PSVersionTable.PSVersion.Major,$PSVersionTable.PSVersion.Minor)};Summary=$null;Sections=[ordered]@{}} $total=[Diagnostics.Stopwatch]::StartNew() # Three workers at a time: nine PowerShell processes at once starved a 4-core PC. A slot is refilled as soon as any # section ends, each section is timed from its own start, and the run cap only stops what is still running, so a # slow section never spends a later one's time (one shared 35 s countdown timed out Environment on CI, 2026-10-16). # Slowest first, by CI and VM measurements: AI up to its 20 s budget, System and Status about 10 s, Apps 7 s, Mole 4 to 13 s. $parallel=3 $sectionTimeout=30 $runCap=90 $order=@('AI','System','Status','Apps','Mole','Storage','Analyze','RecycleTarget','Layout','Updates','Shaders','Environment','Freeze','AppEvents','UpdateLogs') $native=Join-Path ([IO.Path]::GetTempPath()) ('MoleFeedbackNative-'+[guid]::NewGuid().ToString('N')+'.dll') try { . ([scriptblock]::Create($helpers.ToString())); Add-Type -TypeDefinition (MetadataWalker-Source) -OutputAssembly $native; $env:MOLE_FEEDBACK_NATIVE=$native } catch { $env:MOLE_FEEDBACK_NATIVE=$null } $queue=New-Object 'Collections.Generic.Queue[string]' foreach($name in @(@($order|Where-Object {$sections.Contains($_)})+@($sections.Keys|Where-Object {$_ -notin $order}))){$queue.Enqueue($name)} # The report keeps the sections' declared order whatever order they finish in. foreach($name in $sections.Keys){$report.Sections[$name]=[ordered]@{Status='unavailable'}} $running=@{} function Start-Section([string]$name) { try { # InitializationScript is encoded into the child command line on PS 5.1. # Send the growing helper body as remoting data to avoid Windows' 32K limit. Start-Job -ScriptBlock { param($helperText,$sectionText,$target) . ([scriptblock]::Create($helperText)) & ([scriptblock]::Create($sectionText)) $target } -ArgumentList $helpers.ToString(),$sections[$name].ToString(),$Folder } catch { $null } } function Finish-Section([string]$name,$entry,[bool]$timedOut) { $job=$entry.Job try { # A section stopped at its timeout keeps the rows it already produced. $rows=@(Receive-Job $job -ErrorAction SilentlyContinue) if($timedOut){Stop-Job $job;$rows+=@(Receive-Job $job -ErrorAction SilentlyContinue)} $status=if($timedOut){'timeout'}elseif($job.State-eq 'Completed'){'complete'}else{'unavailable'} $elapsed=if(-not $timedOut -and $job.PSEndTime -and $job.PSBeginTime){[int]($job.PSEndTime-$job.PSBeginTime).TotalMilliseconds}else{[int]($total.Elapsed.TotalMilliseconds-$entry.StartedMs)} # Remoting adds machine identifiers to returned objects; rebuild each row. $cleanRows=@(foreach($row in $rows){$clean=[ordered]@{};foreach($p in $row.PSObject.Properties){if($p.Name-notin @('PSComputerName','RunspaceId','PSShowComputerName')){$clean[$p.Name]=$p.Value}};[pscustomobject]$clean}) $report.Sections[$name]=[ordered]@{Status=$status;ElapsedMs=$elapsed;Data=$cleanRows} }catch{$report.Sections[$name]=[ordered]@{Status='unavailable'}} finally{try{if($job.State-eq 'Running'){Stop-Job $job};Remove-Job $job -Force}catch{}} } Write-Host "`nMole Diagnose" Write-Progress -Id 73 -Activity 'Mole Diagnose' -Status 'Collecting diagnostics...' try { while(($queue.Count -or $running.Count) -and $total.Elapsed.TotalSeconds-lt $runCap) { while($running.Count-lt $parallel -and $queue.Count) { $name=$queue.Dequeue() $job=Start-Section $name if($job){$running[$name]=@{Job=$job;StartedMs=$total.Elapsed.TotalMilliseconds}} } if(-not $running.Count){continue} $deadlineMs=$runCap*1000 foreach($entry in $running.Values){$deadlineMs=[Math]::Min($deadlineMs,$entry.StartedMs+$sectionTimeout*1000)} $wait=[int][Math]::Ceiling(($deadlineMs-$total.Elapsed.TotalMilliseconds)/1000) if($wait-gt 0){Wait-Job -Job @($running.Values|ForEach-Object {$_.Job}) -Any -Timeout $wait|Out-Null} $nowMs=$total.Elapsed.TotalMilliseconds foreach($name in @($running.Keys)) { $entry=$running[$name] if($entry.Job.State-notin @('NotStarted','Running','Stopping')){Finish-Section $name $entry $false;$running.Remove($name)} elseif($nowMs-ge $entry.StartedMs+$sectionTimeout*1000){Finish-Section $name $entry $true;$running.Remove($name)} } } # The run cap stops what is still running and records what never started. foreach($name in @($running.Keys)){$entry=$running[$name];Finish-Section $name $entry ($entry.Job.State-in @('NotStarted','Running','Stopping'));$running.Remove($name)} while($queue.Count){$report.Sections[$queue.Dequeue()]=[ordered]@{Status='not-started'}} } finally { # Ctrl-C or an error still ends every owned worker process before the helper DLL is deleted. foreach($entry in @($running.Values)){try{Stop-Job $entry.Job;Remove-Job $entry.Job -Force}catch{}} Write-Progress -Id 73 -Activity 'Mole Diagnose' -Completed $env:MOLE_FEEDBACK_NATIVE=$null try { [IO.File]::Delete($native) } catch {} } $report.ElapsedMs=$total.ElapsedMilliseconds # Fixed facts first so a reader sees the shape of the problem before the rows. try { $report.Summary=Report-Summary $report.Sections } catch { $report.Summary=[ordered]@{Status='unavailable'} } $DestinationSpecified=-not [string]::IsNullOrWhiteSpace($Destination) if(-not $Destination){$Destination=[Environment]::GetFolderPath('Desktop')} $text=$report|ConvertTo-Json -Depth 12 -Compress # A final guard also covers provider-supplied display names; never emit raw exceptions. foreach($private in @($env:USERPROFILE,$env:COMPUTERNAME,$env:USERNAME)) { if($private -and $private.Length-ge 3){$text=$text -replace [regex]::Escape($private.Replace('\','\\')),'[redacted]';$text=$text -replace [regex]::Escape($private),'[redacted]'} } $saved=Save-FeedbackReport $text $Destination $file=$saved.Path $elapsedText=[TimeSpan]::FromMilliseconds($total.ElapsedMilliseconds).ToString('mm\:ss') Write-Host "[OK] Done in $elapsedText. Report saved:" -ForegroundColor Green Write-Host " $file" if($saved.FellBack){Write-Host " $Destination could not be written, so the report is in the temp folder instead." -ForegroundColor Yellow} Write-Host ' Review the file, then email it to hi@mole.fit with a short description of the problem.' Write-Host '' # Match the Mac handoff (Mac 973465633): open the folder, not a selection, since the finished line already names the # file and a highlighted file read as one more step. Explicit support output folders remain non-interactive. if(-not $DestinationSpecified) { try { Start-Process -FilePath (Join-Path $env:WINDIR 'explorer.exe') -ArgumentList ('"'+(Split-Path -Parent $file)+'"') -ErrorAction Stop | Out-Null } catch {} } } if($ChooseFolder -and -not $TargetPath) { if([Threading.Thread]::CurrentThread.GetApartmentState() -eq 'STA') { Add-Type -AssemblyName System.Windows.Forms $picker=New-Object Windows.Forms.FolderBrowserDialog $picker.Description='Select the folder that was slow to recycle. Cancel to skip. Nothing will be deleted.' $picker.ShowNewFolderButton=$false try {if($picker.ShowDialog()-eq [Windows.Forms.DialogResult]::OK){$TargetPath=$picker.SelectedPath}}finally{$picker.Dispose()} } else { # PowerShell 7 can use MTA; Windows PowerShell 5.1 normally uses STA. # Keep the same read-only collection when a native picker cannot open. $TargetPath=(Read-Host 'Folder to inspect (paste its path, or press Enter to skip)').Trim().Trim('"') } } Invoke-MoleFeedback -Folder $TargetPath -Destination $OutputDirectory