Skip to content

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

TypeScript

refactor(cli): split upgrade into api/upgrade leaf shape (#4486)

Joeye9a579a40e84
diff --git a/.changeset/cli-upgrade-leaves.md b/.changeset/cli-upgrade-leaves.md
new file mode 100644
index 0000000000..cc8951d87c
--- /dev/null
+++ b/.changeset/cli-upgrade-leaves.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[refactor] CLI: upgrade reorganized into api/upgrade leaf shape — the flat pipeline is split into a dispatcher+barrel (`upgrade.mjs`), a shared `_adapter.mjs` (version detection + agent-docs refresh + codemod selection/execution machinery), and `list`/`status`/`run` leaves (`upgrade.list` | `upgrade.status` | `upgrade.run`). Pure reorg: the `./api` barrel + CLI consumer are unchanged, and both the human output and `--json` envelopes are byte-identical.
+@josephfarina
diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjs
new file mode 100644
index 0000000000..468a4fff08
--- /dev/null
+++ b/packages/cli/api/upgrade/_adapter.mjs
@@ -0,0 +1,348 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file upgrade adapter — shared version-detection + codemod machinery.
+ *
+ * The engine the upgrade leaves (list/status/run) sit on. It owns the I/O and
+ * resolution for the command: detecting the installed core version, refreshing
+ * the managed agent-docs block, selecting codemods from the registry, loading
+ * the consumer's project/integrations, and executing the core/integration
+ * codemod runners. Leaves call these helpers and PROJECT the results into their
+ * one response type; the dispatcher (`upgrade.mjs`) routes.
+ *
+ * Progress is emitted through an injected `logger` (silent by default), so the
+ * CLI keeps its exact output while a programmatic caller stays quiet.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {execFile} from 'node:child_process';
+import {promisify} from 'node:util';
+import {ensureJscodeshift} from '../../codemods/ensure-jscodeshift.mjs';
+import {getTransformsBetween, latestVersion} from '../../codemods/registry.mjs';
+import {runCodemods} from '../../codemods/runner.mjs';
+import {
+ discoverIntegrationCodemods,
+ selectIntegrationCodemods,
+} from '../../codemods/integration-discovery.mjs';
+import {runIntegrationCodemods} from '../../codemods/integration-runner.mjs';
+import {installAgentDocs, inspectAgentDocs} from '../../lib/agent-docs/agent-docs.mjs';
+import {formatCliCommand} from '../../utils/package-manager.mjs';
+import {Project} from '../../lib/project.mjs';
+import {loadIntegrations} from '../../lib/integrations.mjs';
+import {warnOnIntegrationIssues} from '../../lib/integration-warnings.mjs';
+import {noopLogger} from '../../lib/term-log.mjs';
+
+const execFileAsync = promisify(execFile);
+
+/**
+ * @typedef {object} CoreTransformEntry
+ * @property {string} name
+ * @property {import('../../types/codemod').CodemodTransform} transform
+ * @property {{title: string, description?: string, pr?: string, codemodType?: string}} meta
+ * @property {boolean} [optional]
+ */
+/** @typedef {{version: string, transforms: CoreTransformEntry[]}} CoreVersionManifest */
+
+/**
+ * @typedef {object} UpgradeOptions
+ * @property {boolean} [list]
+ * @property {string} [from]
+ * @property {boolean} [apply]
+ * @property {boolean} [force]
+ * @property {string} [codemod]
+ * @property {string[]} [skipCodemod]
+ * @property {string[]} [integration]
+ * @property {string} [path]
+ * @property {boolean} [installDeps]
+ */
+
+/**
+ * Detect the installed target version from node_modules.
+ * @param {string} cwd
+ * @returns {{version: string, packageName: string}|null}
+ */
+export function detectInstalledTargetVersion(cwd) {
+ for (const packageName of ['@astryxdesign/core', '@xds/core']) {
+ const pkgPath = path.resolve(
+ cwd,
+ 'node_modules',
+ ...packageName.split('/'),
+ 'package.json',
+ );
+ try {
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
+ if (pkg.version) return {version: pkg.version, packageName};
+ } catch {
+ // Missing/unreadable — try the next supported package name.
+ }
+ }
+ return null;
+}
+
+/**
+ * @param {(string | null | undefined | false)[] | undefined} files
+ * @returns {string[]}
+ */
+export function uniqueFiles(files) {
+ return [
+ ...new Set(
+ (files ?? []).filter(/** @returns {f is string} */ f => Boolean(f)),
+ ),
+ ];
+}
+
+/**
+ * Run the app config's post-codemod hooks (config.hooks.postCodemod).
+ * Dry-run PREVIEWS (buildCommand still called, so a throw fails); apply executes.
+ * @param {import('../../types/config').PostCodemodHook[]} hooks
+ * @param {{packageDir: string, files: string[], apply: boolean}} context
+ * @param {import('../../lib/term-log.mjs').CliLogger} logger
+ */
+export async function runPostCodemodHooks(hooks, context, logger) {
+ if (!hooks || hooks.length === 0) return;
+ const {packageDir, files, apply} = context;
+
+ for (let i = 0; i < hooks.length; i++) {
+ const hook = hooks[i];
+ const label = hook.name ?? `postCodemod[${i}]`;
+ if (typeof hook.buildCommand !== 'function') {
+ throw new Error(
+ `Post-codemod hook ${label} is missing a buildCommand function.`,
+ );
+ }
+
+ const cmd = await hook.buildCommand({packageDir, files});
+ if (!cmd) {
+ logger.info(`Post-codemod hook ${label} produced no command; skipping.`);
+ continue;
+ }
+
+ if (!apply) {
+ const preview = [cmd.command, ...(cmd.args ?? [])].join(' ');
+ logger.info(`Post-codemod hook ${label} (dry run): ${preview}`);
+ continue;
+ }
+
+ await execFileAsync(
+ cmd.command,
+ cmd.args ?? [],
+ /** @type {import('node:child_process').ExecFileOptions & {encoding: 'utf-8'}} */ ({
+ cwd: cmd.options?.cwd ?? packageDir,
+ timeout: cmd.options?.timeout ?? 300_000,
+ stdio: 'pipe',
+ encoding: 'utf-8',
+ ...cmd.options,
+ env: {...process.env, ...(cmd.options?.env ?? {})},
+ }),
+ );
+ logger.success(`Post-codemod hook ${label} completed.`);
+ }
+}
+
+/**
+ * Refresh (or, in dry-run, report) the managed agent-docs block after a version
+ * bump. The block documents the INSTALLED library, so it must be re-synced on
+ * EVERY upgrade path, including the no-codemods short-circuits (#4168).
+ *
+ * @param {{cwd: string, installedVersion: string, apply: boolean, logger?: import('../../lib/term-log.mjs').CliLogger}} ctx
+ * @returns {import('../../types/upgrade').AgentDocsSummary}
+ */
+export function refreshAgentDocs({cwd, installedVersion, apply, logger = noopLogger}) {
+ const inspection = inspectAgentDocs(cwd, installedVersion);
+ /** @type {import('../../types/upgrade').AgentDocsSummary} */
+ const summary = {
+ status: inspection.status,
+ installedVersion,
+ fromVersions: inspection.blockVersions,
+ files: [],
+ refreshed: false,
+ action: 'none',
+ };
+
+ // Never initialized — don't silently create docs during an upgrade; nudge.
+ if (inspection.status === 'missing') {
+ summary.action = 'nudge-init';
+ logger.warn(
+ `No Astryx agent-docs block found — AI agents have no component index. Run \`${formatCliCommand('astryx init --features agents')}\` to install it.`,
+ );
+ return summary;
+ }
+
+ if (inspection.status === 'current') return summary;
+
+ // Stale.
+ summary.files = inspection.staleFiles;
+ const fromLabel = summary.fromVersions.length
+ ? `v${summary.fromVersions.join(', v')}`
+ : 'an unknown version';
+
+ if (!apply) {
+ summary.action = 'would-refresh';
+ logger.warn(
+ `Agent docs are stale: block is at ${fromLabel}, installed is v${installedVersion}. Re-run with --apply to refresh (${summary.files.join(', ')}).`,
+ );
+ return summary;
+ }
+
+ // Apply: rewrite only files that already carry a marker (onlyReplace).
+ try {
+ const written = installAgentDocs(cwd, {onlyReplace: true});
+ summary.refreshed = written.length > 0;
+ summary.files = written;
+ if (summary.refreshed) {
+ summary.action = 'refreshed';
+ logger.success(
+ `Agent docs refreshed → v${installedVersion} (from ${fromLabel}): ${written.join(', ')}`,
+ );
+ } else {
+ summary.action = 'error';
+ logger.warn(
+ `Agent docs look stale but couldn't be refreshed — the <!-- ASTRYX:START -->/<!-- ASTRYX:END --> markers may be malformed. Run \`${formatCliCommand('astryx init --features agents')}\` to reinstall the block.`,
+ );
+ }
+ } catch {
+ summary.action = 'error';
+ logger.warn(
+ `Could not refresh agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,
+ );
+ }
+ return summary;
+}
+
+/**
+ * Every registered codemod (oldest→newest) for `upgrade --list`. Registry walk
+ * + flatten; nothing is run.
+ * @returns {Promise<Array<{name: string, title: string, version: string, pr?: string, optional: boolean}>>}
+ */
+export async function collectAllCodemods() {
+ const codemods = [];
+ const manifests = /** @type {CoreVersionManifest[]} */ (
+ await getTransformsBetween('0.0.0', latestVersion)
+ );
+ for (const {version, transforms} of manifests) {
+ for (const {name, meta, optional} of transforms) {
+ codemods.push({name, title: meta.title, version, pr: meta.pr, optional: !!optional});
+ }
+ }
+ return codemods;
+}
+
+/**
+ * Core version manifests for the (from, to] range.
+ * @param {string} from
+ * @param {string} to
+ * @returns {Promise<CoreVersionManifest[]>}
+ */
+export async function getCoreVersionManifests(from, to) {
+ return /** @type {CoreVersionManifest[]} */ ([
+ ...(await getTransformsBetween(from, to)),
+ ]);
+}
+
+/**
+ * Ensure jscodeshift is available before running codemods.
+ * @param {{installDeps?: boolean, logger?: import('../../lib/term-log.mjs').CliLogger}} [options]
+ * @returns {Promise<boolean>}
+ */
+export async function ensureCodemodDeps({installDeps, logger = noopLogger} = {}) {
+ return ensureJscodeshift({installDeps, silent: logger === noopLogger});
+}
+
+/**
+ * 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>, logger?: import('../../lib/term-log.mjs').CliLogger}} options
+ */
+export async function runCoreCodemods(versionManifests, {apply, path: srcPath, codemod, skipCodemods, logger = noopLogger}) {
+ return runCodemods(versionManifests, {
+ apply,
+ path: srcPath,
+ codemod,
+ skipCodemods,
+ silent: logger === noopLogger,
+ });
+}
+
+/**
+ * Load the consumer project's config + integrations. Throws on invalid config;
+ * the run leaf decides between the config_fixable preview and a hard abort.
+ * @param {string} cwd
+ * @param {string[]} [extraIntegrationSpecs] explicit `--integration` specs
+ * @returns {Promise<{postCodemodHooks: import('../../types/config').PostCodemodHook[], integrations: import('../../lib/integrations.mjs').LoadedIntegration[]}>}
+ */
+export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {
+ const project = await Project.load(cwd);
+ const postCodemodHooks = project.config.hooks?.postCodemod ?? [];
+ const integrationSpecs = uniqueFiles([
+ ...(project.integrations ?? []),
+ ...(extraIntegrationSpecs ?? []),
+ ]);
+ const integrations = await loadIntegrations(integrationSpecs);
+ return {postCodemodHooks, integrations};
+}
+
+/**
+ * Non-blocking nudge for integration validation issues. Never throws (a broken
+ * nudge must not fail the upgrade) and is suppressed for --json/programmatic
+ * callers (the silent logger).
+ * @param {Array<import('../../lib/integrations.mjs').LoadedIntegration>} integrations
+ * @param {import('../../lib/term-log.mjs').CliLogger} [logger]
+ * @returns {Promise<void>}
+ */
+export async function warnIntegrationIssues(integrations, logger = noopLogger) {
+ try {
+ await warnOnIntegrationIssues(integrations, {json: logger === noopLogger});
+ } catch {
+ // Never let the nudge break the upgrade.
+ }
+}
+
+/**
+ * Discover + select the integration codemods that apply in the (from, to]
+ * range. An integration whose codemods fail to load is SKIPPED (a definition
+ * error is surfaced by the nudge, not a hard failure of the upgrade).
+ * @param {Array<import('../../lib/integrations.mjs').LoadedIntegration>} integrations
+ * @param {string} from
+ * @param {string} to
+ * @returns {Promise<Array<{version: string, codemods: import('../../types/codemod').CodemodEntry[]}>>}
+ */
+export async function selectIntegrationCodemodsFor(integrations, from, to) {
+ /** @type {Map<string, Array<import('../../types/codemod').CodemodEntry>>} */
+ const integrationCodemodsByVersion = new Map();
+ for (const integration of integrations) {
+ if (!integration?.codemods) continue;
+ try {
+ const byVersion = await discoverIntegrationCodemods([integration]);
+ for (const [version, rawList] of byVersion) {
+ const list = /** @type {Array<import('../../types/codemod').CodemodEntry>} */ (/** @type {unknown} */ (rawList));
+ const existing = integrationCodemodsByVersion.get(version);
+ if (existing) existing.push(...list);
+ else integrationCodemodsByVersion.set(version, [...list]);
+ }
+ } catch {
+ // Skip this integration's codemods (definition error); nudge above surfaces it.
+ }
+ }
+ return /** @type {Array<{version: string, codemods: import('../../types/codemod').CodemodEntry[]}>} */ (
+ selectIntegrationCodemods(integrationCodemodsByVersion, from, to)
+ );
+}
+
+/**
+ * Run the file-based INTEGRATION codemods (config codemods first, then code).
+ * @param {Array<{version: string, codemods: import('../../types/codemod').CodemodEntry[]}>} versionGroups
+ * @param {{apply: boolean, path: string, codemod?: string, skipCodemods: Set<string>, logger?: import('../../lib/term-log.mjs').CliLogger}} options
+ */
+export async function runIntegrationCodemodsStep(versionGroups, {apply, path: srcPath, codemod, skipCodemods, logger = noopLogger}) {
+ const jscodeshift = (await import('jscodeshift')).default;
+ return runIntegrationCodemods(versionGroups, {
+ apply,
+ path: srcPath,
+ codemod,
+ skipCodemods,
+ jscodeshift,
+ silent: logger === noopLogger,
+ });
+}
diff --git a/packages/cli/api/upgrade/list/list.mjs b/packages/cli/api/upgrade/list/list.mjs
new file mode 100644
index 0000000000..328921d872
--- /dev/null
+++ b/packages/cli/api/upgrade/list/list.mjs
@@ -0,0 +1,30 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file upgrade.list leaf — the available codemods, nothing run.
+ *
+ * Projects the registry walk (`_adapter.collectAllCodemods`) into the public
+ * list entries (name/title/version/optional) and emits the human listing
+ * through the injected `logger`. No cwd, no version detection, no side effects.
+ */
+
+import {collectAllCodemods} from '../_adapter.mjs';
+import {noopLogger} from '../../../lib/term-log.mjs';
+
+/**
+ * List every available codemod (oldest→newest).
+ * @param {{logger?: import('../../../lib/term-log.mjs').CliLogger}} [ctx]
+ * @returns {Promise<import('../../../types/upgrade').UpgradeListResponse>}
+ */
+export async function list({logger = noopLogger} = {}) {
+ const codemods = await collectAllCodemods();
+ logger.step('Available codemods:');
+ for (const {name, title, pr, optional} of codemods) {
+ logger.info(` ${name} — ${title}${optional ? ' (optional)' : ''} (${pr})`);
+ }
+ logger.outro('Done');
+ return {
+ type: 'upgrade.list',
+ data: codemods.map(({name, title, version, optional}) => ({name, title, version, optional})),
+ };
+}
diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjs
new file mode 100644
index 0000000000..a5e04e9747
--- /dev/null
+++ b/packages/cli/api/upgrade/run/run.mjs
@@ -0,0 +1,255 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file upgrade.run leaf — the terminal, side-effecting run receipt.
+ *
+ * Orchestrates the non-list upgrade pipeline over the shared `_adapter.mjs`
+ * machinery and returns the run receipt. It also OWNS the two mid-pipeline
+ * short-circuits that resolve to `upgrade.status` (no_codemods, config_fixable)
+ * plus the early up_to_date exit — each delegated to the `status` leaf so the
+ * status envelope + its human lines live in one place.
+ *
+ * Pipeline (--apply): detect installed core → refresh agent-docs (every path) →
+ * run CORE codemods (before Project.load, so a core CONFIG codemod can repair an
+ * otherwise-invalid config) → load config → discover + run INTEGRATION codemods
+ * → post-codemod hooks. Integration DISCOVERY errors skip that integration;
+ * EXECUTION errors abort. Errors throw AstryxError (stable code); human progress
+ * is emitted through the injected `logger` (silent by default).
+ */
+
+import * as path from 'node:path';
+import {
+ detectInstalledTargetVersion,
+ refreshAgentDocs,
+ uniqueFiles,
+ runPostCodemodHooks,
+ getCoreVersionManifests,
+ ensureCodemodDeps,
+ runCoreCodemods,
+ loadProjectContext,
+ warnIntegrationIssues,
+ selectIntegrationCodemodsFor,
+ runIntegrationCodemodsStep,
+} from '../_adapter.mjs';
+import {
+ statusUpToDate,
+ statusNoCodemods,
+ statusConfigFixable,
+} from '../status/status.mjs';
+import {semverGte} from '../../../utils/semver.mjs';
+import {getCliInvocation} from '../../../utils/package-manager.mjs';
+import {ERROR_CODES} from '../../../lib/error-codes.mjs';
+import {AstryxError} from '../../error.mjs';
+import {noopLogger} from '../../../lib/term-log.mjs';
+
+/**
+ * Run the upgrade pipeline for a validated, non-list invocation. Returns the
+ * terminal run receipt, or one of the status short-circuits; throws AstryxError
+ * on failure. Progress is emitted through `logger` (silent by default).
+ *
+ * @param {import('../_adapter.mjs').UpgradeOptions} [options]
+ * @param {{cwd?: string, logger?: import('../../../lib/term-log.mjs').CliLogger}} [ctx]
+ * @returns {Promise<import('../../../types/upgrade').UpgradeStatusResponse | import('../../../types/upgrade').UpgradeRunResponse>}
+ */
+export async function run(options = {}, {cwd = process.cwd(), logger = noopLogger} = {}) {
+ // Resolve the source dir against the API's cwd (not process.cwd()) so a
+ // programmatic caller in another directory scans the right tree. The runners
+ // do path.resolve(srcPath); an already-absolute path is idempotent there, so
+ // this is byte-identical for the CLI (where cwd === process.cwd()).
+ const path_ = path.resolve(cwd, options.path ?? './src');
+ const apply = options.apply ?? false;
+
+ const currentVersion = /** @type {string} */ (options.from);
+ const installed = detectInstalledTargetVersion(cwd);
+ if (!installed) {
+ const msg = `Could not find installed @astryxdesign/core (or legacy @xds/core). Install the target version first, then rerun \`${getCliInvocation()} upgrade --from <old-version>\`.`;
+ logger.error(msg);
+ logger.outro('Aborted');
+ throw new AstryxError(msg, undefined, ERROR_CODES.ERR_VERSION_DETECT);
+ }
+ const targetVersion = installed.version;
+
+ logger.info(`From version: ${currentVersion}`);
+ logger.info(`Installed target: ${targetVersion} (${installed.packageName})`);
+
+ // Sync the managed agent-docs block FIRST — it documents the installed library
+ // independent of codemods, so refresh on every path (issue #4168).
+ const agentDocs = refreshAgentDocs({cwd, installedVersion: targetVersion, apply: apply || false, logger});
+
+ if (!options.force && semverGte(currentVersion, targetVersion)) {
+ return statusUpToDate({from: currentVersion, to: targetVersion, agentDocs}, logger);
+ }
+
+ const versionManifests = await getCoreVersionManifests(currentVersion, targetVersion);
+
+ const coreConfigCodemodNames = [];
+ for (const {transforms} of versionManifests) {
+ for (const t of transforms) {
+ if (options.codemod && t.name !== options.codemod) continue;
+ if (t.meta?.codemodType === 'config') coreConfigCodemodNames.push(t.name);
+ }
+ }
+ const hasCoreConfigCodemod = coreConfigCodemodNames.length > 0;
+
+ const skipCodemods = new Set(options.skipCodemod ?? []);
+
+ let totalTransforms = 0;
+ let totalOptional = 0;
+ for (const {transforms} of versionManifests) {
+ for (const t of transforms) {
+ if (options.codemod && t.name !== options.codemod) continue;
+ if (skipCodemods.has(t.name)) continue;
+ if (t.optional && !options.codemod) totalOptional++;
+ else totalTransforms++;
+ }
+ }
+
+ const ready = await ensureCodemodDeps({installDeps: options.installDeps, logger});
+ if (!ready) {
+ const msg = 'jscodeshift is required but could not be installed.';
+ logger.outro('Aborted');
+ throw new AstryxError(msg, undefined, ERROR_CODES.ERR_DEP_MISSING);
+ }
+
+ // CORE codemods run FIRST (before loading config) so a core CONFIG codemod can
+ // repair a config the strict loader would otherwise reject.
+ const codemodResult = await runCoreCodemods(versionManifests, {
+ apply,
+ path: path_,
+ codemod: options.codemod,
+ skipCodemods,
+ logger,
+ });
+ const coreResult = codemodResult && 'totalFilesChanged' in codemodResult ? codemodResult : null;
+
+ /** @type {Array<import('../../../lib/integrations.mjs').LoadedIntegration>} */
+ let integrations;
+ /** @type {import('../../../types/config').PostCodemodHook[]} */
+ let postCodemodHooks;
+ try {
+ const projectContext = await loadProjectContext(cwd, options.integration ?? []);
+ postCodemodHooks = projectContext.postCodemodHooks;
+ integrations = projectContext.integrations;
+ } catch (err) {
+ const configErr = /** @type {Error} */ (err);
+ // Graceful dry-run catch: a config that fails strict validation is expected
+ // & fixable ONLY when dry-run AND a pending core config codemod previewed a
+ // change (the codemod that would repair it).
+ const codemodWouldFixConfig = hasCoreConfigCodemod && (coreResult?.totalFilesChanged ?? 0) > 0;
+ if (!apply && codemodWouldFixConfig) {
+ return statusConfigFixable(
+ {
+ from: currentVersion,
+ to: targetVersion,
+ configError: configErr.message,
+ configCodemods: coreConfigCodemodNames,
+ agentDocs,
+ },
+ logger,
+ );
+ }
+ // Genuine config error: abort.
+ logger.error(configErr.message);
+ logger.outro('Aborted');
+ throw new AstryxError(configErr.message, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);
+ }
+
+ if (integrations.length > 0) {
+ logger.info(`Integrations: ${integrations.map(i => i.name ?? i.__spec).join(', ')}`);
+ }
+
+ // Non-blocking nudge for integration validation issues (suppressed for
+ // programmatic/--json callers, i.e. the silent logger).
+ await warnIntegrationIssues(integrations, logger);
+
+ const integrationVersionGroups = await selectIntegrationCodemodsFor(
+ integrations,
+ currentVersion,
+ targetVersion,
+ );
+ const hasIntegrationCodemods = integrationVersionGroups.some(g => g.codemods.length > 0);
+
+ for (const {codemods} of integrationVersionGroups) {
+ for (const c of codemods) {
+ if (options.codemod && c.id !== options.codemod) continue;
+ if (skipCodemods.has(c.id)) continue;
+ if (c.codemod.isOptional && !options.codemod) totalOptional++;
+ else totalTransforms++;
+ }
+ }
+
+ if (versionManifests.length === 0 && !hasIntegrationCodemods) {
+ return statusNoCodemods({from: currentVersion, to: targetVersion, agentDocs}, logger);
+ }
+
+ if (totalTransforms === 0 && totalOptional === 0) {
+ const msg = `Codemod "${options.codemod}" not found. Use --list to see available codemods.`;
+ logger.error(msg);
+ logger.outro('Aborted');
+ throw new AstryxError(msg, undefined, ERROR_CODES.ERR_UNKNOWN_CODEMOD);
+ }
+
+ if (totalTransforms > 0) {
+ logger.step(`${totalTransforms} codemod${totalTransforms === 1 ? '' : 's'} to run${apply ? '' : ' (dry run)'}`);
+ } else {
+ logger.step('No automatic codemods to run for this version range.');
+ }
+
+ /**
+ * @type {{from: string, to: string, codemods: number, integrations: string[], agentDocsRefreshed: boolean, agentDocs: import('../../../types/upgrade').AgentDocsSummary, filesChanged?: number, transformsApplied?: number, errors?: Array<{file: string, codemod: string, error: string}>}}
+ */
+ const receipt = {
+ from: currentVersion,
+ to: targetVersion,
+ codemods: totalTransforms,
+ integrations: integrations.map(i => i.name ?? i.__spec),
+ agentDocsRefreshed: agentDocs.refreshed,
+ agentDocs,
+ };
+
+ let integrationResult = null;
+ if (hasIntegrationCodemods) {
+ logger.step('Applying integration codemods...');
+ integrationResult = await runIntegrationCodemodsStep(integrationVersionGroups, {
+ apply,
+ path: path_,
+ codemod: options.codemod,
+ skipCodemods,
+ logger,
+ });
+ }
+
+ const mergedFilesChanged = (coreResult?.totalFilesChanged ?? 0) + (integrationResult?.totalFilesChanged ?? 0);
+ const mergedTransformsApplied = (coreResult?.totalTransformsApplied ?? 0) + (integrationResult?.totalTransformsApplied ?? 0);
+ const mergedWrittenFiles = [...(coreResult?.writtenFiles ?? []), ...(integrationResult?.writtenFiles ?? [])];
+ const mergedErrors = [...(coreResult?.errors ?? []), ...(integrationResult?.errors ?? [])];
+
+ if (postCodemodHooks.length > 0 && mergedFilesChanged > 0) {
+ const files = uniqueFiles(mergedWrittenFiles).map(file => path.relative(cwd, file));
+ try {
+ await runPostCodemodHooks(postCodemodHooks, {packageDir: cwd, files, apply: apply || false}, logger);
+ } catch (err) {
+ const hookErr = /** @type {Error} */ (err);
+ const msg = `Post-codemod hook failed: ${hookErr.message}`;
+ logger.error(msg);
+ logger.outro('Upgrade failed');
+ throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
+ }
+ }
+
+ receipt.filesChanged = mergedFilesChanged;
+ receipt.transformsApplied = mergedTransformsApplied;
+ receipt.errors = mergedErrors;
+
+ if (receipt.errors?.length > 0) {
+ const msg = `Upgrade completed with ${receipt.errors.length} codemod error${receipt.errors.length === 1 ? '' : 's'}.`;
+ logger.outro('Upgrade failed');
+ throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
+ }
+
+ logger.outro(apply ? 'Upgrade complete' : 'Dry run complete');
+ return {
+ type: 'upgrade.run',
+ data: /** @type {import('../../../types/upgrade').UpgradeRunResponse['data']} */ (/** @type {unknown} */ (receipt)),
+ };
+}
diff --git a/packages/cli/api/upgrade/status/status.mjs b/packages/cli/api/upgrade/status/status.mjs
new file mode 100644
index 0000000000..312d0cff0f
--- /dev/null
+++ b/packages/cli/api/upgrade/status/status.mjs
@@ -0,0 +1,80 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file upgrade.status leaf — the short-circuit results of the upgrade pipeline.
+ *
+ * Three status variants, each a projection of state the `run` leaf has already
+ * resolved (via `_adapter.mjs`) at the point it decides not to run codemods:
+ * - `up_to_date` — `--from` is >= the installed target and no `--force`.
+ * - `no_codemods` — no core/integration codemods apply to the range.
+ * - `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.
+ *
+ * These builders own the exact human progress lines for their path (emitted via
+ * the injected `logger`) and return the `upgrade.status` envelope; the caller
+ * just returns what they hand back.
+ */
+
+import {formatCliCommand} from '../../../utils/package-manager.mjs';
+import {noopLogger} from '../../../lib/term-log.mjs';
+
+/**
+ * `--from` is at/after the installed target (and no `--force`): nothing to run.
+ * @param {{from: string, to: string, agentDocs: import('../../../types/upgrade').AgentDocsSummary}} data
+ * @param {import('../../../lib/term-log.mjs').CliLogger} [logger]
+ * @returns {import('../../../types/upgrade').UpgradeStatusResponse}
+ */
+export function statusUpToDate({from, to, agentDocs}, logger = noopLogger) {
+ logger.success('Already up to date — no codemods to run.');
+ logger.info('Use --force to run codemods anyway.');
+ logger.outro('Done');
+ return {type: 'upgrade.status', data: {status: 'up_to_date', from, to, agentDocs}};
+}
+
+/**
+ * No core or integration codemods apply to the requested version range.
+ * @param {{from: string, to: string, agentDocs: import('../../../types/upgrade').AgentDocsSummary}} data
+ * @param {import('../../../lib/term-log.mjs').CliLogger} [logger]
+ * @returns {import('../../../types/upgrade').UpgradeStatusResponse}
+ */
+export function statusNoCodemods({from, to, agentDocs}, logger = noopLogger) {
+ logger.success('No codemods available for this version range.');
+ logger.outro('Done');
+ return {type: 'upgrade.status', data: {status: 'no_codemods', from, to, agentDocs}};
+}
+
+/**
+ * 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('../../../types/upgrade').AgentDocsSummary}} data
+ * @param {import('../../../lib/term-log.mjs').CliLogger} [logger]
+ * @returns {import('../../../types/upgrade').UpgradeStatusResponse}
+ */
+export function statusConfigFixable({from, to, configError, configCodemods, agentDocs}, logger = noopLogger) {
+ const codemodFlags = configCodemods.map(name => `--codemod ${name}`).join(' ');
+ const suggestedCommand = `astryx upgrade --from ${from} ${codemodFlags} --apply`;
+ const guidance =
+ 'Your astryx.config currently fails strict validation, but a pending ' +
+ 'config codemod would repair it. This dry run previewed the fix without ' +
+ 'writing. Re-run with --apply to apply it, or run just the config codemod(s) ' +
+ 'now:';
+ logger.warn(guidance);
+ logger.info(` ${formatCliCommand(suggestedCommand)}`);
+ logger.info('Integrations are skipped in this preview; they will be processed on the --apply run.');
+ logger.outro('Dry run complete');
+ return {
+ type: 'upgrade.status',
+ data: {
+ status: 'config_fixable',
+ from,
+ to,
+ configError,
+ configCodemods,
+ suggestedCommand,
+ message: guidance,
+ note: 'Integrations are skipped in this preview; they will be processed on the --apply run.',
+ agentDocs,
+ },
+ };
+}
diff --git a/packages/cli/api/upgrade/upgrade.mjs b/packages/cli/api/upgrade/upgrade.mjs
index 6ced55729f..1b61d0b6e7 100644
--- a/packages/cli/api/upgrade/upgrade.mjs
+++ b/packages/cli/api/upgrade/upgrade.mjs
@@ -1,226 +1,41 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file upgrade API — full version-to-version upgrade pipeline.
+ * @file upgrade API — dispatcher + barrel over the upgrade leaves.
*
* `upgrade(options)` runs codemods that migrate source from a previous Astryx
* version to the currently installed one, and refreshes the managed agent-docs
- * block. It performs the side effects (in `--apply`) and returns a receipt:
- * - `upgrade.list` — available codemods (no run)
- * - `upgrade.status` — up_to_date | no_codemods | config_fixable short-circuits
- * - `upgrade.run` — the terminal run receipt
- * Errors throw AstryxError (stable code). Human progress is emitted through the
- * injected `logger` (silent by default), so the CLI keeps its exact output and
- * a programmatic caller stays quiet.
+ * block. It is the single entry the CLI calls; it validates the invocation and
+ * routes to one leaf, each of which returns its `{type, data}` envelope:
+ * - `list` (api/upgrade/list) → upgrade.list — available codemods, no run
+ * - `run` (api/upgrade/run) → upgrade.run — the terminal run receipt,
+ * plus the up_to_date / no_codemods / config_fixable short-circuits it
+ * delegates to the `status` leaf → upgrade.status
*
- * Pipeline (--apply): detect installed core → refresh agent-docs (every path) →
- * run CORE codemods (before Project.load, so a core CONFIG codemod can repair an
- * otherwise-invalid config) → load config → discover + run INTEGRATION codemods
- * → post-codemod hooks. Integration DISCOVERY errors skip that integration;
- * EXECUTION errors abort.
+ * Shared version-detection + codemod selection/execution I/O lives in
+ * `_adapter.mjs` (the leaves project its results). Errors throw AstryxError
+ * (stable code). Human progress is emitted through the injected `logger`
+ * (silent by default), so the CLI keeps its exact output and a programmatic
+ * caller stays quiet. `refreshAgentDocs` is re-exported here (unchanged surface).
*/
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import {execFile} from 'node:child_process';
-import {promisify} from 'node:util';
-import {ensureJscodeshift} from '../../codemods/ensure-jscodeshift.mjs';
-import {getTransformsBetween, latestVersion} from '../../codemods/registry.mjs';
-import {runCodemods} from '../../codemods/runner.mjs';
-import {
- discoverIntegrationCodemods,
- selectIntegrationCodemods,
-} from '../../codemods/integration-discovery.mjs';
-import {runIntegrationCodemods} from '../../codemods/integration-runner.mjs';
-import {installAgentDocs, inspectAgentDocs} from '../../lib/agent-docs/agent-docs.mjs';
-import {getCliInvocation, formatCliCommand} from '../../utils/package-manager.mjs';
-import {isValidSemver, semverGte} from '../../utils/semver.mjs';
-import {Project} from '../../lib/project.mjs';
-import {loadIntegrations} from '../../lib/integrations.mjs';
-import {warnOnIntegrationIssues} from '../../lib/integration-warnings.mjs';
+import {list} from './list/list.mjs';
+import {run} from './run/run.mjs';
+import {isValidSemver} from '../../utils/semver.mjs';
+import {getCliInvocation} from '../../utils/package-manager.mjs';
import {ERROR_CODES} from '../../lib/error-codes.mjs';
import {AstryxError} from '../error.mjs';
import {noopLogger} from '../../lib/term-log.mjs';
-const execFileAsync = promisify(execFile);
+export {refreshAgentDocs} from './_adapter.mjs';
/**
- * Detect the installed target version from node_modules.
- * @param {string} cwd
- * @returns {{version: string, packageName: string}|null}
+ * @typedef {import('./_adapter.mjs').UpgradeOptions} UpgradeOptions
*/
-function detectInstalledTargetVersion(cwd) {
- for (const packageName of ['@astryxdesign/core', '@xds/core']) {
- const pkgPath = path.resolve(
- cwd,
- 'node_modules',
- ...packageName.split('/'),
- 'package.json',
- );
- try {
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
- if (pkg.version) return {version: pkg.version, packageName};
- } catch {
- // Missing/unreadable — try the next supported package name.
- }
- }
- return null;
-}
-
-/**
- * @param {(string | null | undefined | false)[] | undefined} files
- * @returns {string[]}
- */
-function uniqueFiles(files) {
- return [
- ...new Set(
- (files ?? []).filter(/** @returns {f is string} */ f => Boolean(f)),
- ),
- ];
-}
-
-/**
- * Run the app config's post-codemod hooks (config.hooks.postCodemod).
- * Dry-run PREVIEWS (buildCommand still called, so a throw fails); apply executes.
- * @param {import('../../types/config').PostCodemodHook[]} hooks
- * @param {{packageDir: string, files: string[], apply: boolean}} context
- * @param {import('../../lib/term-log.mjs').CliLogger} logger
- */
-async function runPostCodemodHooks(hooks, context, logger) {
- if (!hooks || hooks.length === 0) return;
- const {packageDir, files, apply} = context;
-
- for (let i = 0; i < hooks.length; i++) {
- const hook = hooks[i];
- const label = hook.name ?? `postCodemod[${i}]`;
- if (typeof hook.buildCommand !== 'function') {
- throw new Error(
- `Post-codemod hook ${label} is missing a buildCommand function.`,
- );
- }
-
- const cmd = await hook.buildCommand({packageDir, files});
- if (!cmd) {
- logger.info(`Post-codemod hook ${label} produced no command; skipping.`);
- continue;
- }
-
- if (!apply) {
- const preview = [cmd.command, ...(cmd.args ?? [])].join(' ');
- logger.info(`Post-codemod hook ${label} (dry run): ${preview}`);
- continue;
- }
-
- await execFileAsync(
- cmd.command,
- cmd.args ?? [],
- /** @type {import('node:child_process').ExecFileOptions & {encoding: 'utf-8'}} */ ({
- cwd: cmd.options?.cwd ?? packageDir,
- timeout: cmd.options?.timeout ?? 300_000,
- stdio: 'pipe',
- encoding: 'utf-8',
- ...cmd.options,
- env: {...process.env, ...(cmd.options?.env ?? {})},
- }),
- );
- logger.success(`Post-codemod hook ${label} completed.`);
- }
-}
-
-/**
- * Refresh (or, in dry-run, report) the managed agent-docs block after a version
- * bump. The block documents the INSTALLED library, so it must be re-synced on
- * EVERY upgrade path, including the no-codemods short-circuits (#4168).
- *
- * @param {{cwd: string, installedVersion: string, apply: boolean, logger?: import('../../lib/term-log.mjs').CliLogger}} ctx
- * @returns {import('../../types/upgrade').AgentDocsSummary}
- */
-export function refreshAgentDocs({cwd, installedVersion, apply, logger = noopLogger}) {
- const inspection = inspectAgentDocs(cwd, installedVersion);
- /** @type {import('../../types/upgrade').AgentDocsSummary} */
- const summary = {
- status: inspection.status,
- installedVersion,
- fromVersions: inspection.blockVersions,
- files: [],
- refreshed: false,
- action: 'none',
- };
-
- // Never initialized — don't silently create docs during an upgrade; nudge.
- if (inspection.status === 'missing') {
- summary.action = 'nudge-init';
- logger.warn(
- `No Astryx agent-docs block found — AI agents have no component index. Run \`${formatCliCommand('astryx init --features agents')}\` to install it.`,
- );
- return summary;
- }
-
- if (inspection.status === 'current') return summary;
-
- // Stale.
- summary.files = inspection.staleFiles;
- const fromLabel = summary.fromVersions.length
- ? `v${summary.fromVersions.join(', v')}`
- : 'an unknown version';
-
- if (!apply) {
- summary.action = 'would-refresh';
- logger.warn(
- `Agent docs are stale: block is at ${fromLabel}, installed is v${installedVersion}. Re-run with --apply to refresh (${summary.files.join(', ')}).`,
- );
- return summary;
- }
-
- // Apply: rewrite only files that already carry a marker (onlyReplace).
- try {
- const written = installAgentDocs(cwd, {onlyReplace: true});
- summary.refreshed = written.length > 0;
- summary.files = written;
- if (summary.refreshed) {
- summary.action = 'refreshed';
- logger.success(
- `Agent docs refreshed → v${installedVersion} (from ${fromLabel}): ${written.join(', ')}`,
- );
- } else {
- summary.action = 'error';
- logger.warn(
- `Agent docs look stale but couldn't be refreshed — the <!-- ASTRYX:START -->/<!-- ASTRYX:END --> markers may be malformed. Run \`${formatCliCommand('astryx init --features agents')}\` to reinstall the block.`,
- );
- }
- } catch {
- summary.action = 'error';
- logger.warn(
- `Could not refresh agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,
- );
- }
- return summary;
-}
-
-/**
- * @typedef {object} CoreTransformEntry
- * @property {string} name
- * @property {import('../../types/codemod').CodemodTransform} transform
- * @property {{title: string, description?: string, pr?: string, codemodType?: string}} meta
- * @property {boolean} [optional]
- */
-/** @typedef {{version: string, transforms: CoreTransformEntry[]}} CoreVersionManifest */
/**
- * @typedef {object} UpgradeOptions
- * @property {boolean} [list]
- * @property {string} [from]
- * @property {boolean} [apply]
- * @property {boolean} [force]
- * @property {string} [codemod]
- * @property {string[]} [skipCodemod]
- * @property {string[]} [integration]
- * @property {string} [path]
- * @property {boolean} [installDeps]
- */
-
-/**
- * Run the upgrade pipeline. Returns the terminal receipt; throws AstryxError on
+ * Run the upgrade pipeline. Validates the invocation, then dispatches to the
+ * list/status/run leaves. Returns the leaf's receipt; throws AstryxError on
* failure. Progress is emitted through `logger` (silent by default).
*
* @param {UpgradeOptions} [options]
@@ -228,12 +43,6 @@ export function refreshAgentDocs({cwd, installedVersion, apply, logger = noopLog
* @returns {Promise<import('../../types/upgrade').UpgradeListResponse | import('../../types/upgrade').UpgradeStatusResponse | import('../../types/upgrade').UpgradeRunResponse>}
*/
export async function upgrade(options = {}, {cwd = process.cwd(), logger = noopLogger} = {}) {
- // Resolve the source dir against the API's cwd (not process.cwd()) so a
- // programmatic caller in another directory scans the right tree. The runners
- // do path.resolve(srcPath); an already-absolute path is idempotent there, so
- // this is byte-identical for the CLI (where cwd === process.cwd()).
- const path_ = path.resolve(cwd, options.path ?? './src');
- const apply = options.apply ?? false;
logger.intro('Upgrade');
if (!options.list && !options.from) {
@@ -251,265 +60,8 @@ export async function upgrade(options = {}, {cwd = process.cwd(), logger = noopL
}
if (options.list) {
- const codemods = [];
- const manifests = /** @type {CoreVersionManifest[]} */ (
- await getTransformsBetween('0.0.0', latestVersion)
- );
- for (const {version, transforms} of manifests) {
- for (const {name, meta, optional} of transforms) {
- codemods.push({name, title: meta.title, version, pr: meta.pr, optional: !!optional});
- }
- }
- logger.step('Available codemods:');
- for (const {name, title, pr, optional} of codemods) {
- logger.info(` ${name} — ${title}${optional ? ' (optional)' : ''} (${pr})`);
- }
- logger.outro('Done');
- return {
- type: 'upgrade.list',
- data: codemods.map(({name, title, version, optional}) => ({name, title, version, optional})),
- };
- }
-
- const currentVersion = /** @type {string} */ (options.from);
- const installed = detectInstalledTargetVersion(cwd);
- if (!installed) {
- const msg = `Could not find installed @astryxdesign/core (or legacy @xds/core). Install the target version first, then rerun \`${getCliInvocation()} upgrade --from <old-version>\`.`;
- logger.error(msg);
- logger.outro('Aborted');
- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_VERSION_DETECT);
- }
- const targetVersion = installed.version;
-
- logger.info(`From version: ${currentVersion}`);
- logger.info(`Installed target: ${targetVersion} (${installed.packageName})`);
-
- // Sync the managed agent-docs block FIRST — it documents the installed library
- // independent of codemods, so refresh on every path (issue #4168).
- const agentDocs = refreshAgentDocs({cwd, installedVersion: targetVersion, apply: apply || false, logger});
-
- if (!options.force && semverGte(currentVersion, targetVersion)) {
- logger.success('Already up to date — no codemods to run.');
- logger.info('Use --force to run codemods anyway.');
- logger.outro('Done');
- return {type: 'upgrade.status', data: {status: 'up_to_date', from: currentVersion, to: targetVersion, agentDocs}};
- }
-
- const versionManifests = /** @type {CoreVersionManifest[]} */ ([
- ...(await getTransformsBetween(currentVersion, targetVersion)),
- ]);
-
- const coreConfigCodemodNames = [];
- for (const {transforms} of versionManifests) {
- for (const t of transforms) {
- if (options.codemod && t.name !== options.codemod) continue;
- if (t.meta?.codemodType === 'config') coreConfigCodemodNames.push(t.name);
- }
- }
- const hasCoreConfigCodemod = coreConfigCodemodNames.length > 0;
-
- const skipCodemods = new Set(options.skipCodemod ?? []);
-
- let totalTransforms = 0;
- let totalOptional = 0;
- for (const {transforms} of versionManifests) {
- for (const t of transforms) {
- if (options.codemod && t.name !== options.codemod) continue;
- if (skipCodemods.has(t.name)) continue;
- if (t.optional && !options.codemod) totalOptional++;
- else totalTransforms++;
- }
- }
-
- const ready = await ensureJscodeshift({installDeps: options.installDeps, silent: logger === noopLogger});
- if (!ready) {
- const msg = 'jscodeshift is required but could not be installed.';
- logger.outro('Aborted');
- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_DEP_MISSING);
- }
-
- // CORE codemods run FIRST (before loading config) so a core CONFIG codemod can
- // repair a config the strict loader would otherwise reject.
- const codemodResult = await runCodemods(versionManifests, {
- apply: apply,
- path: path_,
- codemod: options.codemod,
- skipCodemods,
- silent: logger === noopLogger,
- });
- const coreResult = codemodResult && 'totalFilesChanged' in codemodResult ? codemodResult : null;
-
- /** @type {Array<import('../../lib/integrations.mjs').LoadedIntegration>} */
- let integrations;
- /** @type {import('../../types/config').PostCodemodHook[]} */
- let postCodemodHooks;
- /** @type {Array<{version: string, codemods: import('../../types/codemod').CodemodEntry[]}>} */
- let integrationVersionGroups;
- try {
- const project = await Project.load(cwd);
- postCodemodHooks = project.config.hooks?.postCodemod ?? [];
- const integrationSpecs = uniqueFiles([
- ...(project.integrations ?? []),
- ...(options.integration ?? []),
- ]);
- integrations = await loadIntegrations(integrationSpecs);
- } catch (err) {
- const configErr = /** @type {Error} */ (err);
- // Graceful dry-run catch: a config that fails strict validation is expected
- // & fixable ONLY when dry-run AND a pending core config codemod previewed a
- // change (the codemod that would repair it).
- const codemodWouldFixConfig = hasCoreConfigCodemod && (coreResult?.totalFilesChanged ?? 0) > 0;
- if (!apply && codemodWouldFixConfig) {
- const codemodFlags = coreConfigCodemodNames.map(name => `--codemod ${name}`).join(' ');
- const suggestedCommand = `astryx upgrade --from ${currentVersion} ${codemodFlags} --apply`;
- const guidance =
- 'Your astryx.config currently fails strict validation, but a pending ' +
- 'config codemod would repair it. This dry run previewed the fix without ' +
- 'writing. Re-run with --apply to apply it, or run just the config codemod(s) ' +
- 'now:';
- logger.warn(guidance);
- logger.info(` ${formatCliCommand(suggestedCommand)}`);
- logger.info('Integrations are skipped in this preview; they will be processed on the --apply run.');
- logger.outro('Dry run complete');
- return {
- type: 'upgrade.status',
- data: {
- status: 'config_fixable',
- from: currentVersion,
- to: targetVersion,
- configError: configErr.message,
- configCodemods: coreConfigCodemodNames,
- suggestedCommand,
- message: guidance,
- note: 'Integrations are skipped in this preview; they will be processed on the --apply run.',
- agentDocs,
- },
- };
- }
- // Genuine config error: abort.
- logger.error(configErr.message);
- logger.outro('Aborted');
- throw new AstryxError(configErr.message, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);
- }
-
- if (integrations.length > 0) {
- logger.info(`Integrations: ${integrations.map(i => i.name ?? i.__spec).join(', ')}`);
- }
-
- // Non-blocking nudge for integration validation issues (suppressed for
- // programmatic/--json callers, i.e. the silent logger).
- try {
- await warnOnIntegrationIssues(integrations, {json: logger === noopLogger});
- } catch {
- // Never let the nudge break the upgrade.
- }
-
- /** @type {Map<string, Array<import('../../types/codemod').CodemodEntry>>} */
- const integrationCodemodsByVersion = new Map();
- for (const integration of integrations) {
- if (!integration?.codemods) continue;
- try {
- const byVersion = await discoverIntegrationCodemods([integration]);
- for (const [version, rawList] of byVersion) {
- const list = /** @type {Array<import('../../types/codemod').CodemodEntry>} */ (/** @type {unknown} */ (rawList));
- const existing = integrationCodemodsByVersion.get(version);
- if (existing) existing.push(...list);
- else integrationCodemodsByVersion.set(version, [...list]);
- }
- } catch {
- // Skip this integration's codemods (definition error); nudge above surfaces it.
- }
- }
- integrationVersionGroups = /** @type {Array<{version: string, codemods: import('../../types/codemod').CodemodEntry[]}>} */ (
- selectIntegrationCodemods(integrationCodemodsByVersion, currentVersion, targetVersion)
- );
- const hasIntegrationCodemods = integrationVersionGroups.some(g => g.codemods.length > 0);
-
- for (const {codemods} of integrationVersionGroups) {
- for (const c of codemods) {
- if (options.codemod && c.id !== options.codemod) continue;
- if (skipCodemods.has(c.id)) continue;
- if (c.codemod.isOptional && !options.codemod) totalOptional++;
- else totalTransforms++;
- }
- }
-
- if (versionManifests.length === 0 && !hasIntegrationCodemods) {
- logger.success('No codemods available for this version range.');
- logger.outro('Done');
- return {type: 'upgrade.status', data: {status: 'no_codemods', from: currentVersion, to: targetVersion, agentDocs}};
- }
-
- if (totalTransforms === 0 && totalOptional === 0) {
- const msg = `Codemod "${options.codemod}" not found. Use --list to see available codemods.`;
- logger.error(msg);
- logger.outro('Aborted');
- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_UNKNOWN_CODEMOD);
- }
-
- if (totalTransforms > 0) {
- logger.step(`${totalTransforms} codemod${totalTransforms === 1 ? '' : 's'} to run${apply ? '' : ' (dry run)'}`);
- } else {
- logger.step('No automatic codemods to run for this version range.');
- }
-
- /**
- * @type {{from: string, to: string, codemods: number, integrations: string[], agentDocsRefreshed: boolean, agentDocs: import('../../types/upgrade').AgentDocsSummary, filesChanged?: number, transformsApplied?: number, errors?: Array<{file: string, codemod: string, error: string}>}}
- */
- const receipt = {
- from: currentVersion,
- to: targetVersion,
- codemods: totalTransforms,
- integrations: integrations.map(i => i.name ?? i.__spec),
- agentDocsRefreshed: agentDocs.refreshed,
- agentDocs,
- };
-
- let integrationResult = null;
- if (hasIntegrationCodemods) {
- logger.step('Applying integration codemods...');
- const jscodeshift = (await import('jscodeshift')).default;
- integrationResult = runIntegrationCodemods(integrationVersionGroups, {
- apply: apply,
- path: path_,
- codemod: options.codemod,
- skipCodemods,
- jscodeshift,
- silent: logger === noopLogger,
- });
- }
-
- const mergedFilesChanged = (coreResult?.totalFilesChanged ?? 0) + (integrationResult?.totalFilesChanged ?? 0);
- const mergedTransformsApplied = (coreResult?.totalTransformsApplied ?? 0) + (integrationResult?.totalTransformsApplied ?? 0);
- const mergedWrittenFiles = [...(coreResult?.writtenFiles ?? []), ...(integrationResult?.writtenFiles ?? [])];
- const mergedErrors = [...(coreResult?.errors ?? []), ...(integrationResult?.errors ?? [])];
-
- if (postCodemodHooks.length > 0 && mergedFilesChanged > 0) {
- const files = uniqueFiles(mergedWrittenFiles).map(file => path.relative(cwd, file));
- try {
- await runPostCodemodHooks(postCodemodHooks, {packageDir: cwd, files, apply: apply || false}, logger);
- } catch (err) {
- const hookErr = /** @type {Error} */ (err);
- const msg = `Post-codemod hook failed: ${hookErr.message}`;
- logger.error(msg);
- logger.outro('Upgrade failed');
- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
- }
- }
-
- receipt.filesChanged = mergedFilesChanged;
- receipt.transformsApplied = mergedTransformsApplied;
- receipt.errors = mergedErrors;
-
- if (receipt.errors?.length > 0) {
- const msg = `Upgrade completed with ${receipt.errors.length} codemod error${receipt.errors.length === 1 ? '' : 's'}.`;
- logger.outro('Upgrade failed');
- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
+ return list({logger});
}
- logger.outro(apply ? 'Upgrade complete' : 'Dry run complete');
- return {
- type: 'upgrade.run',
- data: /** @type {import('../../types/upgrade').UpgradeRunResponse['data']} */ (/** @type {unknown} */ (receipt)),
- };
+ return run(options, {cwd, logger});
}