Skip to content

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

TypeScript

fix(cli): upgrade no longer says "up to date" when the CLI is older than Core (#7491)

Joey8222612312c8
diff --git a/.changeset/upgrade-cli-older-than-core.md b/.changeset/upgrade-cli-older-than-core.md
new file mode 100644
index 0000000000..137fad7a73
--- /dev/null
+++ b/.changeset/upgrade-cli-older-than-core.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx upgrade` no longer reports your code as up to date when the CLI is older than the installed `@astryxdesign/core`. Core codemods ship inside the CLI, so an older CLI has none for the releases after its own version. It used to print "No changes needed" and "No codemods available for this version range" and exit 0 while the code still needed those releases' migrations. It now warns once that it cannot finish, prints the same upgrade pinned to the CLI release that matches your Core (such as `cd <project> && npx @astryxdesign/cli@<core-version> upgrade --from <old-version> --path <source-dir> --apply`), and ends with "Upgrade incomplete". That command changes to the folder the run used and names the directory it scanned as an absolute path, both with symbolic links resolved, so it upgrades the same code wherever you paste it. It is written for a POSIX shell, or for PowerShell on Windows. `upgrade.status` (`no_codemods` and `config_fixable`) and `upgrade.run` gain an optional `cliBehindCore` field with `cliVersion` and `command`, present only in that case. The codemods the CLI has still run, and the exit status and every existing field are unchanged.
+
+@josephfarina
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 7d9ee80cf1..5e26d1c180 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -468,8 +468,8 @@ Every response has a `type` discriminant. The full set is below (generated from
| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |
| `upgrade.list` | Every available codemod, oldest→newest, as {name, package, title, version, optional}; returned for --list without running anything. |
| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. |
-| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |
-| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
+| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. no_codemods and config_fixable carry cliBehindCore ({cliVersion, command}) when the installed Core is newer than the CLI, which then has no codemods for the releases after its own version. |
+| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run. |
| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index. |
| `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. |
| `version` | The CLI version, for `astryx --version --json`: {version}. |
diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjs
index e894559775..974eb3be0e 100644
--- a/packages/cli/api/upgrade/_adapter.mjs
+++ b/packages/cli/api/upgrade/_adapter.mjs
@@ -34,7 +34,15 @@ import {
inspectAgentDocs,
renderAgentDocsBlock,
} from '../../foundation/agent-docs/agent-docs.mjs';
-import {formatCliCommand} from '../../foundation/env/package-manager.mjs';
+import {
+ CLI_PACKAGE,
+ commandInFolder,
+ formatCliCommand,
+ getDlxPrefix,
+ quoteCommandArgument,
+} from '../../foundation/env/package-manager.mjs';
+import {isValidSemver, semverGt} from '../../foundation/env/semver.mjs';
+import {CLI_ROOT} from '../../foundation/fs/paths.mjs';
import {Project, providerLedgerOf} from '../../foundation/config/project.mjs';
import {loadIntegrations} from '../../foundation/integrations/integrations.mjs';
import {resolveProviders} from '../../foundation/integrations/provider-resolution.mjs';
@@ -96,6 +104,99 @@ export function detectInstalledTargetVersion(cwd) {
return null;
}
+/**
+ * The running CLI's own version, read from its package.json.
+ * @returns {string | null} null when it cannot be read or is not semver
+ */
+function readRunningCliVersion() {
+ try {
+ const pkg = JSON.parse(
+ fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf-8'),
+ );
+ return isValidSemver(pkg.version) ? pkg.version : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Whether the installed Core is newer than this CLI, so part of the requested
+ * range has no codemods here.
+ *
+ * Core codemods ship inside the CLI. A CLI older than the installed
+ * `@astryxdesign/core` has none for the releases after its own version, so it
+ * can find no codemods, or stop partway, while the code still needs those
+ * releases' migrations. The returned command repeats this upgrade with the CLI
+ * release that matches the installed Core.
+ *
+ * Where an upgrade runs decides what it finds: the installed Core is read
+ * from that folder, and `--path` must stay inside it. So the command first
+ * changes to `cwd`, the folder this run used, then names `sourcePath`, the
+ * directory this run scanned, as an absolute `--path`. Both are named by their
+ * physical paths, with every symbolic link resolved: a shell's `cd` follows a
+ * link, but the CLI it starts reads its folder with every link resolved and
+ * checks `--path` against that. Pasted from any folder, the command finds the
+ * same Core and scans the same directory, even after a package runner moved
+ * this run (Yarn 1 runs `yarn astryx` at the project root). It is written for
+ * a POSIX shell, or for PowerShell on Windows (cmd.exe is not a target), with
+ * every argument quoted for that shell.
+ *
+ * Returns null when the CLI covers the whole range (`to` is not newer than
+ * both the CLI and `from`), when the CLI's own version cannot be read, or when
+ * the target is legacy `@xds/core`, which no CLI release shares a version with.
+ *
+ * @param {{from: string, to: string, packageName: string, options: UpgradeOptions, cwd: string, sourcePath: string}} input
+ * @returns {import('./upgrade.type.mjs').CliBehindCore | null}
+ */
+export function detectCliBehindCore({
+ from,
+ to,
+ packageName,
+ options,
+ cwd,
+ sourcePath,
+}) {
+ if (packageName !== '@astryxdesign/core') return null;
+ const cliVersion = readRunningCliVersion();
+ if (!cliVersion || !semverGt(to, cliVersion) || !semverGt(to, from)) {
+ return null;
+ }
+ const runFolder = path.resolve(cwd);
+ const folder = physicalFolder(runFolder);
+ const scanned = path.join(folder, path.relative(runFolder, sourcePath));
+ const args = ['upgrade', '--from', from, '--path', scanned];
+ if (options.codemod) args.push('--codemod', options.codemod);
+ for (const name of options.skipCodemod ?? []) {
+ args.push('--skip-codemod', name);
+ }
+ for (const spec of options.integration ?? []) {
+ args.push('--integration', spec);
+ }
+ if (options.force) args.push('--force');
+ if (options.installDeps) args.push('--install-deps');
+ if (options.apply) args.push('--apply');
+ const upgrade = [
+ getDlxPrefix(cwd),
+ ...[`${CLI_PACKAGE}@${to}`, ...args].map(arg => quoteCommandArgument(arg)),
+ ].join(' ');
+ return {cliVersion, command: commandInFolder(folder, upgrade)};
+}
+
+/**
+ * A folder as the operating system reports it to a process that runs there,
+ * with every symbolic link on the way resolved. Falls back to the path as
+ * given when it cannot be resolved.
+ * @param {string} dir an absolute folder
+ * @returns {string}
+ */
+function physicalFolder(dir) {
+ try {
+ return fs.realpathSync(dir);
+ } catch {
+ return dir;
+ }
+}
+
/**
* @param {(string | null | undefined | false)[] | undefined} files
* @returns {string[]}
@@ -332,11 +433,20 @@ export async function ensureCodemodDeps({installDeps} = {}) {
* Run the CORE registry codemods. Runs BEFORE the config is loaded so a core
* CONFIG codemod can repair a config the strict loader would otherwise reject.
* @param {CoreVersionManifest[]} versionManifests
- * @param {{apply: boolean, path: string, codemod?: string, skipCodemods: Set<string>, root?: string, protection?: {root: string, classify: (file: string) => import('../../foundation/fs/file-protection.mjs').FileProtection[]}, silent?: boolean}} options
+ * @param {{apply: boolean, path: string, codemod?: string, skipCodemods: Set<string>, root?: string, protection?: {root: string, classify: (file: string) => import('../../foundation/fs/file-protection.mjs').FileProtection[]}, silent?: boolean, coversTarget?: boolean}} options
*/
export async function runCoreCodemods(
versionManifests,
- {apply, path: srcPath, codemod, skipCodemods, root, protection, silent},
+ {
+ apply,
+ path: srcPath,
+ codemod,
+ skipCodemods,
+ root,
+ protection,
+ silent,
+ coversTarget,
+ },
) {
return runCodemods(versionManifests, {
apply,
@@ -346,6 +456,7 @@ export async function runCoreCodemods(
silent: silent ?? logger.silent,
root,
protection,
+ coversTarget,
});
}
@@ -411,7 +522,9 @@ export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {
const extras =
extraSpecs.length === 0
? []
- : await loadIntegrations(extraSpecs, {resolveProviders: false});
+ : // Resolved from the project, as --integration names a package it
+ // installed, not from whichever folder the process started in.
+ await loadIntegrations(extraSpecs, {cwd, resolveProviders: false});
const {integrations, ledger} = resolveProviders(
[
...candidates,
diff --git a/packages/cli/api/upgrade/run/cli-behind-core.test.mjs b/packages/cli/api/upgrade/run/cli-behind-core.test.mjs
new file mode 100644
index 0000000000..1e6ebc65f9
--- /dev/null
+++ b/packages/cli/api/upgrade/run/cli-behind-core.test.mjs
@@ -0,0 +1,438 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Core codemods ship inside the CLI, so a CLI older than the installed
+ * Core has none for the releases after its own version. Every result past the
+ * up-to-date exit says so in `cliBehindCore`, with the same upgrade pinned to
+ * the CLI release that matches the Core; a CLI that covers the range returns
+ * what it always did. The pinned command changes to the folder the run used
+ * and names the directory it scanned as an absolute path, both with symbolic
+ * links resolved, so a POSIX shell runs it there, with every argument
+ * unchanged, wherever it is pasted, even when upgrade() reached the project
+ * through a link.
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import {execFileSync, spawnSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {upgrade} from '../upgrade.mjs';
+import {logCliBehindCore} from '../status/status.mjs';
+import {logger} from '../../logger.mjs';
+import {CLI_ROOT} from '../../../foundation/fs/paths.mjs';
+import {
+ commandInFolder,
+ getDlxPrefix,
+ quoteCommandArgument,
+} from '../../../foundation/env/package-manager.mjs';
+
+const SLOW = 30_000;
+
+const CLI_VERSION = JSON.parse(
+ fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf8'),
+).version;
+const [MAJOR, MINOR] = CLI_VERSION.split('.').map(Number);
+/** A Core release after this CLI: it has no codemods for it. */
+const NEWER_CORE = `${MAJOR}.${MINOR + 1}.0`;
+
+/** A source file a 0.7.0 codemod rewrites (`emptySearchResultsText`). */
+const TYPEAHEAD_SOURCE =
+ "import {Typeahead} from '@astryxdesign/core';\n" +
+ 'export const x = <Typeahead emptySearchResultsText="None" />;\n';
+
+let dir;
+
+/** @param {string} version @param {string} [packageName] */
+function installCore(version, packageName = '@astryxdesign/core') {
+ const core = path.join(dir, 'node_modules', ...packageName.split('/'));
+ fs.mkdirSync(core, {recursive: true});
+ fs.writeFileSync(
+ path.join(core, 'package.json'),
+ JSON.stringify({name: packageName, version}),
+ );
+}
+
+/** @param {string} rel @param {string} body */
+function write(rel, body) {
+ const file = path.join(dir, rel);
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ fs.writeFileSync(file, body);
+}
+
+/**
+ * A path in the project as a process running there sees it: every symbolic
+ * link resolved.
+ * @param {string} rel
+ */
+function inProject(rel) {
+ return path.join(fs.realpathSync(dir), rel);
+}
+
+/**
+ * The pinned command for this project, as the CLI prints it.
+ * @param {...string} args the arguments after `upgrade`
+ */
+function pinned(...args) {
+ return commandInFolder(
+ fs.realpathSync(dir),
+ [
+ getDlxPrefix(dir),
+ `@astryxdesign/cli@${NEWER_CORE}`,
+ 'upgrade',
+ ...args.map(arg => quoteCommandArgument(arg)),
+ ].join(' '),
+ );
+}
+
+/**
+ * Stand-ins for the package runners: each prints the folder it runs in and the
+ * arguments the shell passed.
+ */
+const RUNNERS = ['npx', 'pnpm', 'yarn', 'bunx']
+ .map(
+ name =>
+ `${name}() { "$0" -e 'process.stdout.write(JSON.stringify({cwd: process.cwd(), argv: process.argv.slice(1)}))' -- "$@"; }`,
+ )
+ .join('; ');
+
+/**
+ * What a POSIX shell runs for `command` pasted in `cwd`: the folder the
+ * package runner ran in, and its arguments from the pinned CLI package on.
+ * @param {string} command
+ * @param {string} cwd the folder the command is pasted in
+ * @returns {{cwd: string, args: string[]}}
+ */
+function runInShell(command, cwd) {
+ const ran = JSON.parse(
+ execFileSync(
+ '/bin/sh',
+ ['-c', `${RUNNERS}; ${command}`, process.execPath],
+ {
+ cwd,
+ encoding: 'utf8',
+ },
+ ),
+ );
+ return {
+ cwd: ran.cwd,
+ args: ran.argv.slice(ran.argv.indexOf(`@astryxdesign/cli@${NEWER_CORE}`)),
+ };
+}
+
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-cli-behind-'));
+ write('package.json', JSON.stringify({name: 'consumer', version: '1.0.0'}));
+ write('src/index.tsx', TYPEAHEAD_SOURCE);
+});
+
+afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));
+
+describe('a CLI older than the installed Core', {timeout: SLOW}, () => {
+ // The defect: the range past this CLI has no codemods here, so the run
+ // reported `no_codemods` (and "already up to date") and exited 0, while the
+ // project still needed the newer releases' migrations.
+ it('marks a range this CLI has no codemods for, and names the CLI that does', async () => {
+ installCore(NEWER_CORE);
+
+ const res = await upgrade({from: CLI_VERSION, apply: true}, {cwd: dir});
+
+ expect(res.type).toBe('upgrade.status');
+ expect(res.data.status).toBe('no_codemods');
+ expect(res.data.cliBehindCore).toEqual({
+ cliVersion: CLI_VERSION,
+ command: pinned(
+ '--from',
+ CLI_VERSION,
+ '--path',
+ inProject('src'),
+ '--apply',
+ ),
+ });
+ });
+
+ it('runs the codemods it has for a range it covers only in part, and marks the rest', async () => {
+ installCore(NEWER_CORE);
+
+ const res = await upgrade({from: '0.6.8', apply: true}, {cwd: dir});
+
+ expect(res.type).toBe('upgrade.run');
+ expect(res.data.codemods).toBeGreaterThan(0);
+ expect(fs.readFileSync(path.join(dir, 'src/index.tsx'), 'utf8')).toContain(
+ 'emptySearchText="None"',
+ );
+ expect(res.data.cliBehindCore).toEqual({
+ cliVersion: CLI_VERSION,
+ command: pinned('--from', '0.6.8', '--path', inProject('src'), '--apply'),
+ });
+ });
+
+ it('repeats the invocation in the pinned command', async () => {
+ installCore(NEWER_CORE);
+ write('my src/index.tsx', TYPEAHEAD_SOURCE);
+ // An installed integration the run names, so --integration is repeated.
+ write(
+ 'node_modules/@acme/widgets/package.json',
+ JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),
+ );
+ write(
+ 'node_modules/@acme/widgets/astryx.integration.mjs',
+ 'export default {};\n',
+ );
+
+ const res = await upgrade(
+ {
+ from: CLI_VERSION,
+ path: 'my src',
+ codemod: 'only-this',
+ skipCodemod: ['first', 'second'],
+ integration: ['@acme/widgets'],
+ force: true,
+ installDeps: true,
+ },
+ {cwd: dir},
+ );
+
+ expect(res.data.cliBehindCore?.command).toBe(
+ pinned(
+ '--from',
+ CLI_VERSION,
+ '--path',
+ inProject('my src'),
+ '--codemod',
+ 'only-this',
+ '--skip-codemod',
+ 'first',
+ '--skip-codemod',
+ 'second',
+ '--integration',
+ '@acme/widgets',
+ '--force',
+ '--install-deps',
+ ),
+ );
+ });
+
+ // Where an upgrade runs decides what it finds: the installed Core is read
+ // from that folder, and --path must stay inside it. The command printed
+ // without a folder failed when pasted anywhere else: ERR_PATH_TRAVERSAL from
+ // a subfolder, ERR_VERSION_DETECT from a parent. A package runner can also
+ // move the run: Yarn 1 runs `yarn astryx` at the project root.
+ it('changes to the folder the run used and names the directory it scanned as an absolute path', async () => {
+ installCore(NEWER_CORE);
+ write('app/index.tsx', TYPEAHEAD_SOURCE);
+ const project = fs.realpathSync(dir);
+
+ for (const [given, scanned] of [
+ [undefined, inProject('src')],
+ ['.', project],
+ ['app', inProject('app')],
+ ['./app/', inProject('app')],
+ ]) {
+ const res = await upgrade(
+ {from: CLI_VERSION, ...(given ? {path: given} : {})},
+ {cwd: dir},
+ );
+ const command = /** @type {string} */ (res.data.cliBehindCore?.command);
+
+ expect(command).toBe(pinned('--from', CLI_VERSION, '--path', scanned));
+ if (process.platform !== 'win32') {
+ for (const pastedIn of [
+ path.join(dir, 'app'),
+ path.dirname(dir),
+ path.parse(dir).root,
+ ]) {
+ const ran = runInShell(command, pastedIn);
+ expect(ran.cwd).toBe(project);
+ expect(ran.args[ran.args.indexOf('--path') + 1]).toBe(scanned);
+ }
+ }
+ }
+ });
+
+ it.skipIf(process.platform === 'win32')(
+ 'quotes the command so a POSIX shell enters the folder and passes every argument unchanged',
+ async () => {
+ fs.rmSync(dir, {recursive: true, force: true});
+ dir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'upg cost $5 `date` \'one\' "two" !x -'),
+ );
+ write(
+ 'package.json',
+ JSON.stringify({name: 'consumer', version: '1.0.0'}),
+ );
+ write('src/index.tsx', TYPEAHEAD_SOURCE);
+ installCore(NEWER_CORE);
+
+ const res = await upgrade(
+ {
+ from: CLI_VERSION,
+ skipCodemod: ["it's", 'a$b c'],
+ apply: true,
+ },
+ {cwd: dir},
+ );
+
+ const ran = runInShell(
+ /** @type {string} */ (res.data.cliBehindCore?.command),
+ path.dirname(dir),
+ );
+
+ expect(ran.cwd).toBe(fs.realpathSync(dir));
+ expect(ran.args).toEqual([
+ `@astryxdesign/cli@${NEWER_CORE}`,
+ 'upgrade',
+ '--from',
+ CLI_VERSION,
+ '--path',
+ inProject('src'),
+ '--skip-codemod',
+ "it's",
+ '--skip-codemod',
+ 'a$b c',
+ '--apply',
+ ]);
+ },
+ );
+});
+
+/** The CLI's own bin, which the stand-in runners below run. */
+const BIN = path.join(CLI_ROOT, 'clients', 'cli', 'bin', 'astryx.mjs');
+
+/**
+ * Stand-ins for the package runners: each drops its own words and the pinned
+ * package, then runs this CLI with the rest of the command.
+ */
+const RUNS_THIS_CLI = /** @type {Array<[string, number]>} */ ([
+ ['npx', 1],
+ ['bunx', 1],
+ ['pnpm', 2],
+ ['yarn', 2],
+])
+ .map(
+ ([name, words]) =>
+ `${name}() { shift ${words}; "$0" ${quoteCommandArgument(BIN)} "$@"; }`,
+ )
+ .join('; ');
+
+// A shell's `cd` follows a symbolic link, but the CLI it starts reads its
+// folder with every link resolved and checks --path against that. A command
+// that kept the link upgrade() was given exited 1 with ERR_PATH_TRAVERSAL.
+describe.skipIf(process.platform === 'win32')(
+ 'a project upgrade() reaches through a symbolic link',
+ {timeout: SLOW},
+ () => {
+ /** @type {string} */
+ let base;
+
+ beforeEach(() => {
+ fs.rmSync(dir, {recursive: true, force: true});
+ base = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-link-'));
+ dir = path.join(base, 'real', 'my app');
+ write(
+ 'package.json',
+ JSON.stringify({name: 'consumer', version: '1.0.0'}),
+ );
+ write('src/index.tsx', TYPEAHEAD_SOURCE);
+ installCore(NEWER_CORE);
+ });
+
+ afterEach(() => fs.rmSync(base, {recursive: true, force: true}));
+
+ /**
+ * Run upgrade() from `cwd`, then the command it prints, in /bin/sh, from
+ * `cwd` and from the folder above the project.
+ * @param {string} cwd
+ */
+ async function expectPrintedCommandToRun(cwd) {
+ const res = await upgrade({from: CLI_VERSION}, {cwd});
+ const command = /** @type {string} */ (res.data.cliBehindCore?.command);
+
+ for (const pastedIn of [cwd, base]) {
+ const ran = spawnSync(
+ '/bin/sh',
+ ['-c', `${RUNS_THIS_CLI}; ${command}`, process.execPath],
+ {cwd: pastedIn, encoding: 'utf8'},
+ );
+
+ expect(ran.status, ran.stderr).toBe(0);
+ expect(ran.stdout).toContain(`Installed target: ${NEWER_CORE}`);
+ expect(ran.stdout).toContain(`Scanning ${inProject('src')} `);
+ }
+ expect(command).toBe(
+ pinned('--from', CLI_VERSION, '--path', inProject('src')),
+ );
+ }
+
+ it('prints a command that runs, from a folder reached through a link above the project', async () => {
+ fs.symlinkSync(path.join(base, 'real'), path.join(base, 'link'), 'dir');
+
+ await expectPrintedCommandToRun(path.join(base, 'link', 'my app'));
+ });
+
+ it('prints a command that runs, through a project root that is a link', async () => {
+ fs.symlinkSync(dir, path.join(base, 'app'), 'dir');
+
+ await expectPrintedCommandToRun(path.join(base, 'app'));
+ });
+ },
+);
+
+describe('a CLI that covers the range', {timeout: SLOW}, () => {
+ it('adds nothing when the installed Core is this CLI release', async () => {
+ installCore(CLI_VERSION);
+
+ const res = await upgrade({from: '0.6.8'}, {cwd: dir});
+
+ expect(res.type).toBe('upgrade.run');
+ expect('cliBehindCore' in res.data).toBe(false);
+ });
+
+ it('adds nothing when --from is already the installed Core', async () => {
+ installCore(NEWER_CORE);
+
+ const res = await upgrade({from: NEWER_CORE}, {cwd: dir});
+
+ expect(res.data.status).toBe('up_to_date');
+ expect('cliBehindCore' in res.data).toBe(false);
+
+ const forced = await upgrade({from: NEWER_CORE, force: true}, {cwd: dir});
+
+ expect(forced.data.status).toBe('no_codemods');
+ expect('cliBehindCore' in forced.data).toBe(false);
+ });
+
+ it('adds nothing for legacy @xds/core, which shares no version with a CLI release', async () => {
+ installCore(NEWER_CORE, '@xds/core');
+
+ const res = await upgrade({from: CLI_VERSION}, {cwd: dir});
+
+ expect(res.data.status).toBe('no_codemods');
+ expect('cliBehindCore' in res.data).toBe(false);
+ });
+});
+
+describe('logCliBehindCore: the warning names the shell its command is written for', () => {
+ it.each([
+ ['win32', 'Run it in PowerShell with the CLI that matches your Core:'],
+ ['linux', 'Run it with the CLI that matches your Core:'],
+ ['darwin', 'Run it with the CLI that matches your Core:'],
+ ])('on %s', (platform, ending) => {
+ const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {});
+ try {
+ logCliBehindCore(
+ {cliVersion: '0.7.0', command: 'cd x; npx y'},
+ '0.8.0',
+ platform,
+ );
+ expect(warn.mock.calls.map(([line]) => String(line))).toEqual([
+ expect.stringMatching(
+ new RegExp(`${ending.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')}$`, 'u'),
+ ),
+ ' cd x; npx y',
+ ]);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjs
index 3c3a8f2262..d1115559bd 100644
--- a/packages/cli/api/upgrade/run/run.mjs
+++ b/packages/cli/api/upgrade/run/run.mjs
@@ -15,12 +15,18 @@
* ShadCN-copied compositions → post-codemod hooks → render + refresh agent docs
* from final post-upgrade state. Integration DISCOVERY errors skip that
* integration; execution errors abort before the agent-doc write.
+ *
+ * Core codemods ship inside the CLI, so a CLI older than the installed Core
+ * has none for the releases after its own version. Every result past the
+ * up-to-date exit then carries `cliBehindCore`, and no human line says the
+ * upgrade finished; the warning names the same upgrade on the matching CLI.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import {
detectInstalledTargetVersion,
+ detectCliBehindCore,
prepareAgentDocsRefresh,
applyAgentDocsRefresh,
inspectAgentDocs,
@@ -42,6 +48,7 @@ import {
statusUpToDate,
statusNoCodemods,
statusConfigFixable,
+ logCliBehindCore,
} from '../status/status.mjs';
import {semverGte} from '../../../foundation/env/semver.mjs';
import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
@@ -195,6 +202,17 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
});
}
+ // Past the up-to-date exit, codemods are needed through targetVersion. A
+ // CLI older than that has none for the releases after its own version.
+ const cliBehindCore = detectCliBehindCore({
+ from: currentVersion,
+ to: targetVersion,
+ packageName: installed.packageName,
+ options,
+ cwd,
+ sourcePath: path_,
+ });
+
const versionManifests = await getCoreVersionManifests(
currentVersion,
targetVersion,
@@ -243,6 +261,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
skipCodemods,
root: cwd,
protection,
+ coversTarget: !cliBehindCore,
});
const coreResult =
codemodResult && 'totalFilesChanged' in codemodResult
@@ -271,6 +290,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
for (const item of protectedFiles) {
logger.error(` ${item.file} — ${item.declarations.join('; ')}`);
}
+ if (cliBehindCore) logCliBehindCore(cliBehindCore, targetVersion);
logger.log('Upgrade incomplete: protected changes remain\n');
return {
type: 'upgrade.run',
@@ -299,6 +319,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
complete: false,
errorCode: 'ERR_CODEMOD_PROTECTED',
errors: coreResult?.errors ?? [],
+ ...(cliBehindCore ? {cliBehindCore} : {}),
},
};
}
@@ -316,6 +337,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
to: targetVersion,
configError: configErr.message,
configCodemods: coreConfigCodemodNames,
+ cliBehindCore,
agentDocs:
/** @type {import('../upgrade.type.mjs').AgentDocsSummary} */ ({
status: inspection.status,
@@ -381,6 +403,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
to: targetVersion,
agentDocs,
...(registryResult ? {registryCompositions: registryResult.summary} : {}),
+ cliBehindCore,
});
}
@@ -620,6 +643,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
}
receipt.errors = finalErrors;
if (registryResult) receipt.registryCompositions = registryResult.summary;
+ if (cliBehindCore) receipt.cliBehindCore = cliBehindCore;
if (protectedFiles.length > 0) {
logger.error(
@@ -655,7 +679,12 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
}
const registryOk = receipt.registryCompositions?.ok ?? true;
- const done = apply ? 'Upgrade complete' : 'Dry run complete';
+ if (cliBehindCore) logCliBehindCore(cliBehindCore, targetVersion);
+ const done = cliBehindCore
+ ? 'Upgrade incomplete'
+ : apply
+ ? 'Upgrade complete'
+ : 'Dry run complete';
logger.log(
protectedFiles.length > 0
? 'Upgrade incomplete: protected changes remain\n'
diff --git a/packages/cli/api/upgrade/status/status.mjs b/packages/cli/api/upgrade/status/status.mjs
index 28b06e1cb7..bd0e8a6759 100644
--- a/packages/cli/api/upgrade/status/status.mjs
+++ b/packages/cli/api/upgrade/status/status.mjs
@@ -10,6 +10,10 @@
* - `config_fixable` — DRY-RUN only: the config fails strict validation but a
* pending core CONFIG codemod would repair it; preview the fix, don't write.
*
+ * `no_codemods` and `config_fixable` also carry `cliBehindCore` when the
+ * installed Core is newer than this CLI: the run cannot finish the upgrade, so
+ * neither says it is done, and `logCliBehindCore` names the command that can.
+ *
* These builders own the exact human progress lines for their path (emitted via
* the shared `logger`) and return the `upgrade.status` envelope; the caller
* just returns what they hand back.
@@ -40,13 +44,43 @@ export function statusUpToDate({from, to, agentDocs, registryCompositions}) {
}
/**
- * No core or integration codemods apply to the requested version range.
- * @param {{from: string, to: string, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary, registryCompositions?: import('../upgrade.type.mjs').RegistryCompositionSummary}} data
+ * The one warning for a CLI older than the installed Core: it has no codemods
+ * for the releases after its own version, and the pinned command does. The
+ * command gets a line of its own, so it copies exactly, whatever quotes or
+ * backticks its arguments carry. On Windows it is written for PowerShell, and
+ * the warning says so.
+ * @param {import('../upgrade.type.mjs').CliBehindCore} cliBehindCore
+ * @param {string} to the installed Core version
+ * @param {string} [platform] the `process.platform` the command was printed
+ * for, as `quoteCommandArgument` and `commandInFolder` take it
+ */
+export function logCliBehindCore({cliVersion, command}, to, platform = process.platform) {
+ const shell = platform === 'win32' ? ' in PowerShell' : '';
+ logger.warn(
+ `This CLI (${cliVersion}) is older than the installed @astryxdesign/core (${to}): ` +
+ `it has no codemods for releases after ${cliVersion}, so it cannot finish this upgrade. ` +
+ `Run it${shell} with the CLI that matches your Core:`,
+ );
+ logger.warn(` ${command}`);
+}
+
+/**
+ * No core or integration codemods apply to the requested version range. When
+ * the CLI is older than the installed Core, that only means this CLI has none:
+ * the result carries `cliBehindCore` and the human lines say so.
+ * @param {{from: string, to: string, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary, registryCompositions?: import('../upgrade.type.mjs').RegistryCompositionSummary, cliBehindCore?: import('../upgrade.type.mjs').CliBehindCore | null}} data
* @returns {import('../upgrade.type.mjs').UpgradeStatusResponse}
*/
-export function statusNoCodemods({from, to, agentDocs, registryCompositions}) {
- logger.log('[ok] No codemods available for this version range.');
- logger.log(registryCompositions?.ok === false ? 'Finished with unresolved registry items\n' : 'Done\n');
+export function statusNoCodemods({from, to, agentDocs, registryCompositions, cliBehindCore}) {
+ if (cliBehindCore) logCliBehindCore(cliBehindCore, to);
+ else logger.log('[ok] No codemods available for this version range.');
+ logger.log(
+ registryCompositions?.ok === false
+ ? 'Finished with unresolved registry items\n'
+ : cliBehindCore
+ ? 'Upgrade incomplete\n'
+ : 'Done\n',
+ );
return {
type: 'upgrade.status',
data: {
@@ -55,6 +89,7 @@ export function statusNoCodemods({from, to, agentDocs, registryCompositions}) {
to,
agentDocs,
...(registryCompositions ? {registryCompositions} : {}),
+ ...(cliBehindCore ? {cliBehindCore} : {}),
},
};
}
@@ -63,10 +98,10 @@ export function statusNoCodemods({from, to, agentDocs, registryCompositions}) {
* DRY-RUN only: the consumer's astryx.config fails strict validation, but a
* pending core CONFIG codemod previewed a change that would repair it. Preview
* the fix + report the exact `--apply` command; integrations are skipped here.
- * @param {{from: string, to: string, configError: string, configCodemods: string[], agentDocs: import('../upgrade.type.mjs').AgentDocsSummary}} data
+ * @param {{from: string, to: string, configError: string, configCodemods: string[], agentDocs: import('../upgrade.type.mjs').AgentDocsSummary, cliBehindCore?: import('../upgrade.type.mjs').CliBehindCore | null}} data
* @returns {import('../upgrade.type.mjs').UpgradeStatusResponse}
*/
-export function statusConfigFixable({from, to, configError, configCodemods, agentDocs}) {
+export function statusConfigFixable({from, to, configError, configCodemods, agentDocs, cliBehindCore}) {
const codemodFlags = configCodemods.map(name => `--codemod ${name}`).join(' ');
const suggestedCommand = `astryx upgrade --from ${from} ${codemodFlags} --apply`;
const guidance =
@@ -77,7 +112,8 @@ export function statusConfigFixable({from, to, configError, configCodemods, agen
logger.warn(guidance);
logger.log(` ${formatCliCommand(suggestedCommand)}`);
logger.log('Integrations are skipped in this preview; they will be processed on the --apply run.');
- logger.log('Dry run complete\n');
+ if (cliBehindCore) logCliBehindCore(cliBehindCore, to);
+ logger.log(cliBehindCore ? 'Upgrade incomplete\n' : 'Dry run complete\n');
return {
type: 'upgrade.status',
data: {
@@ -90,6 +126,7 @@ export function statusConfigFixable({from, to, configError, configCodemods, agen
message: guidance,
note: 'Integrations are skipped in this preview; they will be processed on the --apply run.',
agentDocs,
+ ...(cliBehindCore ? {cliBehindCore} : {}),
},
};
}
diff --git a/packages/cli/api/upgrade/upgrade.doc.mjs b/packages/cli/api/upgrade/upgrade.doc.mjs
index 7258cd01de..6a41994e6f 100644
--- a/packages/cli/api/upgrade/upgrade.doc.mjs
+++ b/packages/cli/api/upgrade/upgrade.doc.mjs
@@ -22,7 +22,9 @@ export const doc = {
'loaded, so they can repair an invalid config. Also updates copied compositions from ' +
'their install receipts: unchanged files are updated, non-overlapping edits are merged, ' +
'and conflicts are left untouched. `list` only lists codemods; `registry` only updates ' +
- 'copied compositions.',
+ 'copied compositions. Core codemods ship inside the CLI, so a CLI older than the installed ' +
+ 'Core has none for the releases after its own version: the result then carries ' +
+ '`cliBehindCore` with the command that runs the same upgrade on the matching CLI.',
importPath: '@astryxdesign/cli/api',
signature:
'upgrade(options?: UpgradeOptions, ctx?: {cwd?: string}): Promise<UpgradeListResponse | UpgradeRegistryResponse | UpgradeStatusResponse | UpgradeRunResponse>',
@@ -118,12 +120,12 @@ export const doc = {
{
type: 'upgrade.status',
description:
- 'A short-circuit outcome (no codemods executed): `up_to_date` (`from` is at/after the installed target and no `force`), `no_codemods` (none apply to the range), or `config_fixable` (dry-run preview that a pending config codemod would repair an invalid astryx.config). up_to_date and no_codemods carry the agent-docs summary and, when receipts are found, the copied-composition summary; config_fixable carries configError, configCodemods, suggestedCommand, message, note, and the agent-docs summary.',
+ 'A short-circuit outcome (no codemods executed): `up_to_date` (`from` is at/after the installed target and no `force`), `no_codemods` (none apply to the range), or `config_fixable` (dry-run preview that a pending config codemod would repair an invalid astryx.config). up_to_date and no_codemods carry the agent-docs summary and, when receipts are found, the copied-composition summary; config_fixable carries configError, configCodemods, suggestedCommand, message, note, and the agent-docs summary. When the installed Core is newer than the CLI, no_codemods and config_fixable also carry cliBehindCore ({cliVersion, command}): this CLI has no codemods for the releases after cliVersion, and command runs the same upgrade with the CLI release that matches the installed Core.',
},
{
type: 'upgrade.run',
description:
- 'The terminal run receipt: from, to, codemods (count), integrations, agentDocs, agentDocsRefreshed, registryCompositions (when receipts are found), sourcePathFound (false when the resolved `path` does not exist, so nothing was scanned), filesChanged, transformsApplied, modifiedFiles, protectedFiles, declinedCandidates, errors, and complete. When a protected file still requires a change, complete is false and errorCode is ERR_CODEMOD_PROTECTED; the CLI exits nonzero while preserving the structured receipt.',
+ 'The terminal run receipt: from, to, codemods (count), integrations, agentDocs, agentDocsRefreshed, registryCompositions (when receipts are found), sourcePathFound (false when the resolved `path` does not exist, so nothing was scanned), filesChanged, transformsApplied, modifiedFiles, protectedFiles, declinedCandidates, errors, and complete. When a protected file still requires a change, complete is false and errorCode is ERR_CODEMOD_PROTECTED; the CLI exits nonzero while preserving the structured receipt. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run, and command runs the same upgrade with the matching CLI.',
},
],
throws: [
diff --git a/packages/cli/api/upgrade/upgrade.type.mjs b/packages/cli/api/upgrade/upgrade.type.mjs
index 40f26f47b5..2ce6e52bf9 100644
--- a/packages/cli/api/upgrade/upgrade.type.mjs
+++ b/packages/cli/api/upgrade/upgrade.type.mjs
@@ -106,6 +106,16 @@
* @property {string[]} commands Exact regeneration commands found in generated headers, when present.
*/
+/**
+ * Present only when the installed `@astryxdesign/core` (the response's `to`) is
+ * newer than the running CLI. Core codemods ship inside the CLI, so this CLI
+ * has none for the releases after `cliVersion`: the run could not migrate them,
+ * whatever else the response reports.
+ * @typedef {object} CliBehindCore
+ * @property {string} cliVersion The running CLI's version, the last release it has codemods for.
+ * @property {string} command The same upgrade, run with the CLI release that matches the installed Core. It first changes to the folder this run used, then names the directory this run scanned as an absolute `--path`, both with symbolic links resolved, so pasted from any folder it finds the same Core and scans the same directory. It is written for a POSIX shell (sh, bash, zsh), or for PowerShell on Windows, with each argument quoted for that shell; cmd.exe is not a target.
+ */
+
/**
* astryx --json upgrade [--apply]
* @typedef {object} UpgradeRunResponse
@@ -127,6 +137,7 @@
* @property {Array<{file: string, location?: string, reason: string}>} [data.declinedCandidates] Candidates left unchanged because proof was insufficient.
* @property {number} [data.transformsApplied] Total codemod changes. A code or config codemod counts once for each file it changed, so one file changed by four of them counts four times; a project codemod counts once, however many files it writes.
* @property {Array<{file: string, codemod: string, error: string}>} [data.errors] Per-codemod errors, when any codemod failed.
+ * @property {CliBehindCore} [data.cliBehindCore] Present only when the installed Core is newer than this CLI: codemods for the releases after `cliBehindCore.cliVersion` did not run.
*/
/**
@@ -140,9 +151,13 @@
* reports the exact command to apply it; integrations are skipped for the
* preview (they will be processed on the `--apply` run).
*
+ * `no_codemods` and `config_fixable` carry `cliBehindCore` when the installed
+ * Core is newer than this CLI; `no_codemods` then means only that this CLI has
+ * no codemods for the range.
+ *
* @typedef {object} UpgradeStatusResponse
* @property {'upgrade.status'} type
- * @property {{status: 'up_to_date', from: string, to: string, agentDocs: AgentDocsSummary, registryCompositions?: RegistryCompositionSummary} | {status: 'no_codemods', from: string, to: string, agentDocs: AgentDocsSummary, registryCompositions?: RegistryCompositionSummary} | {status: 'config_fixable', from: string, to: string, configError: string, configCodemods: string[], suggestedCommand: string, message: string, note: string, agentDocs: AgentDocsSummary}} data
+ * @property {{status: 'up_to_date', from: string, to: string, agentDocs: AgentDocsSummary, registryCompositions?: RegistryCompositionSummary} | {status: 'no_codemods', from: string, to: string, agentDocs: AgentDocsSummary, registryCompositions?: RegistryCompositionSummary, cliBehindCore?: CliBehindCore} | {status: 'config_fixable', from: string, to: string, configError: string, configCodemods: string[], suggestedCommand: string, message: string, note: string, agentDocs: AgentDocsSummary, cliBehindCore?: CliBehindCore}} data
*/
/**
diff --git a/packages/cli/assets/codemods/runner.mjs b/packages/cli/assets/codemods/runner.mjs
index db81f84d5d..1098147d58 100644
--- a/packages/cli/assets/codemods/runner.mjs
+++ b/packages/cli/assets/codemods/runner.mjs
@@ -418,6 +418,7 @@ async function runProjectCodemod(
* @param {boolean} [options.silent] - Suppress all human-facing output (for --json)
* @param {string} [options.root] - Project root a project codemod reads (default: the process cwd)
* @param {{root: string, classify: (file: string) => import('../../foundation/fs/file-protection.mjs').FileProtection[]}} [options.protection] - Preloaded protection resolver
+ * @param {boolean} [options.coversTarget] - False when these codemods stop before the installed target (the CLI is older than Core), so a run with no changes does not say the code is up to date. Default true.
* @returns {Promise<{totalFilesChanged: number, totalTransformsApplied: number, totalValidationBlocked: number, changedFiles: string[], writtenFiles: string[], stagedContents: Map<string, string>, protectedFiles: import('../../authoring/codemod/type').CodemodRunResult['protectedFiles'], errors: Array<{file: string, codemod: string, error: string}>, skippedOptional: Array<{name: string, meta: {title: string, description?: string, fileExtensions?: string[], codemodType?: string}, version: string}>} | {ok: false, reason: string, resolvedPath: string}>}
*/
export async function runCodemods(
@@ -430,6 +431,7 @@ export async function runCodemods(
silent = false,
root = process.cwd(),
protection: providedProtection,
+ coversTarget = true,
},
) {
// No-op stub object so silent mode skips log output entirely without
@@ -643,7 +645,11 @@ export async function runCodemods(
errors.length === 0 &&
protectedFiles.length === 0
) {
- log.success('No changes needed — your code is already up to date!');
+ // Codemods that stop before the installed target cannot vouch for the
+ // code; the caller says what is missing.
+ if (coversTarget) {
+ log.success('No changes needed — your code is already up to date!');
+ }
} else if (apply && protectedFiles.length > 0) {
log.warn(
`Applied ${totalTransformsApplied} owned change${totalTransformsApplied === 1 ? '' : 's'} across ${totalFilesChanged} file${totalFilesChanged === 1 ? '' : 's'}; protected changes remain.`,
diff --git a/packages/cli/clients/cli/commands/upgrade.doc.mjs b/packages/cli/clients/cli/commands/upgrade.doc.mjs
index 5240f8d6f5..ad296cece1 100644
--- a/packages/cli/clients/cli/commands/upgrade.doc.mjs
+++ b/packages/cli/clients/cli/commands/upgrade.doc.mjs
@@ -116,6 +116,20 @@ export const doc = {
],
related: ['init', 'doctor'],
notes: [
+ {type: 'heading', level: 3, text: 'A CLI older than your Core'},
+ {
+ type: 'prose',
+ text:
+ 'Core codemods ship inside the CLI, so a CLI older than the installed @astryxdesign/core has none for ' +
+ 'the releases after its own version. upgrade then says it cannot finish, never reports your code as up to date, ' +
+ 'and prints the same upgrade pinned to the CLI release that matches your Core, such as ' +
+ '`cd <project> && npx @astryxdesign/cli@<core-version> upgrade --from <old-version> --path <source-dir> --apply`. ' +
+ 'It changes to the folder this run used and names the directory it scanned as an absolute path, both with ' +
+ 'symbolic links resolved, so pasted from any folder it upgrades the same code. It is written for a POSIX shell (sh, bash, zsh), or for PowerShell on Windows, ' +
+ 'with each argument quoted for that shell; cmd.exe is not a target. The codemods this CLI has still run. ' +
+ 'It exits 0, so a script checks the JSON: the result carries `cliBehindCore` with `cliVersion` (the newest release ' +
+ 'this CLI has codemods for) and `command`.',
+ },
{type: 'heading', level: 3, text: 'Protected files'},
{
type: 'prose',
diff --git a/packages/cli/clients/cli/commands/upgrade.older-cli.test.mjs b/packages/cli/clients/cli/commands/upgrade.older-cli.test.mjs
new file mode 100644
index 0000000000..fd1751ca7f
--- /dev/null
+++ b/packages/cli/clients/cli/commands/upgrade.older-cli.test.mjs
@@ -0,0 +1,160 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx upgrade` with a CLI older than the installed Core: the human
+ * output never says the code is up to date, warns once with the same upgrade
+ * pinned to the CLI release that matches the Core, and keeps the exit status;
+ * `--json` carries the same facts in `cliBehindCore`. Pasted anywhere, the
+ * printed command runs that upgrade in the same project.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import {spawnSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+import {CLI_ROOT} from '../../../foundation/fs/paths.mjs';
+import {
+ commandInFolder,
+ getDlxPrefix,
+ quoteCommandArgument,
+} from '../../../foundation/env/package-manager.mjs';
+
+const CLI_VERSION = JSON.parse(
+ fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf8'),
+).version;
+const [MAJOR, MINOR] = CLI_VERSION.split('.').map(Number);
+const NEWER_CORE = `${MAJOR}.${MINOR + 1}.0`;
+const NON_ASCII = /[\u0080-\uFFFF]/;
+
+let tmpDir;
+
+/** @param {string} rel @param {string} body */
+function write(rel, body) {
+ const file = path.join(tmpDir, rel);
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ fs.writeFileSync(file, body);
+}
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-upgrade-older-cli-'));
+ write('package.json', JSON.stringify({name: 'consumer', private: true}));
+ write(
+ 'node_modules/@astryxdesign/core/package.json',
+ JSON.stringify({name: '@astryxdesign/core', version: NEWER_CORE}),
+ );
+ write('src/index.ts', 'export const x = 1;\n');
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/**
+ * The pinned command the CLI prints for this project. It names the folder the
+ * CLI ran in and the source directory as the CLI resolved them.
+ * @param {...string} rest the arguments after `--path <dir>`
+ */
+function pinned(...rest) {
+ const project = fs.realpathSync(tmpDir);
+ return commandInFolder(
+ project,
+ [
+ getDlxPrefix(tmpDir),
+ `@astryxdesign/cli@${NEWER_CORE}`,
+ 'upgrade',
+ '--from',
+ CLI_VERSION,
+ '--path',
+ quoteCommandArgument(path.join(project, 'src')),
+ ...rest,
+ ].join(' '),
+ );
+}
+
+/**
+ * Stand-ins for the package runners: each drops its own words and the pinned
+ * package, then runs this CLI with the rest of the command.
+ */
+const RUNS_THIS_CLI = [
+ ['npx', 1],
+ ['bunx', 1],
+ ['pnpm', 2],
+ ['yarn', 2],
+]
+ .map(
+ ([name, words]) =>
+ `${name}() { shift ${words}; "$0" ${quoteCommandArgument(path.join(CLI_ROOT, 'clients', 'cli', 'bin', 'astryx.mjs'))} "$@"; }`,
+ )
+ .join('; ');
+
+describe('astryx upgrade with a CLI older than the installed Core', () => {
+ it('says it cannot finish and prints the upgrade pinned to the matching CLI', async () => {
+ const r = await runCli(['upgrade', '--from', CLI_VERSION, '--apply'], {
+ cwd: tmpDir,
+ });
+ const output = `${r.stdout}\n${r.stderr}`;
+
+ expect(r.status).toBe(0);
+ expect(output).not.toMatch(/up to date/i);
+ expect(output).not.toContain('No codemods available');
+ expect(r.stderr).toContain(
+ `This CLI (${CLI_VERSION}) is older than the installed @astryxdesign/core (${NEWER_CORE})`,
+ );
+ // The command has a line of its own, so it copies exactly.
+ expect(r.stderr).toContain(
+ `the CLI that matches your Core:\n ${pinned('--apply')}\n`,
+ );
+ expect(r.stdout.trim().split('\n').at(-1)).toBe('Upgrade incomplete');
+ expect(output.split('\n').filter(line => NON_ASCII.test(line))).toEqual([]);
+ });
+
+ it('carries cliBehindCore in --json with the same exit status', async () => {
+ const r = await runCli(['--json', 'upgrade', '--from', CLI_VERSION], {
+ cwd: tmpDir,
+ });
+ const parsed = JSON.parse(r.stdout);
+
+ expect(r.status).toBe(0);
+ expect(parsed.type).toBe('upgrade.status');
+ expect(parsed.data.status).toBe('no_codemods');
+ expect(parsed.data.cliBehindCore).toEqual({
+ cliVersion: CLI_VERSION,
+ command: pinned(),
+ });
+ });
+
+ // Where an upgrade runs decides what it finds: the installed Core is read
+ // from that folder, and --path must stay inside it. Printed without its
+ // folder, the command exited 1 when pasted in a subfolder
+ // (ERR_PATH_TRAVERSAL) or in the folder above (ERR_VERSION_DETECT).
+ it.skipIf(process.platform === 'win32')(
+ 'prints a command that upgrades the same project wherever it is pasted',
+ async () => {
+ write('src/deep/index.ts', 'export const y = 2;\n');
+ const r = await runCli(['--json', 'upgrade', '--from', CLI_VERSION], {
+ cwd: tmpDir,
+ });
+ const {command} = JSON.parse(r.stdout).data.cliBehindCore;
+
+ for (const pastedIn of [
+ path.join(tmpDir, 'src', 'deep'),
+ path.dirname(tmpDir),
+ ]) {
+ const ran = spawnSync(
+ '/bin/sh',
+ ['-c', `${RUNS_THIS_CLI}; ${command}`, process.execPath],
+ {cwd: pastedIn, encoding: 'utf8'},
+ );
+
+ expect(ran.status, ran.stderr).toBe(0);
+ expect(ran.stdout).toContain(`Installed target: ${NEWER_CORE}`);
+ expect(ran.stdout).toContain(
+ `Scanning ${path.join(fs.realpathSync(tmpDir), 'src')} `,
+ );
+ }
+ },
+ 30_000,
+ );
+});
diff --git a/packages/cli/foundation/env/package-manager.mjs b/packages/cli/foundation/env/package-manager.mjs
index 2ddb50fd8b..d3286f4813 100644
--- a/packages/cli/foundation/env/package-manager.mjs
+++ b/packages/cli/foundation/env/package-manager.mjs
@@ -512,3 +512,50 @@ export function formatCliCommand(command, targetDir) {
const stem = getCliInvocation(targetDir);
return sub ? `${stem} ${sub}` : stem;
}
+
+/**
+ * Quote one argument of a printed command so the shell it is pasted into
+ * passes it on unchanged. Printed commands target a POSIX shell (sh, bash,
+ * zsh), and PowerShell on Windows; cmd.exe is not a target. A value made only
+ * of letters, digits and `@ / . _ -` (and, on Windows, a drive path's `:` and
+ * `\`) stays bare. Any other value gets single quotes, inside which both
+ * shells read `$`, backticks, `%`, `!`, spaces and double quotes literally. An
+ * embedded single quote is written `'\''` for a POSIX shell and doubled for
+ * PowerShell, which also ends a single-quoted string at the typographic
+ * quotes `‘ ’ ‚ ‛`, so those are doubled too (`Macy’s` → `'Macy’’s'`).
+ *
+ * @param {string} value
+ * @param {string} [platform] the `process.platform` the command is printed for
+ * @returns {string}
+ */
+export function quoteCommandArgument(value, platform = process.platform) {
+ const text = String(value);
+ if (platform === 'win32') {
+ if (/^[A-Za-z0-9@/._:\\-]+$/u.test(text)) return text;
+ return `'${text.replace(/['\u2018\u2019\u201A\u201B]/gu, quote => quote + quote)}'`;
+ }
+ if (/^[A-Za-z0-9@/._-]+$/u.test(text)) return text;
+ return `'${text.replace(/'/gu, `'\\''`)}'`;
+}
+
+/**
+ * A printed command that changes to `dir`, then runs `command` there, so it
+ * does the same work pasted from any folder. It runs `command` only when the
+ * change worked. For a POSIX shell: `cd <dir> && <command>`. For PowerShell
+ * on Windows: `cd -LiteralPath <dir> -ErrorAction Stop; <command>`, because
+ * `-LiteralPath` reads `[` and `]` in a folder name literally, and a failed
+ * change stops the line in Windows PowerShell 5.1, which has no `&&`, as in
+ * PowerShell 7.
+ *
+ * @param {string} dir an absolute folder
+ * @param {string} command the command to run there, its arguments already
+ * quoted with {@link quoteCommandArgument}
+ * @param {string} [platform] the `process.platform` the command is printed for
+ * @returns {string}
+ */
+export function commandInFolder(dir, command, platform = process.platform) {
+ const folder = quoteCommandArgument(dir, platform);
+ return platform === 'win32'
+ ? `cd -LiteralPath ${folder} -ErrorAction Stop; ${command}`
+ : `cd ${folder} && ${command}`;
+}
diff --git a/packages/cli/foundation/env/package-manager.test.mjs b/packages/cli/foundation/env/package-manager.test.mjs
index bb79c1a79c..601a69ff80 100644
--- a/packages/cli/foundation/env/package-manager.test.mjs
+++ b/packages/cli/foundation/env/package-manager.test.mjs
@@ -1,6 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect, afterEach, vi} from 'vitest';
+import {spawnSync} from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
@@ -12,11 +13,32 @@ import {
cliBinResolves,
getCliInvocation,
formatCliCommand,
+ quoteCommandArgument,
+ commandInFolder,
} from './package-manager.mjs';
let tmpDir;
const ORIGINAL_ARGV1 = process.argv[1];
+/** Prints, as JSON, the folder a command ran in and the arguments it got. */
+const PRINT_RUN =
+ 'process.stdout.write(JSON.stringify({cwd: process.cwd(), argv: process.argv.slice(1)}))';
+
+/** PowerShell, when it is on the PATH: printed commands target it on Windows. */
+const PWSH = (process.env.PATH ?? '')
+ .split(path.delimiter)
+ .flatMap(dir => ['pwsh', 'pwsh.exe'].map(name => path.join(dir, name)))
+ .find(file => isFile(file));
+
+/** @param {string} file */
+function isFile(file) {
+ try {
+ return fs.statSync(file).isFile();
+ } catch {
+ return false;
+ }
+}
+
afterEach(() => {
if (tmpDir) {
fs.rmSync(tmpDir, {recursive: true, force: true});
@@ -48,7 +70,8 @@ const YARN_BERRY_LOCK =
'# This file is generated by running "yarn install" inside your project.\n# Manual changes might be lost - proceed with caution!\n\n__metadata:\n version: 8\n';
/** An installed CLI's entry, outside any runner cache (a global or workspace install). */
-const INSTALLED_ENTRY = '/usr/local/lib/node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs';
+const INSTALLED_ENTRY =
+ '/usr/local/lib/node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs';
describe('detectPackageManager', () => {
it('detects yarn from yarn.lock', () => {
@@ -132,7 +155,10 @@ describe('detectPackageManager', () => {
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');
+ fs.writeFileSync(
+ path.join(dir, '.yarnrc.yml'),
+ 'nodeLinker: node-modules\n',
+ );
expect(detectPackageManager(dir)).toBe('yarn');
});
@@ -425,12 +451,14 @@ describe('isCliOneOff', () => {
});
it('detects a pnpm dlx cache entry', () => {
- process.argv[1] = '/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';
+ process.argv[1] =
+ '/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';
expect(isCliOneOff()).toBe(true);
});
it('detects a bunx cache entry', () => {
- process.argv[1] = '/home/u/.bun/install/cache/@astryxdesign/cli/bin/astryx.mjs';
+ process.argv[1] =
+ '/home/u/.bun/install/cache/@astryxdesign/cli/bin/astryx.mjs';
expect(isCliOneOff()).toBe(true);
});
@@ -538,7 +566,8 @@ describe('getCliInvocation', () => {
});
it('pairs the dlx runner with the scoped package for pnpm one-off', () => {
- process.argv[1] = '/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';
+ process.argv[1] =
+ '/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';
const dir = makeTmpDir();
fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
expect(getCliInvocation(dir)).toBe('pnpm dlx @astryxdesign/cli');
@@ -551,7 +580,9 @@ describe('formatCliCommand', () => {
const dir = makeTmpDir();
fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
linkCliBin(dir);
- expect(formatCliCommand('astryx component Button', dir)).toBe('pnpm exec astryx component Button');
+ expect(formatCliCommand('astryx component Button', dir)).toBe(
+ 'pnpm exec astryx component Button',
+ );
});
it('accepts a bare subcommand (no leading astryx)', () => {
@@ -566,6 +597,162 @@ describe('formatCliCommand', () => {
process.argv[1] = '/home/u/.npm/_npx/a1b2/node_modules/.bin/astryx';
const dir = makeTmpDir();
fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');
- expect(formatCliCommand('astryx component Button', dir)).toBe('npx @astryxdesign/cli component Button');
+ expect(formatCliCommand('astryx component Button', dir)).toBe(
+ 'npx @astryxdesign/cli component Button',
+ );
+ });
+});
+
+describe('quoteCommandArgument', () => {
+ it('leaves a plain value bare', () => {
+ for (const platform of ['linux', 'darwin', 'win32']) {
+ expect(quoteCommandArgument('0.7.1', platform)).toBe('0.7.1');
+ expect(quoteCommandArgument('@acme/widgets', platform)).toBe(
+ '@acme/widgets',
+ );
+ expect(quoteCommandArgument('/home/me/app/src', platform)).toBe(
+ '/home/me/app/src',
+ );
+ }
+ });
+
+ it('single-quotes for a POSIX shell, so $, backticks and double quotes stay literal', () => {
+ expect(quoteCommandArgument('/tmp/my app/src', 'linux')).toBe(
+ "'/tmp/my app/src'",
+ );
+ expect(quoteCommandArgument('/tmp/cost $5/src', 'darwin')).toBe(
+ "'/tmp/cost $5/src'",
+ );
+ expect(quoteCommandArgument('a`id`"b"!', 'linux')).toBe('\'a`id`"b"!\'');
+ expect(quoteCommandArgument("it's", 'linux')).toBe("'it'\\''s'");
+ expect(quoteCommandArgument('C:\\app', 'linux')).toBe("'C:\\app'");
+ expect(quoteCommandArgument('', 'linux')).toBe("''");
+ });
+
+ it('keeps a Windows drive path bare', () => {
+ expect(quoteCommandArgument('C:\\Users\\me\\app\\src', 'win32')).toBe(
+ 'C:\\Users\\me\\app\\src',
+ );
+ });
+
+ // Windows output targets PowerShell, not cmd.exe: PowerShell reads a
+ // single-quoted value literally, `$`, backticks, `%` and `!` included.
+ it('single-quotes for PowerShell on Windows, doubling an embedded quote', () => {
+ expect(quoteCommandArgument('C:\\Users\\Jo Smith\\app\\src', 'win32')).toBe(
+ "'C:\\Users\\Jo Smith\\app\\src'",
+ );
+ expect(quoteCommandArgument('C:\\cost $5 %x% !y\\src', 'win32')).toBe(
+ "'C:\\cost $5 %x% !y\\src'",
+ );
+ expect(quoteCommandArgument('C:\\it\'s `x` "q"', 'win32')).toBe(
+ "'C:\\it''s `x` \"q\"'",
+ );
+ // PowerShell also ends a single-quoted string at ‘ ’ ‚ and ‛.
+ expect(
+ quoteCommandArgument('C:\\Users\\jo\\OneDrive - Macy’s\\app', 'win32'),
+ ).toBe("'C:\\Users\\jo\\OneDrive - Macy’’s\\app'");
+ expect(quoteCommandArgument('‘a’ ‚b‛', 'win32')).toBe("'‘‘a’’ ‚‚b‛‛'");
+ // A POSIX shell reads them literally inside single quotes.
+ expect(quoteCommandArgument('/home/jo/Macy’s app', 'linux')).toBe(
+ "'/home/jo/Macy’s app'",
+ );
+ });
+});
+
+describe('commandInFolder', () => {
+ it('enters the folder, then runs the command only if that worked, in a POSIX shell', () => {
+ expect(commandInFolder('/tmp/my app', 'npx x', 'linux')).toBe(
+ "cd '/tmp/my app' && npx x",
+ );
+ expect(commandInFolder('/srv/app', 'npx x', 'darwin')).toBe(
+ 'cd /srv/app && npx x',
+ );
+ });
+
+ it('enters the folder literally and stops if it cannot, in PowerShell', () => {
+ expect(commandInFolder('C:\\a[1] b', 'npx x', 'win32')).toBe(
+ "cd -LiteralPath 'C:\\a[1] b' -ErrorAction Stop; npx x",
+ );
+ });
+
+ it.skipIf(process.platform === 'win32')(
+ 'runs in the folder with every argument unchanged, pasted into /bin/sh elsewhere',
+ () => {
+ const root = makeTmpDir();
+ const project = path.join(root, 'it\'s Macy’s ‘q’ $5 %x% !y `z` "q" [1]');
+ fs.mkdirSync(project);
+ const args = [path.join(project, 'src'), 'a$b c', "it's", '@scope/pkg@1'];
+ const command = commandInFolder(
+ project,
+ ['npx', ...args.map(arg => quoteCommandArgument(arg, 'linux'))].join(
+ ' ',
+ ),
+ 'linux',
+ );
+ const ran = spawnSync(
+ '/bin/sh',
+ [
+ '-c',
+ `npx() { "$0" -e '${PRINT_RUN}' -- "$@"; }; ${command}`,
+ process.execPath,
+ ],
+ {cwd: root, encoding: 'utf8'},
+ );
+
+ expect(ran.status, ran.stderr).toBe(0);
+ expect(JSON.parse(ran.stdout)).toEqual({
+ cwd: fs.realpathSync(project),
+ argv: args,
+ });
+ },
+ );
+
+ describe.runIf(PWSH)('in PowerShell, where it is installed', () => {
+ it('runs in the folder with every argument unchanged', () => {
+ const root = makeTmpDir();
+ const project = path.join(root, 'it\'s Macy’s ‘q’ $5 %x% !y `z` "q" [1]');
+ fs.mkdirSync(project);
+ const args = [path.join(project, 'src'), 'a$b c', "it's", '@scope/pkg@1'];
+ const command = commandInFolder(
+ project,
+ ['npx', ...args.map(arg => quoteCommandArgument(arg, 'win32'))].join(
+ ' ',
+ ),
+ 'win32',
+ );
+ const npx = `function npx { & ${quoteCommandArgument(process.execPath, 'win32')} -e '${PRINT_RUN}' -- @args }`;
+ const ran = spawnSync(
+ /** @type {string} */ (PWSH),
+ ['-NoProfile', '-NonInteractive', '-Command', `${npx}; ${command}`],
+ {cwd: root, encoding: 'utf8'},
+ );
+
+ expect(ran.status, ran.stderr).toBe(0);
+ expect(JSON.parse(ran.stdout)).toEqual({
+ cwd: fs.realpathSync(project),
+ argv: args,
+ });
+ });
+
+ it('stops when the folder cannot be entered', () => {
+ const root = makeTmpDir();
+ const command = commandInFolder(
+ path.join(root, 'missing'),
+ 'npx',
+ 'win32',
+ );
+ const ran = spawnSync(
+ /** @type {string} */ (PWSH),
+ [
+ '-NoProfile',
+ '-NonInteractive',
+ '-Command',
+ `function npx { 'RAN' }; ${command}`,
+ ],
+ {cwd: root, encoding: 'utf8'},
+ );
+
+ expect(ran.stdout).not.toContain('RAN');
+ });
});
});
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 786d25d6ac..89fa26b7a4 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -283,12 +283,12 @@ export const doc = {
{
value: 'upgrade.status',
description:
- 'A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary.',
+ 'A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. no_codemods and config_fixable carry cliBehindCore ({cliVersion, command}) when the installed Core is newer than the CLI, which then has no codemods for the releases after its own version.',
},
{
value: 'upgrade.run',
description:
- 'The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors.',
+ 'The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run.',
},
// manifest