pnpm/pnpm · error · AggregateError

Failed to clean up replaced global installs

Error message

Failed to clean up replaced global installs

What it means

This `AggregateError` is thrown by `cleanupReplacedGlobalInstalls` after a successful activation when removing the bins and install directories of the previously replaced global package group(s) failed. Activation is already committed, so every removal is attempted and individual failures are collected; if two or more failures accumulate, they are aggregated under this message (a single failure is rethrown as-is). The new install works, but stale shims or old install directories remain on disk.

Solutions

  1. Read the aggregated `errors` array for the concrete per-path failures (EPERM/ENOENT/etc.) and address each.
  2. Close programs or exclusions holding the stale shims, or delete the listed leftovers manually, then rerun the command to let cleanup complete.
  3. Fix ownership/permissions of the global bin dir and global dir (`chown`/`chmod`, avoid mixing sudo and non-sudo installs).
  4. Manually remove stale shims in the global bin dir and the old group install dir printed in the error, since activation has already succeeded.
  5. If a stale snapshot references bins that no longer exist, clean the global state entry for that group.

Example fix

// before: leftover shim locked by a running watcher
$ pnpm add -g eslint
AggregateError: Failed to clean up replaced global installs
// after
$ rm -f "$(pnpm config get global-bin-dir)/eslint"  # after stopping the watcher
$ pnpm add -g eslint
Defensive patterns

Strategy: try-catch

Validate before calling

// Before activating over an old group, verify its shims and install dir are removable
import fs from 'node:fs'
async function isRemovable (p: string): Promise<boolean> {
  try { await fs.promises.access(p, fs.constants.W_OK) } catch { return false }
  return true
}

Type guard

import util from 'node:util'
function isCleanupAggregateError (err: unknown): err is AggregateError {
  return util.types.isNativeError(err) && err instanceof AggregateError &&
    err.message === 'Failed to clean up replaced global installs'
}

Try / catch

try {
  await cleanupReplacedGlobalInstalls(opts)
} catch (err) {
  if (isCleanupAggregateError(err)) {
    for (const e of err.errors) {
      // Log each per-path failure (EPERM/ENOENT/...); activation already succeeded,
      // so only schedule manual cleanup of the named leftovers.
    }
  } else {
    throw err
  }
}

Prevention

When it happens

Trigger: Thrown when, for at least two distinct items across `opts.groups`: `removeBin(globalBinDir/<binName>)` rejects for a non-activated, non-protected bin name, the group's old hash-link `rm` fails, or the group's old `installDir` recursive `rm` fails — and the group whose bin removal failed is intentionally kept until all its bins are gone.

Common situations: A bin shim still held open or locked by a running program or antivirus (EPERM/EBUSY on Windows); a read-only or root-owned global bin dir after a sudo/non-sudo mix; an old install directory containing files created by a different user or mounted volume; a stale snapshot in the global packages state referencing bins that were manually edited.

Understand the failure class

Background: "failed to write file", "Could not save figure", "Error saving remote file" — file write failed: causes and fixes across languages and libraries — this error's family across 38 libraries.

Related errors


AI-assisted analysis of pnpm/pnpm@e45f033222 (2026-09-22). Data as JSON: /api/errors/cb535421cca59ac5. Report an issue: GitHub.

Appendix: source

Thrown at pnpm11/global/commands/src/globalActivation.ts:98

    // Activation is already committed, so a leftover backup directory
    // must not fail the command — but it points at a filesystem problem
    // worth surfacing.
    globalWarn(`Failed to remove the global bin backup directory at ${prepared.backupDir}: ${getErrorMessage(err)}`)
  }
  return prepared.actualBinNames
}

export async function cleanupReplacedGlobalInstalls (
  opts: CleanupReplacedGlobalInstallsOptions
): Promise<void> {
  const errors: unknown[] = []
  for (const group of opts.groups) {
    // eslint-disable-next-line no-await-in-loop -- Cleanup mutations must settle before the next group starts.
    errors.push(...await cleanupReplacedGlobalInstall(opts, group))
  }
  if (errors.length === 1) throw errors[0]
  if (errors.length > 1) {
    throw new AggregateError(errors, 'Failed to clean up replaced global installs')
  }
}

// Activation already succeeded when this runs, so every removal is
// attempted even after one fails; the failures are aggregated instead of
// aborting the remaining cleanup.
async function cleanupReplacedGlobalInstall (
  opts: CleanupReplacedGlobalInstallsOptions,
  groupSnapshot: GlobalPackageBinSnapshot
): Promise<unknown[]> {
  const errors: unknown[] = []
  const { info: group, binNames } = groupSnapshot
  let binRemovalFailed = false
  for (const binName of binNames) {
    if (opts.activatedBins.has(binName) || opts.protectedBins.has(binName)) continue
    try {
      await removeBin(path.join(opts.globalBinDir, binName)) // eslint-disable-line no-await-in-loop -- Each removal must settle before cleanup continues.
    } catch (err) {

View on GitHub (pinned to e45f033222)