pnpm/pnpm · error · AggregateError

Failed to clean up after global bin activation preparation…

Error message

Failed to clean up after global bin activation preparation failed.

What it means

This `AggregateError` is thrown by `prepareGlobalInstall` when preparing a global activation failed and the automatic cleanup of partial artifacts (the backup directory and the fresh install directory) also failed. The original preparation error is included first and attached as `cause`, so the `cause` holds the real reason activation could not be prepared; the aggregated siblings are the cleanup failures. The message indicates the global bin directory may still contain leftover state from the aborted attempt.

Solutions

  1. Inspect `err.errors[0]` / `err.cause` for the original preparation failure and fix that first (permissions, missing bins, unsupported file type).
  2. Remove leftover artifacts manually: delete the `.pnpm-bin-backup-*` directory and the fresh `installDir` under the global dir if the cleanup `rm` failed.
  3. Fix write permissions/ownership on the global bin dir and global dir, then retry the activation.
  4. If a bin slot is a non-file, non-symlink entry (FIFO/device), remove or replace it manually — it can also be what blocked cleanup.
  5. On Windows, close processes locking the install dir (editors, terminals cd'd into it) and retry.

Example fix

// before: unwritable global bin dir breaks prep and its own cleanup
pnpm add -g typescript
// AggregateError: Failed to clean up after global bin activation preparation failed.
// after
sudo chown -R "$(id -u):$(id -g)" "$(pnpm config get global-dir)"
rm -rf "$(pnpm config get global-bin-dir)"/.pnpm-bin-backup-*
pnpm add -g typescript
Defensive patterns

Strategy: try-catch

Validate before calling

// Pre-flight: global dir writable, install dir removable, bin slots are file/symlink
import fs from 'node:fs'
async function canPrepare (globalBinDir: string, installDir: string): Promise<boolean> {
  try {
    await fs.promises.access(globalBinDir, fs.constants.W_OK | fs.constants.X_OK)
    return true
  } catch { return false }
}

Type guard

import util from 'node:util'
function isPrepCleanupAggregate (err: unknown): err is AggregateError & { cause: unknown } {
  return util.types.isNativeError(err) && err instanceof AggregateError &&
    err.message === 'Failed to clean up after global bin activation preparation failed.' &&
    'cause' in err
}

Try / catch

try {
  await activateGlobalInstall(opts)
} catch (err) {
  if (isPrepCleanupAggregate(err)) {
    const rootCause = err.cause // the real preparation failure — fix this first
    // Then remove leftover backupDir (.pnpm-bin-backup-*) and installDir manually.
  } else {
    throw err
  }
}

Prevention

When it happens

Trigger: Thrown when any preparation step fails — `getActualBins` (manifest/filesystem errors), `ensureRequiredBinNames` (GLOBAL_BIN_TARGET_MISSING), `mkdir` of the global bin dir, `mkdtemp` of the backup dir, `backupBinSlots` (including GLOBAL_BIN_UNSUPPORTED_TYPE), or `readHashTarget` — AND at least one of the follow-up `rm` calls (removing `backupDir` when it was created, or recursively removing `opts.installDir`) rejects.

Common situations: A bin slot in the global bin dir is a FIFO/socket/device node (triggers GLOBAL_BIN_UNSUPPORTED_TYPE, then its cleanup `rm` fails on a busy dir); the global bin dir is not writable so both `mkdtemp` and the removals fail; a required bin name is missing (preparation error) while the freshly created install dir is held by a running process and cannot be deleted; ENOSPC or EACCES mid-preparation.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


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

Appendix: source

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

    await fs.promises.mkdir(opts.globalBinDir, { recursive: true })
    backupDir = await fs.promises.mkdtemp(path.join(opts.globalBinDir, '.pnpm-bin-backup-'))
    const savedBinSlots = await backupBinSlots({
      actualBinNames,
      backupDir,
      globalBinDir: opts.globalBinDir,
    })
    const oldHashTarget = await readHashTarget(opts.hashLink)
    return { actualBins, actualBinNames, backupDir, savedBinSlots, oldHashTarget }
  } catch (preparationError) {
    const cleanupResults = await Promise.allSettled([
      ...(backupDir == null ? [] : [fs.promises.rm(backupDir, { recursive: true, force: true })]),
      fs.promises.rm(opts.installDir, { recursive: true, force: true }),
    ])
    const cleanupErrors = cleanupResults.flatMap((result) => {
      return result.status === 'rejected' ? [result.reason] : []
    })
    if (cleanupErrors.length > 0) {
      throw new AggregateError(
        [preparationError, ...cleanupErrors],
        'Failed to clean up after global bin activation preparation failed.',
        { cause: preparationError }
      )
    }
    throw preparationError
  }
}

/**
 * Resolves commands not skipped whose target files exist. Missing targets are
 * omitted, while package-manifest resolution and filesystem errors propagate.
 */
async function getActualBins (
  opts: Pick<ActivateGlobalInstallOptions, 'pkgs' | 'binsToSkip'>
): Promise<Map<string, string>> {
  const actualBins = new Map<string, string>()
  const bins = await getBinsToLink(opts.pkgs, opts.binsToSkip)

View on GitHub (pinned to e45f033222)