Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): don't let a stray lockfile decide the package manager (#5301)

Joeyf44484842530
diff --git a/.changeset/fix-package-manager-detection-multiple-lockfiles.md b/.changeset/fix-package-manager-detection-multiple-lockfiles.md
new file mode 100644
index 0000000000..02c4f12415
--- /dev/null
+++ b/.changeset/fix-package-manager-detection-multiple-lockfiles.md
@@ -0,0 +1,38 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Package-manager detection: don't let a stray lockfile decide
+
+`detectPackageManager` checked lockfiles in a fixed order and returned the
+first hit, so a directory holding more than one lockfile was resolved by array
+position. `yarn.lock` is first in that array, which means a single
+`yarn install` inside a pnpm project silently switches the CLI's answer to yarn
+— permanently, because the stray lockfile stays on disk.
+
+Every command the CLI prints is then wrong, including the invocation line
+written into the agent-docs block, which agents copy verbatim into their own
+runs.
+
+A single lockfile still outranks everything else in its directory, unchanged.
+When several sit in one directory the tie is broken only from evidence the
+project owns: the declared `packageManager` field, then a committed
+package-manager config file (`pnpm-workspace.yaml`, `.yarnrc.yml`,
+`bunfig.toml`). A stray `install` drops a lockfile; it writes none of those.
+
+The runner (`npm_config_user_agent`) deliberately does NOT break that tie. An
+agent handed the wrong `yarn astryx` line runs the CLI through yarn, so the
+runner agrees with the mistake and regenerating agent docs writes the wrong
+line again — the failure reproduces itself. The same holds for an installed
+binary invoked from that shell. Both now have regressions that start from the
+wrong line.
+
+When nothing project-owned decides it, the CLI does not guess.
+`detectPackageManager` returns the neutral `npx`, which is correct under every
+package manager, and the new `explainPackageManager` reports `ambiguous` with
+the tied candidates. `astryx doctor` turns that into a FAIL naming the
+directory and the fix — add a `packageManager` field, or delete the lockfile
+that does not belong. It is the refusal `findConfigPath` already makes for
+coexisting config files.
+
+@josephfarina
diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjs
index 897bb9c377..845d08a520 100644
--- a/packages/cli/api/doctor/doctor.mjs
+++ b/packages/cli/api/doctor/doctor.mjs
@@ -26,7 +26,7 @@ import {createRequire} from 'node:module';
import {MIN_NODE_VERSION, isNodeVersionSupported} from '../../foundation/env/node-version.mjs';
import {CLI_ROOT, findCoreDir} from '../../foundation/fs/paths.mjs';
-import {detectPackageManager, getCliInvocation} from '../../foundation/env/package-manager.mjs';
+import {explainPackageManager, getCliInvocation} from '../../foundation/env/package-manager.mjs';
import {findConfigPath, Project} from '../../foundation/config/project.mjs';
import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/env/semver.mjs';
@@ -495,20 +495,34 @@ export function checkPeerDeps(ctx) {
}
/**
- * Check 8 — report the detected package manager (informational).
+ * Check 8 — report the detected package manager, and FAIL when several
+ * lockfiles tie with nothing project-owned to break them. That tie is the one
+ * case where every command the CLI prints can be silently wrong, so it is the
+ * one case worth surfacing rather than guessing past.
* @param {DoctorContext} ctx
* @returns {DoctorCheck}
*/
export function checkPackageManager(ctx) {
- const pm = detectPackageManager(ctx.cwd);
- const detected = pm !== 'npx';
+ const {pm, ambiguous, dir, candidates} = explainPackageManager(ctx.cwd);
+
+ if (ambiguous) {
+ return {
+ id: 'package-manager',
+ label: 'Package manager',
+ status: 'fail',
+ message: `Cannot tell which package manager this project uses: ${candidates.join(' and ')} lockfiles both sit in ${dir}, and nothing the project owns picks between them. Commands are printed with the neutral \`npx\` form until this is resolved.`,
+ fix: `Add a \`packageManager\` field to ${dir}/package.json, or delete the lockfile that does not belong.`,
+ };
+ }
+
return {
id: 'package-manager',
label: 'Package manager',
status: 'info',
- message: detected
- ? `Detected package manager: ${pm}.`
- : 'No lockfile detected — defaulting to npm/npx.',
+ message:
+ pm !== 'npx'
+ ? `Detected package manager: ${pm}.`
+ : 'No lockfile detected — defaulting to npm/npx.',
};
}
diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjs
index 1ddb1a3f66..3d455a4463 100644
--- a/packages/cli/api/doctor/doctor.test.mjs
+++ b/packages/cli/api/doctor/doctor.test.mjs
@@ -11,7 +11,7 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
-import {doctor, checkVersionAlignment} from './doctor.mjs';
+import {doctor, checkVersionAlignment, checkPackageManager} from './doctor.mjs';
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
const cwd = REPO;
@@ -149,3 +149,33 @@ describe('doctor — checkVersionAlignment', () => {
if (c.fix) expect(c.fix).not.toMatch(/NaN|undefined/);
});
});
+
+describe('checkPackageManager', () => {
+ it('is informational when one lockfile answers', () => {
+ const dir = mkProject({'pnpm-lock.yaml': ''});
+ const c = checkPackageManager({cwd: dir});
+ expect(c).toMatchObject({id: 'package-manager', status: 'info'});
+ expect(c.message).toContain('pnpm');
+ });
+
+ it('fails when several lockfiles tie and nothing project-owned breaks it', () => {
+ // Without this the CLI answers from array order, and every command it
+ // prints — including the agent-docs invocation line — names a package
+ // manager the project may not use at all. Silence is the bug; say it.
+ const dir = mkProject({'pnpm-lock.yaml': '', 'yarn.lock': ''});
+ const c = checkPackageManager({cwd: dir});
+ expect(c.status).toBe('fail');
+ expect(c.message).toContain('yarn');
+ expect(c.message).toContain('pnpm');
+ expect(c.fix).toContain('packageManager');
+ });
+
+ it('is informational again once the project declares a packageManager', () => {
+ const dir = mkProject({
+ 'pnpm-lock.yaml': '',
+ 'yarn.lock': '',
+ 'package.json': JSON.stringify({packageManager: '[email protected]'}),
+ });
+ expect(checkPackageManager({cwd: dir}).status).toBe('info');
+ });
+});
diff --git a/packages/cli/foundation/env/package-manager.mjs b/packages/cli/foundation/env/package-manager.mjs
index 858b654c3c..612222f371 100644
--- a/packages/cli/foundation/env/package-manager.mjs
+++ b/packages/cli/foundation/env/package-manager.mjs
@@ -26,6 +26,18 @@ import * as path from 'node:path';
/** @type {readonly PackageManager[]} */
const KNOWN_PMS = ['yarn', 'pnpm', 'bun', 'npm'];
+/**
+ * Lockfile names by package manager. Order is the tiebreak of LAST resort —
+ * see {@link detectPackageManager} for why it should rarely decide anything.
+ * @type {readonly [PackageManager, readonly string[]][]}
+ */
+const LOCKFILES = [
+ ['yarn', ['yarn.lock']],
+ ['pnpm', ['pnpm-lock.yaml']],
+ ['bun', ['bun.lockb', 'bun.lock']],
+ ['npm', ['package-lock.json']],
+];
+
/**
* Narrow an arbitrary string to a known {@link PackageManager}.
* @param {string} name
@@ -36,50 +48,165 @@ function isKnownPackageManager(name) {
}
/**
- * Detect the package manager used in a project directory.
- * Walks up from targetDir looking for lockfiles.
+ * The `packageManager` field of a directory's package.json, if it names one we
+ * know. This is the declarative answer (corepack's field), so it outranks any
+ * lockfile sitting next to it.
+ * @param {string} dir
+ * @returns {PackageManager | null}
+ */
+function declaredPackageManager(dir) {
+ const pkgPath = path.join(dir, 'package.json');
+ if (!fs.existsSync(pkgPath)) return null;
+ try {
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
+ const name = String(pkg.packageManager ?? '').split('@')[0];
+ return isKnownPackageManager(name) ? name : null;
+ } catch {
+ // Best-effort: unreadable/invalid package.json.
+ return null;
+ }
+}
+
+/**
+ * The package manager currently running us, from the user agent every PM sets
+ * on the scripts and binaries it spawns.
+ * @returns {PackageManager | null}
+ */
+function runningPackageManager() {
+ const name = String(process.env.npm_config_user_agent ?? '').split('/')[0];
+ return isKnownPackageManager(name) ? name : null;
+}
+
+/**
+ * Every package manager with a lockfile in this directory.
+ * @param {string} dir
+ * @returns {PackageManager[]}
+ */
+function lockfilesIn(dir) {
+ return LOCKFILES.filter(([, names]) =>
+ names.some(name => fs.existsSync(path.join(dir, name))),
+ ).map(([pm]) => pm);
+}
+
+/**
+ * Files a project COMMITS that name its package manager. A stray `install` in
+ * the wrong tool drops a lockfile; it does not write any of these. That is what
+ * makes them project-owned evidence and a lockfile, on its own, merely a trace.
+ * @type {readonly [PackageManager, readonly string[]][]}
+ */
+const PROJECT_EVIDENCE = [
+ ['pnpm', ['pnpm-workspace.yaml']],
+ ['yarn', ['.yarnrc.yml', '.yarnrc']],
+ ['bun', ['bunfig.toml']],
+];
+
+/**
+ * Every package manager this directory declares through a committed config file.
+ * @param {string} dir
+ * @returns {PackageManager[]}
+ */
+function evidenceIn(dir) {
+ return PROJECT_EVIDENCE.filter(([, names]) =>
+ names.some(name => fs.existsSync(path.join(dir, name))),
+ ).map(([pm]) => pm);
+}
+
+/**
+ * A detection result, with the reasoning a caller needs to report it.
+ * @typedef {object} PackageManagerResolution
+ * @property {DetectedPackageManager} pm - What to use.
+ * @property {boolean} ambiguous - True when several lockfiles sit in one
+ * directory and nothing the project owns picks between them. `pm` is then the
+ * neutral `'npx'`: correct under every package manager, wrong under none.
+ * @property {string | null} dir - The directory that answered, if any.
+ * @property {PackageManager[]} candidates - The tied lockfile owners, when ambiguous.
+ */
+
+/**
+ * Detect the project's package manager, with the reasoning attached.
+ * Walks up from targetDir, taking the first directory that answers.
+ *
+ * A single lockfile still wins over everything else in its directory, which is
+ * the long-standing behaviour. What changes here is the case of SEVERAL
+ * lockfiles in one directory, which the fixed array order used to resolve
+ * silently and often wrongly.
+ *
+ * That case is not hypothetical. One `yarn install` inside a pnpm project
+ * leaves a `yarn.lock` beside the committed `pnpm-lock.yaml` forever, and
+ * `fbsource/nest` ships both at its root deliberately. Answering "yarn" from
+ * array order then makes every command the CLI prints wrong for that project —
+ * including the invocation line written into agent docs, which agents copy.
+ *
+ * Ambiguity is therefore resolved ONLY from evidence the project owns: the
+ * declared `packageManager` field, then a committed package-manager config
+ * file. Deliberately NOT `npm_config_user_agent`: an agent that was handed the
+ * wrong `yarn astryx` line runs the CLI *through yarn*, so the runner agrees
+ * with the mistake and the wrong line reproduces itself forever. The same is
+ * true of an installed binary invoked from that shell.
*
- * Returns `'npx'` when nothing can be detected — see {@link DetectedPackageManager}.
+ * When nothing project-owned decides it, the answer is not a guess — it is
+ * `'npx'`, which runs correctly under every package manager, plus
+ * `ambiguous: true` so `astryx doctor` can report the real problem. (Same idea
+ * as `findConfigPath`, which refuses to choose between coexisting configs.)
*
* @param {string} [targetDir=process.cwd()]
- * @returns {DetectedPackageManager}
+ * @returns {PackageManagerResolution}
*/
-export function detectPackageManager(targetDir = process.cwd()) {
+export function explainPackageManager(targetDir = process.cwd()) {
let dir = path.resolve(targetDir);
const root = path.parse(dir).root;
while (dir !== root) {
- // 1. Lockfiles (highest priority)
- if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn';
- if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm';
- if (fs.existsSync(path.join(dir, 'bun.lockb')) || fs.existsSync(path.join(dir, 'bun.lock'))) return 'bun';
- if (fs.existsSync(path.join(dir, 'package-lock.json'))) return 'npm';
-
- // 2. packageManager field in package.json
- const pkgPath = path.join(dir, 'package.json');
- if (fs.existsSync(pkgPath)) {
- try {
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
- if (pkg.packageManager) {
- const name = pkg.packageManager.split('@')[0];
- if (isKnownPackageManager(name)) return name;
- }
- } catch {
- // Best-effort: unreadable/invalid package.json — keep walking up.
+ const locks = lockfilesIn(dir);
+
+ // 1. One lockfile is unambiguous, and outranks the field as it always has.
+ if (locks.length === 1) {
+ return {pm: locks[0], ambiguous: false, dir, candidates: locks};
+ }
+
+ // 2. Several lockfiles: the filesystem cannot say. Only the project can.
+ if (locks.length > 1) {
+ const declared = declaredPackageManager(dir);
+ if (declared && locks.includes(declared)) {
+ return {pm: declared, ambiguous: false, dir, candidates: locks};
+ }
+ const evidence = evidenceIn(dir).filter(pm => locks.includes(pm));
+ if (evidence.length === 1) {
+ return {pm: evidence[0], ambiguous: false, dir, candidates: locks};
}
+ return {pm: 'npx', ambiguous: true, dir, candidates: locks};
}
+ // 3. No lockfile here: the field, if this directory declares one.
+ const declared = declaredPackageManager(dir);
+ if (declared) return {pm: declared, ambiguous: false, dir, candidates: []};
+
dir = path.dirname(dir);
}
- // 3. npm_config_user_agent env var (set by all PMs when running scripts)
- const ua = process.env.npm_config_user_agent;
- if (ua) {
- const name = ua.split('/')[0];
- if (isKnownPackageManager(name)) return name;
- }
+ // 4. Nothing on disk said anything anywhere. With no project evidence to
+ // contradict, the runner is the only signal there is.
+ return {
+ pm: runningPackageManager() ?? 'npx',
+ ambiguous: false,
+ dir: null,
+ candidates: [],
+ };
+}
- return 'npx';
+/**
+ * Detect the package manager used in a project directory.
+ *
+ * Returns `'npx'` when nothing can be detected, and also when several lockfiles
+ * tie with nothing project-owned to break them — see
+ * {@link explainPackageManager}, which carries the `ambiguous` flag callers need
+ * to report that second case.
+ *
+ * @param {string} [targetDir=process.cwd()]
+ * @returns {DetectedPackageManager}
+ */
+export function detectPackageManager(targetDir = process.cwd()) {
+ return explainPackageManager(targetDir).pm;
}
/**
diff --git a/packages/cli/foundation/env/package-manager.test.mjs b/packages/cli/foundation/env/package-manager.test.mjs
index aa7267c0d1..b4626a527b 100644
--- a/packages/cli/foundation/env/package-manager.test.mjs
+++ b/packages/cli/foundation/env/package-manager.test.mjs
@@ -6,6 +6,7 @@ import * as path from 'node:path';
import * as os from 'node:os';
import {
detectPackageManager,
+ explainPackageManager,
getDlxPrefix,
isCliOneOff,
getCliInvocation,
@@ -55,6 +56,94 @@ describe('detectPackageManager', () => {
expect(detectPackageManager(dir)).toBe('bun');
});
+ it('refuses to let the runner break a multi-lockfile tie', () => {
+ // One `yarn install` inside a pnpm project leaves a yarn.lock next to the
+ // committed pnpm-lock.yaml. Nothing the project owns picks between them, so
+ // there is no honest answer to give — only the neutral one.
+ const dir = makeTmpDir();
+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
+ process.env.npm_config_user_agent = 'pnpm/11.10.0 npm/? node/v22.0.0';
+ expect(detectPackageManager(dir)).toBe('npx');
+ expect(explainPackageManager(dir)).toMatchObject({
+ ambiguous: true,
+ candidates: ['yarn', 'pnpm'],
+ });
+ });
+
+ it('does not reproduce a wrong `yarn astryx` line it was invoked through', () => {
+ // The regression: an agent handed the wrong `yarn astryx` line runs the CLI
+ // THROUGH yarn, so npm_config_user_agent says yarn. A runner tiebreak then
+ // agrees with the mistake, and regenerating agent docs writes it again —
+ // the wrong line reproduces itself forever. Project evidence only.
+ const dir = makeTmpDir();
+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
+ process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
+ expect(detectPackageManager(dir)).not.toBe('yarn');
+ expect(getCliInvocation(dir)).toBe('npx astryx');
+ });
+
+ it('does not reproduce it for a directly invoked installed binary either', () => {
+ const dir = makeTmpDir();
+ const entry = process.argv[1];
+ try {
+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
+ process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
+ process.argv[1] = path.join(dir, 'node_modules/.bin/astryx');
+ expect(getCliInvocation(dir)).toBe('npx astryx');
+ } finally {
+ process.argv[1] = entry;
+ }
+ });
+
+ it('breaks the tie from a committed pnpm-workspace.yaml', () => {
+ const dir = makeTmpDir();
+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
+ fs.writeFileSync(path.join(dir, 'pnpm-workspace.yaml'), 'packages: []\n');
+ process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
+ expect(detectPackageManager(dir)).toBe('pnpm');
+ });
+
+ it('breaks the tie from a committed .yarnrc.yml', () => {
+ const dir = makeTmpDir();
+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
+ fs.writeFileSync(path.join(dir, '.yarnrc.yml'), 'nodeLinker: node-modules\n');
+ expect(detectPackageManager(dir)).toBe('yarn');
+ });
+
+ it('stays ambiguous when the project owns evidence for both', () => {
+ const dir = makeTmpDir();
+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
+ fs.writeFileSync(path.join(dir, 'pnpm-workspace.yaml'), 'packages: []\n');
+ fs.writeFileSync(path.join(dir, '.yarnrc.yml'), '');
+ expect(explainPackageManager(dir).ambiguous).toBe(true);
+ });
+
+ it('lets the packageManager field break a multi-lockfile tie', () => {
+ // A single lockfile still outranks the field (asserted above). This is only
+ // about the case where the filesystem is self-contradictory.
+ const dir = makeTmpDir();
+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({packageManager: '[email protected]'}),
+ );
+ expect(detectPackageManager(dir)).toBe('pnpm');
+ });
+
+ it('ignores a runner that has no lockfile in the directory', () => {
+ const dir = makeTmpDir();
+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
+ process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
+ expect(detectPackageManager(dir)).toBe('pnpm');
+ });
+
it('detects from packageManager field in package.json (no lockfile)', () => {
const dir = makeTmpDir();
fs.writeFileSync(