{"record":{"id":"477dafcb5aa32b21","repo":"pnpm/pnpm","slug":"failed-to-clean-up-after-global-bin-activation-pre","errorCode":null,"errorMessage":"Failed to clean up after global bin activation preparation failed.","messagePattern":"Failed to clean up after global bin activation preparation failed\\.","errorType":"exception","errorClass":"AggregateError","httpStatus":null,"severity":"error","filePath":"pnpm11/global/commands/src/globalActivation.ts","lineNumber":209,"sourceCode":"    await fs.promises.mkdir(opts.globalBinDir, { recursive: true })\n    backupDir = await fs.promises.mkdtemp(path.join(opts.globalBinDir, '.pnpm-bin-backup-'))\n    const savedBinSlots = await backupBinSlots({\n      actualBinNames,\n      backupDir,\n      globalBinDir: opts.globalBinDir,\n    })\n    const oldHashTarget = await readHashTarget(opts.hashLink)\n    return { actualBins, actualBinNames, backupDir, savedBinSlots, oldHashTarget }\n  } catch (preparationError) {\n    const cleanupResults = await Promise.allSettled([\n      ...(backupDir == null ? [] : [fs.promises.rm(backupDir, { recursive: true, force: true })]),\n      fs.promises.rm(opts.installDir, { recursive: true, force: true }),\n    ])\n    const cleanupErrors = cleanupResults.flatMap((result) => {\n      return result.status === 'rejected' ? [result.reason] : []\n    })\n    if (cleanupErrors.length > 0) {\n      throw new AggregateError(\n        [preparationError, ...cleanupErrors],\n        'Failed to clean up after global bin activation preparation failed.',\n        { cause: preparationError }\n      )\n    }\n    throw preparationError\n  }\n}\n\n/**\n * Resolves commands not skipped whose target files exist. Missing targets are\n * omitted, while package-manifest resolution and filesystem errors propagate.\n */\nasync function getActualBins (\n  opts: Pick<ActivateGlobalInstallOptions, 'pkgs' | 'binsToSkip'>\n): Promise<Map<string, string>> {\n  const actualBins = new Map<string, string>()\n  const bins = await getBinsToLink(opts.pkgs, opts.binsToSkip)","sourceCodeStart":191,"sourceCodeEnd":227,"githubUrl":"https://github.com/pnpm/pnpm/blob/e45f0332229b094d61f2ecad114a166e338c0d61/pnpm11/global/commands/src/globalActivation.ts#L191-L227","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Inspect `err.errors[0]` / `err.cause` for the original preparation failure and fix that first (permissions, missing bins, unsupported file type).","Remove leftover artifacts manually: delete the `.pnpm-bin-backup-*` directory and the fresh `installDir` under the global dir if the cleanup `rm` failed.","Fix write permissions/ownership on the global bin dir and global dir, then retry the activation.","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.","On Windows, close processes locking the install dir (editors, terminals cd'd into it) and retry."],"exampleFix":"// before: unwritable global bin dir breaks prep and its own cleanup\npnpm add -g typescript\n// AggregateError: Failed to clean up after global bin activation preparation failed.\n// after\nsudo chown -R \"$(id -u):$(id -g)\" \"$(pnpm config get global-dir)\"\nrm -rf \"$(pnpm config get global-bin-dir)\"/.pnpm-bin-backup-*\npnpm add -g typescript","handlingStrategy":"try-catch","validationCode":"// Pre-flight: global dir writable, install dir removable, bin slots are file/symlink\nimport fs from 'node:fs'\nasync function canPrepare (globalBinDir: string, installDir: string): Promise<boolean> {\n  try {\n    await fs.promises.access(globalBinDir, fs.constants.W_OK | fs.constants.X_OK)\n    return true\n  } catch { return false }\n}","typeGuard":"import util from 'node:util'\nfunction isPrepCleanupAggregate (err: unknown): err is AggregateError & { cause: unknown } {\n  return util.types.isNativeError(err) && err instanceof AggregateError &&\n    err.message === 'Failed to clean up after global bin activation preparation failed.' &&\n    'cause' in err\n}","tryCatchPattern":"try {\n  await activateGlobalInstall(opts)\n} catch (err) {\n  if (isPrepCleanupAggregate(err)) {\n    const rootCause = err.cause // the real preparation failure — fix this first\n    // Then remove leftover backupDir (.pnpm-bin-backup-*) and installDir manually.\n  } else {\n    throw err\n  }\n}","preventionTips":["Verify the global bin dir is writable by the current user before installing globally.","Ensure no directory, FIFO, or device occupies a bin slot name in the global bin dir.","Avoid processes (terminals, editors, watchers) holding the fresh installDir open during activation.","Clean leftover .pnpm-bin-backup-* directories after any failed activation before retrying.","Read err.cause / err.errors[0] first — the cleanup errors are secondary to the preparation failure."],"tags":["global-install","cleanup","aggregate-error","filesystem"],"backgroundTag":"invalid-state-transition","analyzedSha":"e45f0332229b094d61f2ecad114a166e338c0d61","analyzedAt":"2026-09-22T05:07:20.233Z","contentChangedAt":"2026-09-22T05:07:20.233Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}