feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history

Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting
history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com
and sibling-fork URL fixes that aelrynth git still has as tombohar links.

Co-authored-by: BlankenshipG <BlankenshipG@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-10-04 15:43:50 +00:00
commit 4ddbb52eb2
No known key found for this signature in database
244 changed files with 59710 additions and 3067 deletions

View file

@ -1,6 +1,21 @@
param(
[string]$Destination = "C:\Games\RynthCore",
[switch]$SkipPublish
[string]$PluginsDestination = "C:\Games\RynthSuite",
[switch]$SkipPublish,
# When set, skip both the launcher publish AND the launcher payload copy
# to $Destination root. Use this for engine-only / plugin-only iteration
# while the launcher (RynthCore.exe) is running — without it, the launcher's
# held Avalonia.Base.dll causes a Copy-Item lock failure that wipes the
# Runtime\ folder. Engine still publishes/deploys to Runtime\ and plugins
# still deploy under $PluginsDestination.
[switch]$SkipLauncher,
# Pre-deploy pattern gate (tools\check-patterns.ps1): verify every acclient.exe
# signature embedded in the engine source still resolves uniquely + correctly
# against the live client BEFORE shipping. -SkipPatternCheck bypasses it;
# -AcClient overrides the binary it checks (default: auto-detect the private
# copy under $Destination\AcClient, else C:\Turbine\Asheron's Call).
[switch]$SkipPatternCheck,
[string]$AcClient = ""
)
$ErrorActionPreference = "Stop"
@ -9,24 +24,73 @@ Set-StrictMode -Version Latest
$repoRoot = Split-Path -Parent $PSScriptRoot
$launcherProject = Join-Path $repoRoot "src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj"
$engineProject = Join-Path $repoRoot "src\RynthCore.Engine\RynthCore.Engine.csproj"
$loaderProject = Join-Path $repoRoot "src\RynthCore.Loader\RynthCore.Loader.csproj"
# Plugins are deployed to per-plugin folders under $PluginsDestination
# (e.g. C:\Games\RynthSuite\RynthAi\). Users register plugin DLLs through
# the launcher's "Add Plugin DLL" UI; the engine no longer relies on a
# default Runtime\Plugins\ scan being populated by deploy.
#
# RynthAi's live source lives in a separate repo at C:\Projects\RynthSuite -
# the rynthcore\Plugins\RynthCore.Plugin.RynthAi tree is a stub (~1 MB
# published) that lacks Combat / Loot / Meta / Raycasting / LegacyUi.
# Always source from the RynthSuite tree so the real ~8 MB plugin ships.
$rynthAiSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi"
$rynthChatSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthChat"
$rynthVisionSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthVision"
$rynthJuiceSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthJuice"
$pluginProjects = @(
@{
Project = Join-Path $repoRoot "Plugins\RynthCore.Plugin.HelloBox\RynthCore.Plugin.HelloBox.csproj"
Publish = Join-Path $repoRoot "Plugins\RynthCore.Plugin.HelloBox\bin\Release\net9.0-windows\win-x86\publish"
DllName = "RynthCore.Plugin.HelloBox.dll"
Project = Join-Path $rynthAiSourceRoot "RynthCore.Plugin.RynthAi.csproj"
Publish = Join-Path $rynthAiSourceRoot "bin\Release\net10.0-windows\win-x86\publish"
DllName = "RynthCore.Plugin.RynthAi.dll"
DestSubdir = "RynthAi"
},
@{
Project = Join-Path $repoRoot "Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj"
Publish = Join-Path $repoRoot "Plugins\RynthCore.Plugin.RynthAi\bin\Release\net9.0-windows\win-x86\publish"
DllName = "RynthCore.Plugin.RynthAi.dll"
Project = Join-Path $rynthChatSourceRoot "RynthCore.Plugin.RynthChat.csproj"
Publish = Join-Path $rynthChatSourceRoot "bin\Release\net10.0-windows\win-x86\publish"
DllName = "RynthCore.Plugin.RynthChat.dll"
DestSubdir = "RynthChat"
},
# RynthVision sets <PublishDir> to its deploy home, so publish lands
# directly in $PluginsDestination\RynthVision. The copy step below detects
# source == dest and skips the redundant self-copy.
@{
Project = Join-Path $rynthVisionSourceRoot "RynthCore.Plugin.RynthVision.csproj"
Publish = Join-Path $PluginsDestination "RynthVision"
DllName = "RynthCore.Plugin.RynthVision.dll"
DestSubdir = "RynthVision"
},
@{
Project = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthTracker\RynthCore.Plugin.RynthTracker.csproj"
Publish = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthTracker\bin\Release\net10.0-windows\win-x86\publish"
DllName = "RynthCore.Plugin.RynthTracker.dll"
DestSubdir = "RynthTracker"
},
# RynthJuice sets <PublishDir> to its deploy home (like RynthVision), so
# publish lands directly in $PluginsDestination\RynthJuice and the copy step
# below detects source == dest and skips the redundant self-copy.
@{
Project = Join-Path $rynthJuiceSourceRoot "RynthCore.Plugin.RynthJuice.csproj"
Publish = Join-Path $PluginsDestination "RynthJuice"
DllName = "RynthCore.Plugin.RynthJuice.dll"
DestSubdir = "RynthJuice"
},
# RynthNav also publishes straight to its deploy home via <PublishDir>.
# It was missing from this list entirely, so full deploys never refreshed it.
@{
Project = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthNav\RynthCore.Plugin.RynthNav.csproj"
Publish = Join-Path $PluginsDestination "RynthNav"
DllName = "RynthCore.Plugin.RynthNav.dll"
DestSubdir = "RynthNav"
}
)
$launcherPublish = Join-Path $repoRoot "src\RynthCore.App.Avalonia\bin\Release\net9.0-windows7.0\win-x86\publish"
$enginePublish = Join-Path $repoRoot "src\RynthCore.Engine\bin\Release\net9.0-windows\win-x86\publish"
$launcherPublish = Join-Path $repoRoot "src\RynthCore.App.Avalonia\bin\Release\net10.0-windows7.0\win-x86\publish"
$enginePublish = Join-Path $repoRoot "src\RynthCore.Engine\bin\Release\net10.0-windows\win-x86\publish"
$loaderPublish = Join-Path $repoRoot "src\RynthCore.Loader\bin\Release\net10.0-windows\win-x86\publish"
$runtimeDir = Join-Path $Destination "Runtime"
$runtimePluginsDir = Join-Path $runtimeDir "Plugins"
function Copy-FilteredChildren {
param(
@ -41,14 +105,71 @@ function Copy-FilteredChildren {
} | Copy-Item -Destination $Target -Recurse -Force
}
# ---------------------------------------------------------------------------
# Pre-deploy pattern gate: verify every acclient.exe signature embedded in the
# engine source still resolves uniquely + correctly against the live client
# binary BEFORE we publish/ship. A future AC patch / ACE rebuild that shifts
# code or a data global fails HERE instead of silently shipping a hook that
# falls back to a stale VA at runtime. (tools\pe_pattern.py CHECK, wrapped by
# tools\check-patterns.ps1.) Bypass: -SkipPatternCheck. Target: -AcClient.
# ---------------------------------------------------------------------------
if (-not $SkipPatternCheck) {
$checkScript = Join-Path $repoRoot "tools\check-patterns.ps1"
$acClientPath = $AcClient
if ([string]::IsNullOrWhiteSpace($acClientPath)) {
foreach ($cand in @((Join-Path $Destination "AcClient\acclient.exe"), "C:\Turbine\Asheron's Call\acclient.exe")) {
if (Test-Path -LiteralPath $cand) { $acClientPath = $cand; break }
}
}
# Fail CLOSED: a gate that silently downgrades to a warning when python /
# the script / the binary is missing is no gate at all — the explicit
# bypass is -SkipPatternCheck.
if (-not (Get-Command python -ErrorAction SilentlyContinue)) {
throw "Pattern gate cannot run: 'python' is not on PATH. Install Python, or pass -SkipPatternCheck to bypass deliberately."
}
elseif (-not (Test-Path -LiteralPath $checkScript)) {
throw "Pattern gate cannot run: $checkScript not found. Pass -SkipPatternCheck to bypass deliberately."
}
elseif ([string]::IsNullOrWhiteSpace($acClientPath) -or -not (Test-Path -LiteralPath $acClientPath)) {
throw "Pattern gate cannot run: no acclient.exe found (tried '$Destination\AcClient' and 'C:\Turbine\Asheron''s Call'). Pass -AcClient <path>, or -SkipPatternCheck to bypass deliberately."
}
else {
Write-Host "Pattern gate: verifying engine signatures against $acClientPath ..."
& $checkScript -AcClient $acClientPath
if ($LASTEXITCODE -ne 0) {
throw "Pattern gate FAILED (exit $LASTEXITCODE) - aborting deploy. A signature drifted or is wrong; re-cut it with tools\pe_pattern.py (GEN / ALL / DATA), fix the source, rebuild, and retry. Override with -SkipPatternCheck only if you understand the risk."
}
Write-Host "Pattern gate PASSED - all engine signatures unique & correct."
}
}
function Invoke-Publish {
param(
[Parameter(Mandatory = $true)][string]$What,
[Parameter(Mandatory = $true)][string[]]$Arguments
)
dotnet @Arguments
# PS 5.1's $ErrorActionPreference=Stop does NOT throw on a native exe's
# nonzero exit — without this check a failed publish silently deployed the
# PREVIOUS publish output (the root staleness trap).
if ($LASTEXITCODE -ne 0) {
throw "dotnet publish FAILED for $What (exit $LASTEXITCODE) - aborting deploy so stale output cannot ship."
}
}
if (-not $SkipPublish) {
$env:DOTNET_CLI_HOME = Join-Path $repoRoot ".dotnet-home-deploy-clean"
$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1"
dotnet publish $launcherProject -c Release -r win-x86
dotnet publish $engineProject -c Release
if (-not $SkipLauncher) {
# --self-contained false is required: omitting it with the launcher's IncludeNativeLibrariesForSelfExtract=true produces a broken half-payload (apphost + coreclr.dll, no framework) that reports ".NET is not installed".
Invoke-Publish -What "launcher" -Arguments @('publish', $launcherProject, '-c', 'Release', '-r', 'win-x86', '--self-contained', 'false')
}
Invoke-Publish -What "engine" -Arguments @('publish', $engineProject, '-c', 'Release')
Invoke-Publish -What "loader" -Arguments @('publish', $loaderProject, '-c', 'Release')
foreach ($plugin in $pluginProjects) {
dotnet publish $plugin.Project -c Release
Invoke-Publish -What $plugin.DllName -Arguments @('publish', $plugin.Project, '-c', 'Release')
}
}
@ -77,32 +198,129 @@ $rootCleanup = @(
"RynthCore.exe.pre-avalonia-redeploy-20260331.bak"
)
foreach ($name in $rootCleanup) {
$target = Join-Path $Destination $name
if (Test-Path -LiteralPath $target) {
Remove-Item -LiteralPath $target -Recurse -Force
if (-not $SkipLauncher) {
# Same pre-flight for the launcher payload: a running RynthCore.exe holds its
# Avalonia DLLs, and the copy failing on one of them used to abort the deploy
# AFTER Runtime\ below had been wiped (2026-09-26) — no engine until a redeploy.
$launcherLocked = @()
foreach ($f in Get-ChildItem -LiteralPath $launcherPublish -File) {
$target = Join-Path $Destination $f.Name
if ($f.Name -eq "RynthCore.App.Avalonia.exe") { $target = Join-Path $Destination "RynthCore.exe" }
if (-not (Test-Path -LiteralPath $target)) { continue }
try {
$s = [System.IO.File]::Open($target, 'Open', 'ReadWrite', 'None')
$s.Close()
} catch {
$launcherLocked += $target
}
}
if ($launcherLocked.Count -gt 0) {
throw ("Deploy aborted BEFORE touching anything - $($launcherLocked.Count) launcher file(s) are locked (close the RynthCore launcher, or pass -SkipLauncher):`n " + ($launcherLocked -join "`n "))
}
foreach ($name in $rootCleanup) {
$target = Join-Path $Destination $name
if (Test-Path -LiteralPath $target) {
Remove-Item -LiteralPath $target -Recurse -Force
}
}
}
if (Test-Path -LiteralPath $runtimeDir) {
# Lock pre-flight BEFORE the destructive wipe. A running client holds
# Runtime\RynthCore.Loader.dll (loaded UNshadowed into acclient.exe) and
# its .engine_loads shadow DLLs; the old behavior wiped Runtime\ first and
# then died on the locked file, leaving a half-destroyed deploy. Probe
# every file for an exclusive open and abort cleanly while the old deploy
# is still intact.
$locked = @()
foreach ($f in Get-ChildItem -LiteralPath $runtimeDir -Recurse -File) {
try {
$s = [System.IO.File]::Open($f.FullName, 'Open', 'ReadWrite', 'None')
$s.Close()
} catch {
$locked += $f.FullName
}
}
if ($locked.Count -gt 0) {
throw ("Deploy aborted BEFORE wiping Runtime\ - $($locked.Count) file(s) are locked by running processes (close all AC clients and the launcher, then retry):`n " + ($locked -join "`n "))
}
Remove-Item -LiteralPath $runtimeDir -Recurse -Force
}
New-Item -ItemType Directory -Path $Destination -Force | Out-Null
New-Item -ItemType Directory -Path $runtimeDir -Force | Out-Null
New-Item -ItemType Directory -Path $runtimePluginsDir -Force | Out-Null
Copy-FilteredChildren -Source $launcherPublish -Target $Destination -ExcludeNames @("RynthCore.App.Avalonia.exe") -ExcludeExtensions @(".pdb")
Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeExtensions @(".pdb")
foreach ($plugin in $pluginProjects) {
Copy-FilteredChildren -Source $plugin.Publish -Target $runtimePluginsDir -ExcludeNames @("cimgui.dll") -ExcludeExtensions @(".pdb")
if (-not $SkipLauncher) {
# Launcher payload to root, except the bootstrapper exe (renamed below).
Copy-FilteredChildren -Source $launcherPublish -Target $Destination -ExcludeNames @("RynthCore.App.Avalonia.exe") -ExcludeExtensions @(".pdb")
}
Copy-Item -LiteralPath (Join-Path $launcherPublish "RynthCore.App.Avalonia.exe") -Destination (Join-Path $Destination "RynthCore.exe") -Force
foreach ($plugin in $pluginProjects) {
Copy-Item -LiteralPath (Join-Path $plugin.Publish $plugin.DllName) -Destination (Join-Path $runtimePluginsDir $plugin.DllName) -Force
}
Get-ChildItem -Path $Destination -Recurse -Filter *.pdb -File | Remove-Item -Force
# Engine payload to Runtime\. Skip the bundled Plugins\ subfolder - plugins
# are deployed separately to $PluginsDestination so they have a single home.
Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeNames @("Plugins") -ExcludeExtensions @(".pdb")
Write-Host "Launcher deployed to $Destination"
# Loader DLL - this is what RynthCore.Injector loads into acclient.exe; the
# Loader then maps RynthCore.Engine.dll and provides hot-reload support.
Copy-Item -LiteralPath (Join-Path $loaderPublish "RynthCore.Loader.dll") -Destination (Join-Path $runtimeDir "RynthCore.Loader.dll") -Force
# SEH trampoline - small native x86 MSVC DLL providing __try/__except wrappers
# around dangerous AC API calls so object-teardown AVs are caught instead of
# crashing acclient.exe. Built by native\SehTrampoline\Build-SehTrampoline.ps1.
$sehTrampolineSrc = Join-Path $repoRoot "native\SehTrampoline\bin\RynthCore.SehTrampoline.dll"
$sehTrampolineC = Join-Path $repoRoot "native\SehTrampoline\SehTrampoline.c"
if (-not (Test-Path -LiteralPath $sehTrampolineSrc)) {
# Fail closed: the trampoline is load-bearing (SEH-guarded AC reads) and a
# missing DLL silently shipped an engine whose guarded calls all throw.
throw "RynthCore.SehTrampoline.dll not found at $sehTrampolineSrc - build it with native\SehTrampoline\Build-SehTrampoline.ps1, then re-run deploy."
}
if (Test-Path -LiteralPath $sehTrampolineC) {
# The trampoline is hand-built (cl.exe), not part of dotnet publish — a
# newer .c than the built DLL means the binary about to ship is stale.
$srcTime = (Get-Item -LiteralPath $sehTrampolineC).LastWriteTime
$dllTime = (Get-Item -LiteralPath $sehTrampolineSrc).LastWriteTime
if ($srcTime -gt $dllTime) {
throw "RynthCore.SehTrampoline.dll is STALE (SehTrampoline.c edited $srcTime > DLL built $dllTime). Rebuild with native\SehTrampoline\Build-SehTrampoline.ps1, then re-run deploy."
}
}
Copy-Item -LiteralPath $sehTrampolineSrc -Destination (Join-Path $runtimeDir "RynthCore.SehTrampoline.dll") -Force
Write-Host "SEH trampoline deployed to $runtimeDir"
if (-not $SkipLauncher) {
Copy-Item -LiteralPath (Join-Path $launcherPublish "RynthCore.App.Avalonia.exe") -Destination (Join-Path $Destination "RynthCore.exe") -Force
}
foreach ($plugin in $pluginProjects) {
$pluginSrc = Join-Path $plugin.Publish $plugin.DllName
if (-not (Test-Path -LiteralPath $pluginSrc)) {
Write-Warning "Plugin DLL not found at $pluginSrc - skipping copy."
continue
}
$pluginTargetDir = Join-Path $PluginsDestination $plugin.DestSubdir
if (-not (Test-Path -LiteralPath $pluginTargetDir)) {
New-Item -ItemType Directory -Path $pluginTargetDir -Force | Out-Null
}
# Only the DLL - leave any user data (LootProfiles\, imgui.ini, etc.)
# in place by not touching anything else under $pluginTargetDir.
$pluginDest = Join-Path $pluginTargetDir $plugin.DllName
if ([System.IO.Path]::GetFullPath($pluginSrc) -ieq [System.IO.Path]::GetFullPath($pluginDest)) {
# Plugin published straight into its deploy home (see RynthVision) -
# nothing to copy, the publish already put the DLL in place.
Write-Host "Plugin $($plugin.DllName) already in place at $pluginTargetDir; skipping copy."
} else {
Copy-Item -LiteralPath $pluginSrc -Destination $pluginDest -Force
Write-Host "Plugin $($plugin.DllName) deployed to $pluginTargetDir"
}
}
# Scoped pdb sweep: root + Runtime\ only. A $Destination-wide recurse walked
# the ~1.4 GB private AcClient copy on every deploy for nothing.
Get-ChildItem -Path $Destination -Filter *.pdb -File | Remove-Item -Force
Get-ChildItem -Path $runtimeDir -Recurse -Filter *.pdb -File | Remove-Item -Force
if (-not $SkipLauncher) {
Write-Host "Launcher deployed to $Destination"
}
Write-Host "Engine runtime deployed to $runtimeDir"

View file

@ -0,0 +1,344 @@
# ============================================================================
# Show-AcMemoryTrend.ps1
#
# Live console-based memory monitor for acclient.exe. Complements the
# persistent CSV logger (Watch-AcMemory.ps1) by giving an in-the-moment
# trend view: current WorkingSet/Private/Virtual + handle/thread counts,
# deltas vs. session start, and computed growth rates (MB/min, MB/hour)
# with stable/growing/shrinking indicators.
#
# Two parallel rate windows are shown:
# * all-time — from the first sample we took to now (good for long
# averaged leak rates)
# * recent — last ~15 samples (~75s at 5s tick), so a process that
# leaked at startup then stabilised reads STABLE in this
# column while the all-time column still shows growth
#
# Zero impact on the running engine — pure OS query, no injection.
#
# This is a live VIEWER only — no file output. Persistence is owned by
# Watch-AcMemory.ps1 (5-min CSV samples to C:\Games\RynthCore\Logs\).
# Both can run in parallel against the same PID.
#
# Usage:
# .\Show-AcMemoryTrend.ps1 # auto-pick first acclient.exe, 5s refresh
# .\Show-AcMemoryTrend.ps1 -TargetPid 35456 # explicit PID
# .\Show-AcMemoryTrend.ps1 -IntervalSeconds 2 # tighter cadence
# .\Show-AcMemoryTrend.ps1 -HistorySize 120 # deeper recent-trend window
#
# acclient.exe is x86 — 2 GB user address space ceiling. The viewer
# surfaces a WARNING line at >1800 MB Virtual and a CRITICAL line at
# >1900 MB Virtual.
#
# Exit: Ctrl-C (clean), or auto-exits with a final summary when the
# watched process terminates.
#
# Accessibility: status indicators use text labels (STABLE / GROWING /
# SHRINKING) and ASCII arrows (->, ^, v). Colour is used as a
# supplement only and is never the sole signal.
# ============================================================================
[CmdletBinding()]
param(
[Alias('Pid')]
[int]$TargetPid = 0,
[int]$IntervalSeconds = 5,
# How many samples to keep in the rolling buffer. 60 @ 5s = 5 min.
[int]$HistorySize = 60,
# How many of the most-recent samples define the "recent trend" slope.
[int]$RecentSampleCount = 15,
# MB/min threshold below which a memory metric reads STABLE.
[double]$StableThresholdMbPerMin = 0.5,
# Handles/hour threshold below which the handle metric reads STABLE.
[double]$StableThresholdHandlesPerHour = 50.0
)
# ---------------------------------------------------------------------------
# Resolve target PID — explicit param wins, else auto-pick the running client.
# ---------------------------------------------------------------------------
if ($TargetPid -eq 0) {
$candidates = @(Get-Process -Name acclient -ErrorAction SilentlyContinue)
if ($candidates.Count -eq 0) {
Write-Error 'No acclient.exe process found. Pass -TargetPid <id> or launch AC first.'
exit 1
}
if ($candidates.Count -gt 1) {
Write-Warning ("Multiple acclient.exe processes running ({0}). Picking PID {1}; pass -TargetPid to override." -f $candidates.Count, $candidates[0].Id)
Start-Sleep -Seconds 2
}
$TargetPid = $candidates[0].Id
}
$proc = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue
if (-not $proc) {
Write-Error "No process found with PID $TargetPid."
exit 1
}
# StartTime can throw on protected processes; tolerate it.
$startTime = $null
try { $startTime = $proc.StartTime } catch { $startTime = (Get-Date) }
# ---------------------------------------------------------------------------
# Sample state. Each sample is a PSCustomObject; we keep at most $HistorySize.
# ---------------------------------------------------------------------------
$history = New-Object System.Collections.Generic.List[object]
$firstSample = $null
$sessionStartWall = Get-Date
function New-Sample {
param([System.Diagnostics.Process]$p)
[pscustomobject]@{
Time = Get-Date
WsMB = [double]($p.WorkingSet64 / 1MB)
PrivMB = [double]($p.PrivateMemorySize64 / 1MB)
VmMB = [double]($p.VirtualMemorySize64 / 1MB)
Handles = [int]$p.HandleCount
Threads = [int]$p.Threads.Count
}
}
# Compute MB-per-minute slope between two samples. Returns 0 if window is
# too short to be meaningful.
function Get-RatePerMinute {
param($older, $newer, [string]$field)
if (-not $older -or -not $newer) { return 0.0 }
$deltaMinutes = ($newer.Time - $older.Time).TotalMinutes
if ($deltaMinutes -le 0.01) { return 0.0 }
return ($newer.$field - $older.$field) / $deltaMinutes
}
# Pick a text status label + an ASCII arrow given a slope and a stability
# threshold. The arrow + label are the load-bearing signals (the user is
# colorblind — colour, where used, is a supplement only).
function Get-Status {
param([double]$ratePerMinute, [double]$threshold)
$abs = [math]::Abs($ratePerMinute)
if ($abs -lt $threshold) {
return [pscustomobject]@{ Label = 'STABLE '; Arrow = '->'; Color = 'Gray' }
}
if ($ratePerMinute -gt 0) {
return [pscustomobject]@{ Label = 'GROWING '; Arrow = '^^'; Color = 'Yellow' }
}
return [pscustomobject]@{ Label = 'SHRINKING'; Arrow = 'vv'; Color = 'Cyan' }
}
# Format a delta with explicit sign so STABLE vs GROWING is visually obvious
# even without colour. "+12.3" / "-4.5" / " 0.0".
function Format-Delta {
param([double]$v, [int]$width = 7, [int]$decimals = 1)
# Build the .NET composite-format string explicitly to dodge PS's
# "variable:scope" lookahead after a colon. e.g. width=7, decimals=1 ->
# "{0,7:+0.0;-0.0; 0.0}".
$dec = ('0' * $decimals)
$pos = if ($decimals -gt 0) { "+0.$dec" } else { '+0' }
$neg = if ($decimals -gt 0) { "-0.$dec" } else { '-0' }
$zero = if ($decimals -gt 0) { " 0.$dec" } else { ' 0' }
$fmt = '{0,' + $width + ':' + $pos + ';' + $neg + ';' + $zero + '}'
return ($fmt -f $v)
}
# ---------------------------------------------------------------------------
# Console plumbing. We try in-place redraw via SetCursorPosition; if the host
# doesn't support it (ISE, some remote shells) we fall back to Clear-Host.
# Either way, redraws must tolerate a resized terminal — no fixed widths
# beyond the host's BufferWidth.
# ---------------------------------------------------------------------------
$supportsCursor = $true
try {
[void][Console]::CursorTop
[void][Console]::CursorLeft
} catch {
$supportsCursor = $false
}
function Clear-Frame {
if ($supportsCursor) {
try {
[Console]::SetCursorPosition(0, 0)
# Overwrite the previously-drawn region with blanks. We pad to the
# current BufferWidth so the new frame doesn't leave stale chars
# at the right edge after a resize.
$w = [Console]::BufferWidth
$h = [Math]::Min(40, [Console]::BufferHeight - 1)
$blank = ' ' * ($w - 1)
for ($i = 0; $i -lt $h; $i++) {
[Console]::SetCursorPosition(0, $i)
[Console]::Write($blank)
}
[Console]::SetCursorPosition(0, 0)
} catch {
# Resize or other transient failure — fall back to Clear-Host.
Clear-Host
}
} else {
Clear-Host
}
}
function Write-Line {
param([string]$text, [ConsoleColor]$Color = [ConsoleColor]::White)
# Truncate to BufferWidth-1 so we never wrap mid-frame and corrupt
# subsequent SetCursorPosition writes.
try {
$maxLen = [Console]::BufferWidth - 1
if ($maxLen -gt 0 -and $text.Length -gt $maxLen) {
$text = $text.Substring(0, $maxLen)
}
} catch { }
$prevFg = $null
try { $prevFg = [Console]::ForegroundColor } catch { }
try { [Console]::ForegroundColor = $Color } catch { }
[Console]::WriteLine($text)
if ($null -ne $prevFg) {
try { [Console]::ForegroundColor = $prevFg } catch { }
}
}
function Format-Uptime {
param([TimeSpan]$ts)
return ("{0:00}:{1:00}:{2:00}" -f [int]$ts.TotalHours, $ts.Minutes, $ts.Seconds)
}
# ---------------------------------------------------------------------------
# Main loop. Sample, append to history, render frame, sleep.
# Ctrl-C handling: PowerShell raises a PipelineStoppedException out of
# Start-Sleep; the finally block prints a goodbye and restores cursor.
# ---------------------------------------------------------------------------
try {
Clear-Frame
Write-Line ("Starting Show-AcMemoryTrend for PID {0} (interval {1}s, history {2})..." -f $TargetPid, $IntervalSeconds, $HistorySize)
Start-Sleep -Milliseconds 250
while ($true) {
$p = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue
if (-not $p) {
Clear-Frame
Write-Line ("PID {0} (acclient.exe) exited at {1}." -f $TargetPid, (Get-Date).ToString('HH:mm:ss')) Red
if ($firstSample -and $history.Count -gt 0) {
$last = $history[$history.Count - 1]
$sessionMin = ($last.Time - $firstSample.Time).TotalMinutes
if ($sessionMin -gt 0) {
$wsRate = ($last.WsMB - $firstSample.WsMB) / $sessionMin
$privRate = ($last.PrivMB - $firstSample.PrivMB) / $sessionMin
$vmRate = ($last.VmMB - $firstSample.VmMB) / $sessionMin
Write-Line ("Final summary : {0} samples over {1:0.0} min" -f $history.Count, $sessionMin)
Write-Line (" WS : last={0,5:0.0} MB delta={1} rate={2,7:+0.00;-0.00; 0.00} MB/min" -f $last.WsMB, (Format-Delta ($last.WsMB - $firstSample.WsMB)), $wsRate)
Write-Line (" Priv: last={0,5:0.0} MB delta={1} rate={2,7:+0.00;-0.00; 0.00} MB/min" -f $last.PrivMB, (Format-Delta ($last.PrivMB - $firstSample.PrivMB)), $privRate)
Write-Line (" VM : last={0,5:0.0} MB delta={1} rate={2,7:+0.00;-0.00; 0.00} MB/min" -f $last.VmMB, (Format-Delta ($last.VmMB - $firstSample.VmMB)), $vmRate)
}
}
exit 0
}
$sample = New-Sample -p $p
if (-not $firstSample) { $firstSample = $sample }
$history.Add($sample)
if ($history.Count -gt $HistorySize) {
$history.RemoveAt(0)
}
# ---- Compute deltas + rates ----
$deltaWs = $sample.WsMB - $firstSample.WsMB
$deltaPriv = $sample.PrivMB - $firstSample.PrivMB
$deltaVm = $sample.VmMB - $firstSample.VmMB
$deltaHnd = $sample.Handles - $firstSample.Handles
$deltaThr = $sample.Threads - $firstSample.Threads
$allTimeWs = Get-RatePerMinute $firstSample $sample 'WsMB'
$allTimePriv = Get-RatePerMinute $firstSample $sample 'PrivMB'
$allTimeVm = Get-RatePerMinute $firstSample $sample 'VmMB'
$allTimeHnd = Get-RatePerMinute $firstSample $sample 'Handles'
# Recent window: last N samples, oldest of those vs newest.
$recentOlder = $null
if ($history.Count -ge 2) {
$idx = [Math]::Max(0, $history.Count - $RecentSampleCount)
$recentOlder = $history[$idx]
}
$recentWs = Get-RatePerMinute $recentOlder $sample 'WsMB'
$recentPriv = Get-RatePerMinute $recentOlder $sample 'PrivMB'
$recentVm = Get-RatePerMinute $recentOlder $sample 'VmMB'
$recentHnd = Get-RatePerMinute $recentOlder $sample 'Handles'
$statWs = Get-Status -ratePerMinute $recentWs -threshold $StableThresholdMbPerMin
$statPriv = Get-Status -ratePerMinute $recentPriv -threshold $StableThresholdMbPerMin
$statVm = Get-Status -ratePerMinute $recentVm -threshold $StableThresholdMbPerMin
# Handle threshold is given per-hour; convert to per-minute for the
# comparator so we share the same Get-Status helper.
$statHnd = Get-Status -ratePerMinute $recentHnd -threshold ($StableThresholdHandlesPerHour / 60.0)
# ---- Render frame ----
Clear-Frame
$procUptime = if ($startTime) { (Get-Date) - $startTime } else { [TimeSpan]::Zero }
$sessionUptime = (Get-Date) - $sessionStartWall
Write-Line "============================================================================"
Write-Line (" Show-AcMemoryTrend PID {0,-6} now {1}" -f $TargetPid, (Get-Date).ToString('HH:mm:ss'))
Write-Line (" proc started {0} proc uptime {1} viewer uptime {2}" -f `
($(if ($startTime) { $startTime.ToString('yyyy-MM-dd HH:mm:ss') } else { '?' })), `
(Format-Uptime $procUptime), (Format-Uptime $sessionUptime))
Write-Line (" samples {0}/{1} interval {2}s recent window = last {3} samples" -f `
$history.Count, $HistorySize, $IntervalSeconds, [Math]::Min($RecentSampleCount, $history.Count))
Write-Line "============================================================================"
Write-Line ""
Write-Line " METRIC CURRENT DELTA ALL-TIME RECENT (~75s)"
Write-Line " --------- ----------- ----------- -------------- ------------------------"
# WorkingSet
Write-Line ((" {0,-9} {1,7:0.0} MB {2} MB {3,7:+0.00;-0.00; 0.00} MB/min {4,7:+0.00;-0.00; 0.00} MB/min {5} {6}" -f `
'WS', $sample.WsMB, (Format-Delta $deltaWs), $allTimeWs, $recentWs, $statWs.Arrow, $statWs.Label)) $statWs.Color
# Private
Write-Line ((" {0,-9} {1,7:0.0} MB {2} MB {3,7:+0.00;-0.00; 0.00} MB/min {4,7:+0.00;-0.00; 0.00} MB/min {5} {6}" -f `
'Private', $sample.PrivMB, (Format-Delta $deltaPriv), $allTimePriv, $recentPriv, $statPriv.Arrow, $statPriv.Label)) $statPriv.Color
# Virtual
Write-Line ((" {0,-9} {1,7:0.0} MB {2} MB {3,7:+0.00;-0.00; 0.00} MB/min {4,7:+0.00;-0.00; 0.00} MB/min {5} {6}" -f `
'Virtual', $sample.VmMB, (Format-Delta $deltaVm), $allTimeVm, $recentVm, $statVm.Arrow, $statVm.Label)) $statVm.Color
# Handles (count, not MB; rate column header still reads correctly)
Write-Line ((" {0,-9} {1,7} {2} {3,7:+0.00;-0.00; 0.00} /min {4,7:+0.00;-0.00; 0.00} /min {5} {6}" -f `
'Handles', $sample.Handles, (Format-Delta $deltaHnd 7 0), $allTimeHnd, $recentHnd, $statHnd.Arrow, $statHnd.Label)) $statHnd.Color
# Threads (informational, no slope label — usually noisy by design)
Write-Line (" {0,-9} {1,7} {2}" -f `
'Threads', $sample.Threads, (Format-Delta $deltaThr 7 0))
Write-Line ""
Write-Line (" Per-hour extrapolation (all-time): WS {0,7:+0.0;-0.0; 0.0} MB/hr Priv {1,7:+0.0;-0.0; 0.0} MB/hr VM {2,7:+0.0;-0.0; 0.0} MB/hr Handles {3,7:+0;-0; 0} /hr" -f `
($allTimeWs * 60), ($allTimePriv * 60), ($allTimeVm * 60), ($allTimeHnd * 60))
Write-Line (" Per-hour extrapolation (recent) : WS {0,7:+0.0;-0.0; 0.0} MB/hr Priv {1,7:+0.0;-0.0; 0.0} MB/hr VM {2,7:+0.0;-0.0; 0.0} MB/hr Handles {3,7:+0;-0; 0} /hr" -f `
($recentWs * 60), ($recentPriv * 60), ($recentVm * 60), ($recentHnd * 60))
# ---- x86 2 GB ceiling warnings ----
Write-Line ""
if ($sample.VmMB -ge 1900) {
Write-Line " !! CRITICAL: Virtual memory >= 1900 MB. acclient.exe x86 ceiling is ~2 GB. Crash imminent. !!" Red
Write-Line " !! CRITICAL: Save state / disconnect now before the address space is exhausted. !!" Red
} elseif ($sample.VmMB -ge 1800) {
Write-Line " ** WARNING: Virtual memory >= 1800 MB. Approaching x86 ~2 GB address space ceiling. **" Yellow
}
Write-Line ""
Write-Line " Status legend: STABLE -> (within threshold) GROWING ^^ (rising) SHRINKING vv (falling)"
Write-Line (" Thresholds : memory < {0} MB/min = STABLE; handles < {1} /hr = STABLE" -f $StableThresholdMbPerMin, $StableThresholdHandlesPerHour)
Write-Line " Press Ctrl-C to exit. CSV persistence is handled separately by Watch-AcMemory.ps1."
Start-Sleep -Seconds $IntervalSeconds
}
} finally {
# Make sure the cursor is left on a fresh line so the prompt isn't
# overwritten on whatever row the last frame happened to end on.
try { [Console]::ResetColor() } catch { }
Write-Host ""
Write-Host "Show-AcMemoryTrend exited."
}

338
scripts/Watch-AcFreeze.ps1 Normal file
View file

@ -0,0 +1,338 @@
# ============================================================================
# Watch-AcFreeze.ps1
#
# Out-of-process freeze/wedge watchdog for RynthCore-injected acclient.exe.
# Tails the per-PID heartbeat log (C:\Games\RynthCore\Logs\RynthCore.<pid>.log)
# and applies the SAME wedge heuristics the Avalonia launcher uses
# (MaybeRestartWedgedClients), so it can run with the launcher closed:
#
# * fps=0 with login=1 sustained >= WedgeHoldSeconds (render dead, alive)
# * main-thread queue qd > QueueWedgeDepth with login=1 (queue not draining)
# * combat-mode "stuck Ns" >= StanceStuckSeconds (item-action hard-lock)
# * heartbeat file silent > HbStaleSeconds while alive (engine died in-proc)
#
# On a CONFIRMED wedge it captures a diagnostic bundle, then (by default) kills
# and relaunches the same account so an unattended soak keeps running:
#
# 1. procdump -ma full dump -> Logs\freezes\freeze_<pid>_<stamp>.dmp
# 2. cdb "~*k" all-thread stacks -> ..._cdb.txt
# 3. symbolicate.py on the per-PID log -> ..._symbolicated.txt
#
# Zero impact on the running engine - pure OS query + log tail, no injection.
#
# Usage:
# .\Watch-AcFreeze.ps1 # auto-pick the RynthCore client
# .\Watch-AcFreeze.ps1 -TargetPid 12345
# .\Watch-AcFreeze.ps1 -Account Buffi # account to use on relaunch
# .\Watch-AcFreeze.ps1 -Relaunch:$false # capture only, leave frozen
# .\Watch-AcFreeze.ps1 -Once # single evaluation pass (test)
# ============================================================================
[CmdletBinding()]
param(
[Alias('Pid')]
[int]$TargetPid = 0,
# Account name/id passed to the injector on relaunch. If empty, read from
# the watched PID's launch_context_<pid>.json.
[string]$Account = '',
[int]$IntervalSeconds = 5,
# Sustained dwell before an fps=0 / queue wedge is acted on. Matches the
# launcher's WedgeRestartSeconds default.
[int]$WedgeHoldSeconds = 90,
# Heartbeat file untouched this long while the process lives = engine dead.
[int]$HbStaleSeconds = 120,
# Combat-mode "stuck Ns" threshold for the fps>0 item-action hard-lock.
[int]$StanceStuckSeconds = 300,
# Main-thread queue depth that means AC stopped draining.
[int]$QueueWedgeDepth = 2000,
[bool]$Relaunch = $true,
# Stop relaunching after this many wedges (kill/relaunch loop breaker).
[int]$MaxRelaunch = 5,
[string]$InjectorPath = 'C:\Projects\RynthCore\src\RynthCore.Injector\bin\Release\net10.0-windows\RynthCore.Injector.exe',
[string]$LogDir = 'C:\Games\RynthCore\Logs',
[string]$ToolsDir = 'C:\Games\RynthCore\tools',
[string]$SymbolicatePs1 = 'C:\Projects\RynthCore\tools\symbolicate.ps1',
# Do one evaluation pass and exit (for testing the detection logic).
[switch]$Once
)
$ErrorActionPreference = 'Stop'
$DumpDir = Join-Path $LogDir 'freezes'
$WatchLog = Join-Path $LogDir 'freeze-watch.log'
$ProcDump = Join-Path $ToolsDir 'procdump.exe'
$Cdb = Join-Path $ToolsDir 'dbg_x86\cdb.exe'
New-Item -ItemType Directory -Path $DumpDir -Force | Out-Null
# Heartbeat parse. Groups: 1=fps, 2=plug pump rate, 3=login(in-world), 4=qd.
# NOTE: fps is captured but NOT used as a wedge signal - see Test-Wedge.
$HbRegex = [regex]'hb #\d+ .*?fps=(\d+) .*?plug=(\d+)/s .*?login=(\d)(?:.*?qd=(\d+))?'
$StanceRegex = [regex]'ChangeCombatMode\([^)]*\) retry #\d+ \(stuck (\d+)s'
# The engine's own MainThreadHangWatchdog confirms a permanent main-thread wedge.
# It beats off the UseTime game tick (live even when EndScene/fps is not), so it
# works in every overlay config - the strongest cross-config signal.
$HangPermRegex = [regex]'still hung after'
$RecoverRegex = [regex]'MAIN THREAD RECOVERED'
Add-Type -Namespace Native -Name Win -MemberDefinition @'
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool IsIconic(System.IntPtr hWnd);
'@
function Write-WatchLog {
param([string]$Message, [string]$Level = 'INF')
$line = "[{0}] [{1}] {2}" -f (Get-Date -Format 'HH:mm:ss'), $Level, $Message
Write-Host $line
try { Add-Content -Path $WatchLog -Value $line -Encoding UTF8 } catch { }
}
function Get-RynthCorePids {
# A RynthCore-injected acclient is the one with a recently-written
# per-PID log; Decal/Thwargle clients have no RynthCore.<pid>.log.
$live = @{}
foreach ($p in @(Get-Process -Name acclient -ErrorAction SilentlyContinue)) { $live[$p.Id] = $true }
$result = @()
foreach ($f in Get-ChildItem (Join-Path $LogDir 'RynthCore.*.log') -ErrorAction SilentlyContinue) {
if ($f.Name -match '^RynthCore\.(\d+)\.log$') {
$candidatePid = [int]$Matches[1]
if ($live.ContainsKey($candidatePid) -and ((Get-Date) - $f.LastWriteTime).TotalSeconds -lt 30) {
$result += $candidatePid
}
}
}
return $result
}
function Resolve-TargetPid {
if ($TargetPid -ne 0) { return $TargetPid }
$found = @(Get-RynthCorePids)
if ($found.Count -eq 0) { return 0 }
if ($found.Count -gt 1) {
Write-WatchLog ("Multiple RynthCore clients ({0}); picking {1}. Pass -TargetPid to override." -f ($found -join ', '), $found[0]) 'WRN'
}
return $found[0]
}
function Get-AccountForPid {
param([int]$ProcId)
if ($Account) { return $Account }
$ctx = Join-Path $env:APPDATA "RynthCore\launch_contexts\launch_context_$ProcId.json"
if (Test-Path $ctx) {
try { return (Get-Content $ctx -Raw | ConvertFrom-Json).AccountName } catch { }
}
return ''
}
# Returns $null if healthy, else a reason string. $state is a hashtable used to
# track sustained-dwell start times across calls (per the launcher's logic).
function Test-Wedge {
param([int]$ProcId, [hashtable]$State)
$proc = Get-Process -Id $ProcId -ErrorAction SilentlyContinue
if (-not $proc) { return $null } # gone, not wedged
# Minimized windows can read fps=0 on healthy clients - exempt them.
try {
$h = $proc.MainWindowHandle
if ($h -ne [IntPtr]::Zero -and [Native.Win]::IsIconic($h)) {
$State.Remove('zeroSince'); return $null
}
} catch { }
$logPath = Join-Path $LogDir "RynthCore.$ProcId.log"
$fi = Get-Item $logPath -ErrorAction SilentlyContinue
if (-not $fi) { $State.Remove('zeroSince'); return $null }
if (((Get-Date) - $fi.LastWriteTime).TotalSeconds -gt $HbStaleSeconds) {
return ("engine heartbeat silent for >{0}s while process alive" -f $HbStaleSeconds)
}
# Tail ~16KB (enough for the every-30s combat-stuck line).
$tail = ''
try {
$fs = [System.IO.File]::Open($logPath, 'Open', 'Read', 'ReadWrite, Delete')
try {
$want = [Math]::Min(16384, $fs.Length)
[void]$fs.Seek(-$want, 'End')
$buf = New-Object byte[] $want
$read = $fs.Read($buf, 0, $want)
$tail = [System.Text.Encoding]::UTF8.GetString($buf, 0, $read)
} finally { $fs.Close() }
} catch { return $null }
# STRONGEST signal: the engine's own watchdog confirmed a permanent
# main-thread wedge. Act only on the "still hung" confirmation, and only if
# no later RECOVERED line (transient stalls self-recover).
$hangIdx = $tail.LastIndexOf('MAIN THREAD HANG DETECTED')
if ($hangIdx -ge 0) {
$after = $tail.Substring($hangIdx)
if ($HangPermRegex.IsMatch($after) -and -not $RecoverRegex.IsMatch($after)) {
return "in-process MainThreadHangWatchdog confirmed a permanent main-thread wedge"
}
}
# Item-action hard-lock while the engine threads keep ticking.
$stanceStuck = 0
foreach ($m in $StanceRegex.Matches($tail)) {
$s = [int]$m.Groups[1].Value
if ($s -gt $stanceStuck) { $stanceStuck = $s }
}
if ($stanceStuck -ge $StanceStuckSeconds) {
return ("combat-mode stuck {0}s with login=1 (item-action hard-lock, heartbeat alive)" -f $stanceStuck)
}
$hb = $HbRegex.Matches($tail)
if ($hb.Count -eq 0) { $State.Remove('zeroSince'); return $null }
$last = $hb[$hb.Count - 1]
$fps = [int]$last.Groups[1].Value
$plug = [int]$last.Groups[2].Value
$inWorld = $last.Groups[3].Value -eq '1'
$qd = if ($last.Groups[4].Success) { [int]$last.Groups[4].Value } else { 0 }
# Minimized clients were already exempted above (they throttle fps on their
# own), so fps=0 here = a VISIBLE in-world client that stopped rendering
# (a healthy visible client renders tens of fps). plug=0 = plugin pump dead.
if (-not $inWorld) { $State.Remove('zeroSince'); return $null }
$reason = $null
if ($fps -eq 0) { $reason = "fps=0 with login=1 (render dead)" }
elseif ($plug -eq 0) { $reason = "plugin pump dead (plug=0/s) with login=1" }
elseif ($qd -gt $QueueWedgeDepth) { $reason = ("main-thread queue backing up (qd={0}, login=1)" -f $qd) }
if (-not $reason) { $State.Remove('zeroSince'); return $null }
if (-not $State.ContainsKey('zeroSince')) {
$State['zeroSince'] = Get-Date
Write-WatchLog ("Wedge candidate on PID {0} ({1}) - holding {2}s to confirm." -f $ProcId, $reason, $WedgeHoldSeconds) 'WRN'
return $null
}
$held = ((Get-Date) - $State['zeroSince']).TotalSeconds
if ($held -lt $WedgeHoldSeconds) { return $null }
return ("{0} for >{1}s (heartbeat alive - AC main thread/pump wedged)" -f $reason, $WedgeHoldSeconds)
}
function Invoke-FreezeCapture {
param([int]$ProcId, [string]$Reason)
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$base = Join-Path $DumpDir ("freeze_{0}_{1}" -f $ProcId, $stamp)
$dmp = "$base.dmp"
$cdbOut = "${base}_cdb.txt"
$symOut = "${base}_symbolicated.txt"
Write-WatchLog ("FREEZE CONFIRMED pid={0} - {1}" -f $ProcId, $Reason) 'ERR'
Write-WatchLog ("Capturing bundle -> {0}.*" -f $base)
# 1. Full dump.
if (Test-Path $ProcDump) {
try {
& $ProcDump -accepteula -ma $ProcId $dmp 2>&1 | Out-Null
if (Test-Path $dmp) { Write-WatchLog (" dump: {0} ({1} MB)" -f $dmp, [int]((Get-Item $dmp).Length/1MB)) }
else { Write-WatchLog " dump: procdump produced no file" 'WRN' }
} catch { Write-WatchLog (" dump FAILED: {0}" -f $_.Exception.Message) 'WRN' }
} else { Write-WatchLog (" procdump not found at {0}" -f $ProcDump) 'WRN' }
# 2. All-thread native stacks from the dump (catches fps>0 locks the
# in-process watchdog never logged a stack for).
if ((Test-Path $Cdb) -and (Test-Path $dmp)) {
try {
& $Cdb -z $dmp -c "~*k; q" 2>&1 | Out-File -FilePath $cdbOut -Encoding UTF8
Write-WatchLog (" cdb stacks: {0}" -f $cdbOut)
} catch { Write-WatchLog (" cdb FAILED: {0}" -f $_.Exception.Message) 'WRN' }
}
# 3. Symbolicate the per-PID log (contains the in-process hang stack when
# the EndScene/UseTime watchdog fired).
$logPath = Join-Path $LogDir "RynthCore.$ProcId.log"
if ((Test-Path $SymbolicatePs1) -and (Test-Path $logPath)) {
try {
& powershell -NoProfile -ExecutionPolicy Bypass -File $SymbolicatePs1 $logPath -o $symOut --only-crash 2>&1 | Out-Null
if (Test-Path $symOut) { Write-WatchLog (" symbolicated: {0}" -f $symOut) }
} catch { Write-WatchLog (" symbolicate FAILED: {0}" -f $_.Exception.Message) 'WRN' }
}
return $base
}
function Invoke-Relaunch {
param([int]$DeadPid, [string]$Acct)
if (-not (Test-Path $InjectorPath)) {
Write-WatchLog ("Cannot relaunch - injector not found at {0}" -f $InjectorPath) 'ERR'
return 0
}
if (-not $Acct) {
Write-WatchLog "Cannot relaunch - no account resolved (pass -Account)." 'ERR'
return 0
}
try { Stop-Process -Id $DeadPid -Force -ErrorAction SilentlyContinue } catch { }
Write-WatchLog ("Relaunching account '{0}' via injector..." -f $Acct)
$out = & $InjectorPath --launch --account $Acct 2>&1
$out | ForEach-Object { Write-WatchLog (" injector> {0}" -f $_) }
$m = ($out | Select-String -Pattern 'LAUNCHED_PID=(\d+)' | Select-Object -Last 1)
if ($m) {
$newPid = [int]$m.Matches[0].Groups[1].Value
Write-WatchLog ("Relaunched as PID {0}." -f $newPid) 'INF'
return $newPid
}
Write-WatchLog "Relaunch did not report a PID." 'WRN'
return 0
}
# -- Main ---------------------------------------------------------------------
$activePid = Resolve-TargetPid
if ($activePid -eq 0) {
Write-WatchLog "No RynthCore-injected acclient found. Launch one first (RynthCore.Injector.exe --launch)." 'ERR'
exit 1
}
$acct = Get-AccountForPid -ProcId $activePid
Write-WatchLog ("Watching PID {0} (account='{1}', relaunch={2}, hold={3}s, interval={4}s)." -f $activePid, $acct, $Relaunch, $WedgeHoldSeconds, $IntervalSeconds)
$state = @{}
$relaunchCount = 0
while ($true) {
$proc = Get-Process -Id $activePid -ErrorAction SilentlyContinue
if (-not $proc) {
Write-WatchLog ("PID {0} is gone." -f $activePid) 'WRN'
if ($Relaunch -and -not $Once -and $acct -and $relaunchCount -lt $MaxRelaunch) {
$relaunchCount++
$newPid = Invoke-Relaunch -DeadPid $activePid -Acct $acct
if ($newPid -ne 0) { $activePid = $newPid; $state = @{}; Start-Sleep -Seconds 10; continue }
}
break
}
$reason = Test-Wedge -ProcId $activePid -State $state
if ($reason) {
[void](Invoke-FreezeCapture -ProcId $activePid -Reason $reason)
$state = @{}
if ($Relaunch -and -not $Once) {
if ($relaunchCount -ge $MaxRelaunch) {
Write-WatchLog ("Hit MaxRelaunch ({0}) - leaving client and stopping." -f $MaxRelaunch) 'ERR'
break
}
$relaunchCount++
$newPid = Invoke-Relaunch -DeadPid $activePid -Acct $acct
if ($newPid -ne 0) { $activePid = $newPid; Start-Sleep -Seconds 10; continue }
break
} else {
Write-WatchLog ("Relaunch disabled - leaving PID {0} frozen for inspection. Stopping." -f $activePid) 'INF'
break
}
}
if ($Once) { Write-WatchLog ("Single pass complete - PID {0} healthy." -f $activePid); break }
Start-Sleep -Seconds $IntervalSeconds
}

100
scripts/Watch-AcMemory.ps1 Normal file
View file

@ -0,0 +1,100 @@
# ============================================================================
# Watch-AcMemory.ps1
#
# Polls acclient.exe's memory + handle metrics on an interval and appends
# them to a CSV under C:\Games\RynthCore\Logs\. Designed for long-running
# 24/7 bot sessions where we want to know:
#
# * is RynthCore (or AC itself) leaking?
# * if yes, how fast (MB/hour)?
# * does growth correlate with subsystem activity (loot on/off, mage cast
# cycles, travel into new cells)?
#
# Zero impact on the running engine — runs in a separate PowerShell host,
# pure OS query, no injection.
#
# Usage:
# .\Watch-AcMemory.ps1 # auto-pick first acclient.exe
# .\Watch-AcMemory.ps1 -Pid 35456 # explicit PID
# .\Watch-AcMemory.ps1 -IntervalSeconds 60 # tighter cadence
# .\Watch-AcMemory.ps1 -OutFile foo.csv # custom output path
#
# Exits when the watched process exits (clean or crash) so it's safe to
# start-and-forget; the CSV stays on disk for post-session analysis.
# ============================================================================
[CmdletBinding()]
param(
[Alias('Pid')]
[int]$TargetPid = 0,
[int]$IntervalSeconds = 300,
[string]$OutFile = $null
)
# Resolve target PID — explicit param wins, else auto-pick the running acclient.
if ($TargetPid -eq 0) {
$candidates = @(Get-Process -Name acclient -ErrorAction SilentlyContinue)
if ($candidates.Count -eq 0) {
Write-Error 'No acclient.exe process found. Pass -TargetPid <id> or launch AC first.'
exit 1
}
if ($candidates.Count -gt 1) {
Write-Warning ("Multiple acclient.exe processes running ({0}). Picking PID {1}; pass -TargetPid to override." -f $candidates.Count, $candidates[0].Id)
}
$TargetPid = $candidates[0].Id
}
# Verify the PID is alive before we commit to a CSV path.
$proc = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue
if (-not $proc) {
Write-Error "No process found with PID $TargetPid."
exit 1
}
# Default output: timestamped per session so successive runs never overwrite.
if (-not $OutFile) {
$logsDir = 'C:\Games\RynthCore\Logs'
if (-not (Test-Path $logsDir)) { New-Item -ItemType Directory -Path $logsDir | Out-Null }
$stamp = (Get-Date -Format 'yyyyMMdd-HHmmss')
$OutFile = Join-Path $logsDir ("acclient-memory-pid{0}-{1}.csv" -f $TargetPid, $stamp)
}
Write-Host "Watching acclient.exe PID $TargetPid"
Write-Host "Interval : $IntervalSeconds seconds"
Write-Host "Output : $OutFile"
Write-Host "Process start: $($proc.StartTime)"
Write-Host ''
# Header. Append-only after this so a Ctrl-C resume preserves prior samples.
'Timestamp,PID,UptimeMinutes,WorkingSetMB,PrivateMB,VirtualMB,HandleCount,ThreadCount' |
Out-File -FilePath $OutFile -Encoding UTF8
$startTime = $proc.StartTime
while ($true) {
$p = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue
if (-not $p) {
Write-Host "PID $TargetPid exited. Final sample written. CSV: $OutFile"
break
}
$now = Get-Date
$uptimeMin = [math]::Round(($now - $startTime).TotalMinutes, 2)
$wsMB = [int]($p.WorkingSet64 / 1MB)
$privMB = [int]($p.PrivateMemorySize64 / 1MB)
$vmMB = [int]($p.VirtualMemorySize64 / 1MB)
$handles = $p.HandleCount
$threads = $p.Threads.Count
$row = "{0},{1},{2},{3},{4},{5},{6},{7}" -f `
$now.ToString('s'), $TargetPid, $uptimeMin, $wsMB, $privMB, $vmMB, $handles, $threads
$row | Out-File -FilePath $OutFile -Append -Encoding UTF8
# Echo to console too so a watching terminal shows live trend.
Write-Host ("[{0}] up={1,7:0.00}min WS={2,5}MB Priv={3,5}MB Handles={4,5} Threads={5,3}" -f `
$now.ToString('HH:mm:ss'), $uptimeMin, $wsMB, $privMB, $handles, $threads)
Start-Sleep -Seconds $IntervalSeconds
}