Skip to content

The agent that grows with you

fix(desktop): reap install-rooted stragglers so MSIX can launch again

ethernet6caa15b8b25a
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 08b83f9f930..7117a496144 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -272,6 +272,7 @@ import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'
import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'
import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity'
import { adoptPayloadVenv, installIdForRoot, isBundledInstall, resolvePayload, type PayloadInfo } from './payload-backend'
+import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap'
import { PLACEHOLDER_FEED_BASE_URL } from './app-updater'
import { AppInstallerStrategy } from './updater/app-installer'
import { ExternalStrategy } from './updater/external'
@@ -12457,6 +12458,58 @@ function stopAllPoolBackends() {
return poolStopper.stopAll()
}
+/**
+ * Last teardown act on Windows: kill anything still running out of THIS
+ * install's roots, so no straggler holds an image open.
+ *
+ * Two roots, because two install shapes have the same daemon problem:
+ *
+ * - The artifact resources dir (bundled/MSIX). A live process rooted in the
+ * package family pins the family's container silo, and every later
+ * activation then fails the job → silo conversion with 0x80070020 — the app
+ * never launches again. Live cause on windows-11-arm was the payload's
+ * bundled-git gpg-agent, which daemonizes out of our process tree and so is
+ * unreachable by taskkill /T.
+ * - The managed tool store (mutable install.ps1 / install.sh checkout), where
+ * pm stages node, git and uv. A daemonized tool there keeps its own image
+ * open, and Windows cannot overwrite a running image — so the next
+ * `hermes update` fails to replace exactly those files.
+ *
+ * HERMES_RUNTIME_DIR is the store when pm is aimed at one (a bundled payload
+ * aims it at its own, where the roots overlap harmlessly); otherwise the store
+ * is <hermes root>/tools, mirroring pm.paths.store_root().
+ *
+ * Runs AFTER the graceful backend teardown and skips the pids it owned, so
+ * this is only the net for what detached. Best effort throughout: quit must
+ * never hang or fail on it. See package-process-reap.ts for the evidence.
+ */
+function reapInstallRootedStragglers(excludePids: number[]): void {
+ if (!IS_WINDOWS) {
+ return
+ }
+
+ const payloadRoot = isBundledInstall(process.resourcesPath, { fileExists }) ? process.resourcesPath : null
+ // HERMES_HOME is already root-normalized by resolveHermesHome().
+ const managedStore = process.env.HERMES_RUNTIME_DIR || path.join(HERMES_HOME, 'tools')
+
+ try {
+ reapPackageRootedProcesses({
+ installRoots: [payloadRoot, managedStore],
+ listProcesses: () => listWindowsProcesses((file, args, options) => execFileSync(file, args, {
+ ...hiddenWindowsChildOptions({ encoding: 'utf8', timeout: options.timeout }),
+ windowsHide: options.windowsHide
+ }) as unknown as string),
+ killProcess: pid => process.kill(pid, 'SIGKILL'),
+ selfPid: process.pid,
+ excludePids,
+ isWindows: true,
+ log: message => rememberLog(message)
+ })
+ } catch (err) {
+ rememberLog(`[package-reap] skipped: ${(err as Error).message}`)
+ }
+}
+
const backendShutdown = createBackendShutdownCoordinator(async () => {
const primary = backendConnectionState.invalidate()
@@ -12469,6 +12522,8 @@ const backendShutdown = createBackendShutdownCoordinator(async () => {
}
await Promise.all([waitForBackendExit(primary), pooledStops])
+
+ reapInstallRootedStragglers(Number.isInteger(primary?.pid) ? [primary.pid] : [])
})
async function exitAfterBackendShutdown(code) {
diff --git a/apps/desktop/electron/package-process-reap.test.ts b/apps/desktop/electron/package-process-reap.test.ts
new file mode 100644
index 00000000000..e4afe552773
--- /dev/null
+++ b/apps/desktop/electron/package-process-reap.test.ts
@@ -0,0 +1,289 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import {
+ isUnderInstallRoot,
+ listWindowsProcesses,
+ reapPackageRootedProcesses,
+ type RunningProcess
+} from './package-process-reap'
+
+const ROOT = 'C:\\Program Files\\WindowsApps\\NousResearch.HermesBundled_0.21.20.25635_arm64__e60prshbsznhj'
+
+/** A mutable install's managed tool store: HERMES_RUNTIME_DIR / <root>\tools. */
+const TOOLS_ROOT = 'C:\\Users\\arilo\\AppData\\Local\\hermes\\tools'
+
+/** The live-observed pinner: payload git's gpg-agent, daemonized out of our tree. */
+const GPG_AGENT = `${ROOT}\\app\\resources\\agent-payload\\tools\\git-2.53.0+3-win32-arm64\\usr\\bin\\gpg-agent.exe`
+const PAYLOAD_PYTHON = `${ROOT}\\app\\resources\\agent-payload\\tools\\python-3.11.16+20260814-win32-arm64\\python.exe`
+const MAIN_EXE = `${ROOT}\\app\\Hermes.exe`
+
+/** Same class, mutable install: pm-staged node holding its own image open. */
+const STORE_NODE = `${TOOLS_ROOT}\\node-26.7.0-win32-arm64\\node.exe`
+
+function reap(processes: RunningProcess[], overrides: Record<string, unknown> = {}) {
+ const killProcess = vi.fn()
+
+ const outcome = reapPackageRootedProcesses({
+ installRoots: [ROOT],
+ listProcesses: () => processes,
+ killProcess,
+ selfPid: 1,
+ isWindows: true,
+ ...overrides
+ })
+
+ return { outcome, killProcess }
+}
+
+describe('isUnderInstallRoot', () => {
+ it('matches an image nested under the root regardless of case or separator', () => {
+ expect(isUnderInstallRoot(GPG_AGENT, ROOT)).toBe(true)
+ expect(isUnderInstallRoot(GPG_AGENT.toUpperCase(), ROOT)).toBe(true)
+ expect(isUnderInstallRoot(GPG_AGENT.replace(/\\/g, '/'), ROOT)).toBe(true)
+ expect(isUnderInstallRoot(MAIN_EXE, `${ROOT}\\`)).toBe(true)
+ })
+
+ it('does NOT match a sibling package whose name merely shares the prefix', () => {
+ // A bare startsWith would kill another package's processes here. The
+ // separator check is the whole guard.
+ const sibling =
+ 'C:\\Program Files\\WindowsApps\\NousResearch.HermesBundled_0.21.20.256350_arm64__e60prshbsznhj\\app\\Hermes.exe'
+
+ expect(isUnderInstallRoot(sibling, ROOT)).toBe(false)
+ })
+
+ it('does not match another vendor, an unreadable path, or an empty root', () => {
+ const other = 'C:\\Program Files\\WindowsApps\\8bitSolutionsLLC.bitwardendesktop_2026.7.0.0_arm64__x\\app\\Bitwarden.exe'
+
+ expect(isUnderInstallRoot(other, ROOT)).toBe(false)
+ expect(isUnderInstallRoot(null, ROOT)).toBe(false)
+ expect(isUnderInstallRoot(MAIN_EXE, null)).toBe(false)
+ expect(isUnderInstallRoot(MAIN_EXE, '')).toBe(false)
+ expect(isUnderInstallRoot(MAIN_EXE, [])).toBe(false)
+ })
+
+ it('matches under ANY supplied root, so both install shapes are covered', () => {
+ // Bundled artifact resources AND a mutable install's managed tool store.
+ const roots = [ROOT, TOOLS_ROOT]
+
+ expect(isUnderInstallRoot(GPG_AGENT, roots)).toBe(true)
+ expect(isUnderInstallRoot(STORE_NODE, roots)).toBe(true)
+ expect(isUnderInstallRoot('C:\\Windows\\System32\\node.exe', roots)).toBe(false)
+ })
+
+ it('skips nullish roots instead of matching everything', () => {
+ // A bootstrap install has no resourcesPath payload: the artifact root is
+ // absent and only the tool store is real. An absent root must never widen
+ // the predicate.
+ expect(isUnderInstallRoot(STORE_NODE, [null, TOOLS_ROOT])).toBe(true)
+ expect(isUnderInstallRoot('C:\\Windows\\System32\\node.exe', [null, undefined, ''])).toBe(false)
+ })
+})
+
+describe('reapPackageRootedProcesses', () => {
+ it('kills a detached package-rooted daemon that a tree-kill cannot reach', () => {
+ // The regression: gpg-agent reparented away from us, so it is in no tree we
+ // own. Path scoping is what catches it.
+ const { outcome, killProcess } = reap([{ pid: 48236, path: GPG_AGENT }])
+
+ expect(outcome.matched).toBe(1)
+ expect(outcome.killed).toEqual([48236])
+ expect(killProcess).toHaveBeenCalledWith(48236)
+ })
+
+ it('reaps every package-rooted process, whatever the image name', () => {
+ const { outcome } = reap([
+ { pid: 10, path: MAIN_EXE },
+ { pid: 11, path: PAYLOAD_PYTHON },
+ { pid: 12, path: GPG_AGENT }
+ ])
+
+ expect(outcome.matched).toBe(3)
+ expect(outcome.killed).toEqual([10, 11, 12])
+ })
+
+ it('never kills processes outside the install root', () => {
+ const { outcome, killProcess } = reap([
+ { pid: 20, path: 'C:\\Program Files\\Git\\usr\\bin\\gpg-agent.exe' },
+ { pid: 21, path: 'C:\\Users\\arilo\\AppData\\Local\\Programs\\HermesBundled\\app\\Hermes.exe' },
+ { pid: 22, path: GPG_AGENT }
+ ])
+
+ // The user's OWN gpg-agent is exactly what a GNUPGHOME-scoped
+ // `gpgconf --kill all` would have taken out. Path scoping leaves it alone.
+ expect(outcome.killed).toEqual([22])
+ expect(killProcess).not.toHaveBeenCalledWith(20)
+ expect(killProcess).not.toHaveBeenCalledWith(21)
+ })
+
+ it('reaps a mutable install: pm-staged tooling under the managed store', () => {
+ // No MSIX here. A daemonized node/git under <hermes root>\tools keeps its
+ // image open, and on Windows a running image cannot be overwritten — so
+ // the next `hermes update` fails to replace exactly those files.
+ const { outcome, killProcess } = reap(
+ [
+ { pid: 70, path: STORE_NODE },
+ { pid: 71, path: `${TOOLS_ROOT}\\git-2.53.0+3-win32-arm64\\usr\\bin\\gpg-agent.exe` },
+ { pid: 72, path: 'C:\\Windows\\System32\\node.exe' }
+ ],
+ { installRoots: [null, TOOLS_ROOT] }
+ )
+
+ expect(outcome.killed).toEqual([70, 71])
+ expect(killProcess).not.toHaveBeenCalledWith(72)
+ })
+
+ it('reaps both roots in one pass when an install has both', () => {
+ const { outcome } = reap(
+ [
+ { pid: 80, path: GPG_AGENT },
+ { pid: 81, path: STORE_NODE }
+ ],
+ { installRoots: [ROOT, TOOLS_ROOT] }
+ )
+
+ expect(outcome.matched).toBe(2)
+ expect(outcome.killed).toEqual([80, 81])
+ })
+
+ it('never kills itself', () => {
+ const { outcome, killProcess } = reap([{ pid: 99, path: MAIN_EXE }], { selfPid: 99 })
+
+ expect(outcome.matched).toBe(0)
+ expect(killProcess).not.toHaveBeenCalled()
+ })
+
+ it('skips pids the graceful backend teardown already owns', () => {
+ const { outcome } = reap([
+ { pid: 30, path: MAIN_EXE },
+ { pid: 31, path: PAYLOAD_PYTHON }
+ ], { excludePids: [30] })
+
+ expect(outcome.killed).toEqual([31])
+ })
+
+ it('leaves a process whose path cannot be read alone', () => {
+ // Missing one pinner reproduces a bug we already have; killing an
+ // unidentified process is unbounded damage.
+ const { outcome, killProcess } = reap([{ pid: 40, path: null }])
+
+ expect(outcome.matched).toBe(0)
+ expect(killProcess).not.toHaveBeenCalled()
+ })
+
+ it('keeps going when one kill throws, and reports it', () => {
+ const killProcess = vi.fn((pid: number) => {
+ if (pid === 50) {
+ throw new Error('Access is denied')
+ }
+ })
+
+ const outcome = reapPackageRootedProcesses({
+ installRoots: [ROOT],
+ listProcesses: () => [
+ { pid: 50, path: MAIN_EXE },
+ { pid: 51, path: GPG_AGENT }
+ ],
+ killProcess,
+ selfPid: 1,
+ isWindows: true
+ })
+
+ expect(outcome.failed).toEqual([50])
+ expect(outcome.killed).toEqual([51])
+ })
+
+ it('never lets a failed enumeration break quit', () => {
+ const outcome = reapPackageRootedProcesses({
+ installRoots: [ROOT],
+ listProcesses: () => {
+ throw new Error('enumeration failed')
+ },
+ killProcess: vi.fn(),
+ selfPid: 1,
+ isWindows: true
+ })
+
+ expect(outcome.skipped).toBe(true)
+ expect(outcome.killed).toEqual([])
+ })
+
+ it('is a no-op on POSIX and when no install root resolves', () => {
+ const killProcess = vi.fn()
+
+ const posix = reapPackageRootedProcesses({
+ installRoots: [ROOT],
+ listProcesses: () => [{ pid: 60, path: MAIN_EXE }],
+ killProcess,
+ selfPid: 1,
+ isWindows: false
+ })
+
+ const rootless = reapPackageRootedProcesses({
+ installRoots: [null, ''],
+ listProcesses: () => [{ pid: 61, path: MAIN_EXE }],
+ killProcess,
+ selfPid: 1,
+ isWindows: true
+ })
+
+ expect(posix.skipped).toBe(true)
+ expect(rootless.skipped).toBe(true)
+ expect(killProcess).not.toHaveBeenCalled()
+ })
+})
+
+describe('listWindowsProcesses', () => {
+ it('parses Get-Process output, mapping an unreadable path to null', () => {
+ // The real shape: `.Path` throws for processes we cannot open, so the
+ // script emits an empty tail for those.
+ const stdout = [
+ `48236|${GPG_AGENT}`,
+ `22660|${MAIN_EXE}`,
+ '4|',
+ ''
+ ].join('\r\n')
+
+ const parsed = listWindowsProcesses(() => stdout)
+
+ expect(parsed).toEqual([
+ { pid: 48236, path: GPG_AGENT },
+ { pid: 22660, path: MAIN_EXE },
+ { pid: 4, path: null }
+ ])
+ })
+
+ it('keeps paths that contain spaces intact', () => {
+ // "C:\Program Files\..." — splitting on the FIRST separator is what
+ // preserves the rest of the path.
+ const parsed = listWindowsProcesses(() => `10|${MAIN_EXE}`)
+
+ expect(parsed[0].path).toBe(MAIN_EXE)
+ })
+
+ it('ignores malformed lines instead of inventing pids', () => {
+ const parsed = listWindowsProcesses(() => ['garbage', '|no-pid', 'abc|path', ''].join('\n'))
+
+ expect(parsed).toEqual([])
+ })
+
+ it('runs hidden and bounded so it cannot stall or flash a console on quit', () => {
+ const calls: Array<{ file: string; options: { timeout: number; windowsHide: boolean } }> = []
+
+ const execFile = (
+ file: string,
+ _args: string[],
+ options: { timeout: number; windowsHide: boolean }
+ ): string => {
+ calls.push({ file, options })
+
+ return ''
+ }
+
+ listWindowsProcesses(execFile)
+
+ expect(calls[0].file).toBe('powershell.exe')
+ expect(calls[0].options.windowsHide).toBe(true)
+ expect(calls[0].options.timeout).toBeGreaterThan(0)
+ })
+})
diff --git a/apps/desktop/electron/package-process-reap.ts b/apps/desktop/electron/package-process-reap.ts
new file mode 100644
index 00000000000..5633686b8d3
--- /dev/null
+++ b/apps/desktop/electron/package-process-reap.ts
@@ -0,0 +1,278 @@
+/**
+ * package-process-reap.ts
+ *
+ * Reap every process still running out of our MSIX package root at shutdown.
+ *
+ * Why this exists. A Desktop-Bridge (Centennial) MSIX package activates inside
+ * a Desktop AppX container: Windows creates a Job Object for the package family
+ * and converts it to a silo. One live process rooted in the family pins that
+ * silo. While it is pinned, EVERY later activation of the family fails at the
+ * conversion step:
+ *
+ * AppModel-Runtime/Admin
+ * [215] 0x80070020: Cannot create the Desktop AppX container for package
+ * <full name> because an error was encountered converting the job.
+ * [208] 0x80070020: Cannot create the process for package <full name>
+ * because an error was encountered while configuring runtime.
+ * [LaunchProcess]
+ *
+ * 0x80070020 is ERROR_SHARING_VIOLATION, which Windows surfaces to the user as
+ * "The process cannot access the file because it is being used by another
+ * process" — a file-lock message for what is really a container-layer failure.
+ *
+ * Observed live on windows-11-arm: the payload's own bundled-git gpg-agent.exe
+ * (under tools/git-<version>/usr/bin/) had daemonized, outlived its package by
+ * a week, and pinned the family. Killing that ONE pid turned [215]/[208] into
+ * [210] Created / [211] Added on the very next activation, with nothing else
+ * changed.
+ *
+ * Why the platform does not save us. Deployment already asks for the shutdown
+ * (ForceApplicationShutdownOption + ForceTargetApplicationShutdownOption) and
+ * it still missed the daemon; the old package folder then failed to move with
+ * `0x80070005` and Windows logged `[503] The file system entries ... could not
+ * be cleaned up after reboot. The package is removed from the purge list.`
+ * Once that happens not even a reboot clears it. Our daemon defeated the
+ * platform's own mechanism, so the reap is ours to do.
+ *
+ * Why not a process-TREE kill. `taskkill /T` walks parentage, and a daemon that
+ * detaches is by construction no longer in our tree — that is what daemonizing
+ * means. Tree scoping is the actual bug. Install-root scoping is what matches
+ * the silo: the pin is "a process whose image lives under this package", so
+ * that is exactly the predicate to kill on.
+ *
+ * Why not a gpg-specific kill. `gpgconf --kill all` is scoped by GNUPGHOME, not
+ * by install root, so it can reach the user's OWN gpg-agent outside our package
+ * — real collateral harm for a case the generic path reap already covers. One
+ * mechanism, no per-daemon special cases: any future payload tool that
+ * daemonizes is caught with no new code.
+ *
+ * Scoping. Two roots hold binaries this install owns, and either can hold the
+ * straggler:
+ *
+ * 1. The artifact itself — resources/ on a bundled/MSIX install, which
+ * contains agent-payload (repo + venv + its own tool store).
+ * 2. The per-install managed tool store — where pm stages node, git, uv,
+ * ripgrep and friends for a MUTABLE install (an install.ps1 / install.sh
+ * checkout). That is HERMES_RUNTIME_DIR when set, else <hermes root>/tools.
+ * A bundled payload sets HERMES_RUNTIME_DIR at its own store, so the two
+ * roots coincide there and the overlap is harmless.
+ *
+ * A mutable install has exactly the same daemon problem with none of the MSIX
+ * framing: node tooling, a language server, or bundled git's gpg-agent under
+ * <hermes root>/tools keeps running and holds an open handle on the very files
+ * the next `hermes update` wants to replace. On Windows a running image cannot
+ * be overwritten, which is the same 0x80070020 the user reads as "used by
+ * another process". Reaping both roots covers both install shapes with one
+ * predicate.
+ *
+ * The roots are deliberately the CURRENT install's, not the package family or
+ * every Hermes on the box: once this ships, each shutdown reaps its own
+ * processes, so no install leaves a daemon behind. Cleaning up a straggler
+ * that a PREVIOUS version already leaked needs a repair path outside the
+ * install (the app cannot launch to clean up after itself) and is tracked
+ * separately.
+ *
+ * Live-verified on windows-11-arm at Medium Mandatory Level (admin=False, the
+ * integrity level the app actually runs at): all 6 package-rooted processes
+ * enumerated, all killed, 0 remaining, 0 with an unreadable path — then the
+ * next activation logged [210]/[211] and the app came up clean.
+ *
+ * Pure module: no electron import, no process globals reached directly, every
+ * dependency injected — so the predicate and the ordering are asserted against
+ * the real function rather than by grepping main.ts.
+ */
+
+/** One running process, reduced to what the reap decision needs. */
+export interface RunningProcess {
+ pid: number
+ /**
+ * Absolute path of the process image, or null when it cannot be read.
+ * A path we cannot read is never a match — see reapPackageRootedProcesses.
+ */
+ path: string | null
+}
+
+export interface ReapPackageRootedProcessesDeps {
+ /**
+ * Absolute roots to scope on: the artifact resources dir and/or the managed
+ * tool store. Empty/nullish entries are ignored, and an empty list disables
+ * the reap entirely.
+ */
+ installRoots: ReadonlyArray<string | null | undefined>
+ /** Snapshot of running processes. Real: enumerate with readable image paths. */
+ listProcesses: () => RunningProcess[]
+ /** Force-kill one pid. Real: process.kill(pid, 'SIGKILL') / taskkill /F. */
+ killProcess: (pid: number) => void
+ /** Our own pid, never reaped — we are rooted in the package too. */
+ selfPid: number
+ /**
+ * Pids already being torn down by the normal backend path. Skipped so the
+ * graceful teardown owns them and this stays a net for what it missed.
+ */
+ excludePids?: Iterable<number>
+ /** Defaults to the real platform check; injectable for tests. */
+ isWindows?: boolean
+ /** Optional diagnostic sink; failures must never break quit. */
+ log?: (message: string) => void
+}
+
+export interface ReapOutcome {
+ /** Package-rooted processes found (excluding self and excludePids). */
+ matched: number
+ /** Pids the kill call was made for. */
+ killed: number[]
+ /** Pids whose kill threw (already gone, or not permitted). */
+ failed: number[]
+ /** True when the reap did not run (non-Windows, or no install root). */
+ skipped: boolean
+}
+
+/**
+ * Enumerate running processes with their image paths, via PowerShell's
+ * Get-Process.
+ *
+ * Live-verified at Medium Mandatory Level (admin=False): all package-rooted
+ * processes were enumerated with readable paths and killed, so this needs no
+ * elevation and no WMI. `.Path` throws for processes the caller cannot open,
+ * which is why each read is guarded and reported as a null path rather than
+ * aborting the sweep.
+ *
+ * Bounded and best effort: this runs on the quit path, so it takes a hard
+ * timeout and returns an empty list rather than delaying shutdown.
+ */
+export function listWindowsProcesses(
+ execFile: (file: string, args: string[], options: { timeout: number; windowsHide: boolean }) => string
+): RunningProcess[] {
+ const script =
+ '$ErrorActionPreference = "SilentlyContinue"; ' +
+ 'Get-Process | ForEach-Object { ' +
+ '$p = $null; try { $p = $_.Path } catch { $p = $null }; ' +
+ '"{0}|{1}" -f $_.Id, $p }'
+
+ const stdout = execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
+ timeout: 10_000,
+ windowsHide: true
+ })
+
+ const processes: RunningProcess[] = []
+
+ for (const line of String(stdout).split(/\r?\n/)) {
+ const separator = line.indexOf('|')
+
+ if (separator <= 0) {
+ continue
+ }
+
+ const pid = Number.parseInt(line.slice(0, separator), 10)
+
+ if (!Number.isInteger(pid)) {
+ continue
+ }
+
+ const imagePath = line.slice(separator + 1).trim()
+ processes.push({ pid, path: imagePath === '' ? null : imagePath })
+ }
+
+ return processes
+}
+
+/**
+ * True when `imagePath` lives under any of `roots`.
+ *
+ * Windows paths are case-insensitive, so the compare is too. The separator
+ * check is what keeps the prefix honest: a bare startsWith would match a
+ * sibling directory whose name merely begins with a root
+ * (`...\HermesBundled_0.21` vs `...\HermesBundled_0.21.20`), and killing
+ * another package's processes is a far worse bug than the one being fixed.
+ */
+export function isUnderInstallRoot(
+ imagePath: string | null | undefined,
+ roots: ReadonlyArray<string | null | undefined> | string | null | undefined
+): boolean {
+ if (!imagePath) {
+ return false
+ }
+
+ const normalize = (value: string): string => value.replace(/[\\/]+$/, '').replace(/\//g, '\\').toLowerCase()
+ const normalizedPath = normalize(imagePath)
+ const candidates = typeof roots === 'string' || roots == null ? [roots] : roots
+
+ for (const root of candidates) {
+ if (!root) {
+ continue
+ }
+
+ const normalizedRoot = normalize(root)
+
+ if (!normalizedRoot) {
+ continue
+ }
+
+ if (normalizedPath === normalizedRoot || normalizedPath.startsWith(`${normalizedRoot}\\`)) {
+ return true
+ }
+ }
+
+ return false
+}
+
+/**
+ * Kill every process whose image lives under the install root.
+ *
+ * Best effort by construction: this runs on the quit path, so a failure to
+ * enumerate or to kill is logged and swallowed rather than allowed to hang or
+ * crash the shutdown. A process whose path cannot be read is left alone — the
+ * cost of missing one pinner is the bug we already have, while killing a
+ * process we could not identify is unbounded damage.
+ */
+export function reapPackageRootedProcesses(deps: ReapPackageRootedProcessesDeps): ReapOutcome {
+ const isWindows = deps.isWindows ?? process.platform === 'win32'
+ const log = deps.log ?? ((): void => undefined)
+ const roots = (deps.installRoots ?? []).filter((root): root is string => Boolean(root))
+
+ // The container silo is a Windows construct; POSIX has nothing to reap.
+ if (!isWindows || roots.length === 0) {
+ return { matched: 0, killed: [], failed: [], skipped: true }
+ }
+
+ let running: RunningProcess[]
+
+ try {
+ running = deps.listProcesses()
+ } catch (err) {
+ log(`[package-reap] process enumeration failed: ${(err as Error).message}`)
+
+ return { matched: 0, killed: [], failed: [], skipped: true }
+ }
+
+ const excluded = new Set<number>(deps.excludePids ?? [])
+ const killed: number[] = []
+ const failed: number[] = []
+ let matched = 0
+
+ for (const candidate of running) {
+ if (!Number.isInteger(candidate.pid) || candidate.pid === deps.selfPid || excluded.has(candidate.pid)) {
+ continue
+ }
+
+ if (!isUnderInstallRoot(candidate.path, roots)) {
+ continue
+ }
+
+ matched += 1
+
+ try {
+ deps.killProcess(candidate.pid)
+ killed.push(candidate.pid)
+ } catch (err) {
+ failed.push(candidate.pid)
+ log(`[package-reap] kill pid=${candidate.pid} failed: ${(err as Error).message}`)
+ }
+ }
+
+ if (matched > 0) {
+ log(`[package-reap] matched=${matched} killed=${killed.length} failed=${failed.length}`)
+ }
+
+ return { matched, killed, failed, skipped: false }
+}