An open source design system that's fully customizable and agent ready
TypeScript
refactor(cli): extract upgrade into api/upgrade (thin handler + injected logger) (#4429)
Joey55351daa1f99
diff --git a/.changeset/cli-thin-api-upgrade.md b/.changeset/cli-thin-api-upgrade.mdnew file mode 100644index 0000000000..658e0af7f6--- /dev/null+++ b/.changeset/cli-thin-api-upgrade.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[feat] CLI: `upgrade` is now fully scriptable through the `./api` barrel — the version-to-version pipeline (codemods + agent-docs refresh) lives in `api/upgrade` and returns a typed receipt (`upgrade.list` | `upgrade.status` | `upgrade.run`), with the CLI reduced to a thin parse → API call → render wrapper. Human progress is emitted through an injectable logger, so a scripted `upgrade()` stays silent while the CLI output and `--json` envelopes are unchanged for existing usage.+@josephfarinadiff --git a/.github/scripts/api-cli-parity-test.mjs b/.github/scripts/api-cli-parity-test.mjsindex a709b0b0e0..5d822414f7 100644--- a/.github/scripts/api-cli-parity-test.mjs+++ b/.github/scripts/api-cli-parity-test.mjs@@ -268,10 +268,19 @@ add('swizzle --list', ['swizzle', '--list'],add('swizzle (not found)', ['swizzle', 'NotARealComponent99'],() => apiCall(api.swizzle, 'NotARealComponent99', {cwd: ROOT}));+// Upgrade — list + the two argument-validation errors are read-only: they+// return/throw before any codemod or agent-docs side effect, so the api matches+// the CLI envelope exactly. The full run/status pipeline is covered by the+// upgrade unit tests (side-effecting, needs a fixtured project).+add('upgrade --list', ['upgrade', '--list'],+ () => apiCall(api.upgrade, {list: true}, {cwd: ROOT}));+add('upgrade (missing --from)', ['upgrade'],+ () => apiCall(api.upgrade, {}, {cwd: ROOT}));+add('upgrade (invalid --from)', ['upgrade', '--from', 'not-a-version'],+ () => apiCall(api.upgrade, {from: 'not-a-version'}, {cwd: ROOT}));+// Other commands — probe with safe read-only args (no API yet)-const otherCommands = [- ['upgrade', '--list'],-];+const otherCommands = [];for (const args of otherCommands) {const probe = cliJson(args);if (!probe.__parse_error && !probe.error?.includes('not supported')) {diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjsindex 0acbcfeec1..3a081e012f 100644--- a/packages/cli/api/index.mjs+++ b/packages/cli/api/index.mjs@@ -29,6 +29,7 @@ export {hook} from './hook/hook.mjs';export {search} from './search/search.mjs';export {build} from './build/build.mjs';export {swizzle} from './swizzle/swizzle.mjs';+export {upgrade} from './upgrade/upgrade.mjs';export {doctor} from './doctor/doctor.mjs';export {layoutExpand, layoutCheck, layoutGrammar} from './layout/layout.mjs';export {diff --git a/packages/cli/api/upgrade/upgrade.mjs b/packages/cli/api/upgrade/upgrade.mjsnew file mode 100644index 0000000000..6ced55729f--- /dev/null+++ b/packages/cli/api/upgrade/upgrade.mjs@@ -0,0 +1,515 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file upgrade API — full version-to-version upgrade pipeline.+ *+ * `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.+ *+ * 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.+ */++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 {ERROR_CODES} from '../../lib/error-codes.mjs';+import {AstryxError} from '../error.mjs';+import {noopLogger} from '../../lib/term-log.mjs';++const execFileAsync = promisify(execFile);++/**+ * Detect the installed target version from node_modules.+ * @param {string} cwd+ * @returns {{version: string, packageName: string}|null}+ */+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+ * failure. Progress is emitted through `logger` (silent by default).+ *+ * @param {UpgradeOptions} [options]+ * @param {{cwd?: string, logger?: import('../../lib/term-log.mjs').CliLogger}} [ctx]+ * @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) {+ const msg = `Missing required --from. Install the target version first, then run \`${getCliInvocation()} upgrade --from <old-version>\`.`;+ logger.error(msg);+ logger.outro('Aborted');+ throw new AstryxError(msg, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);+ }++ if (!options.list && !isValidSemver(options.from)) {+ const msg = `Invalid --from value: "${options.from}". Expected a semver string like 0.0.5.`;+ logger.error(msg);+ logger.outro('Aborted');+ throw new AstryxError(msg, undefined, ERROR_CODES.ERR_INVALID_VERSION);+ }++ 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);+ }++ 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/upgrade.test.mjs b/packages/cli/api/upgrade/upgrade.test.mjsnew file mode 100644index 0000000000..27869d6adc--- /dev/null+++ b/packages/cli/api/upgrade/upgrade.test.mjs@@ -0,0 +1,211 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Direct API tests for `upgrade()` — the programmatic surface (`@astryxdesign/cli/api`).+ *+ * The CLI suites (cli/commands/upgrade*.test.mjs) drive `registerUpgrade` and+ * cover behavior end-to-end; these assert the API contract you get when calling+ * `upgrade()` in code: the typed receipt shape, thrown AstryxError codes, that+ * it honors the `cwd` option for detection/agent-docs, and that it stays SILENT+ * under the default noopLogger (no console spam for a scripted caller).+ */++import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {upgrade} from './upgrade.mjs';+import {AstryxError} from '../error.mjs';+import {ERROR_CODES} from '../../lib/error-codes.mjs';+import {generateCompressedIndex} from '../../lib/agent-docs/agent-docs.mjs';++vi.setConfig({testTimeout: 30000});++let tmpDir;+let originalCwd;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-upgrade-api-'));+ originalCwd = process.cwd();+});++afterEach(() => {+ process.chdir(originalCwd);+ fs.rmSync(tmpDir, {recursive: true, force: true});+ vi.restoreAllMocks();+});++function writePkg(dir, deps = {}) {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: 'fixture', dependencies: deps}, null, 2),+ );+}++function writeInstalledCore(dir, version) {+ const d = path.join(dir, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(d, {recursive: true});+ fs.writeFileSync(+ path.join(d, 'package.json'),+ JSON.stringify({name: '@astryxdesign/core', version}, null, 2),+ );+}++function writeAgentBlock(dir, rel, version) {+ fs.writeFileSync(path.join(dir, rel), `# Doc\n\n${generateCompressedIndex(version)}\n`);+}++describe('upgrade() — receipts', () => {+ it('returns upgrade.list without touching cwd', async () => {+ const res = await upgrade({list: true});+ expect(res.type).toBe('upgrade.list');+ expect(Array.isArray(res.data)).toBe(true);+ expect(res.data.length).toBeGreaterThan(0);+ // The public list entry is the stripped shape (no `pr`).+ for (const entry of res.data) {+ expect(entry).toHaveProperty('name');+ expect(entry).toHaveProperty('title');+ expect(entry).toHaveProperty('version');+ expect(entry).not.toHaveProperty('pr');+ }+ });++ it('honors cwd: refreshes a stale agent-docs block on the up-to-date path (--apply)', async () => {+ // from == installed → up_to_date short-circuit (returns before the codemod+ // runner), so this exercises detection + agent-docs purely via the cwd+ // option, with NO process.chdir.+ writePkg(tmpDir);+ writeInstalledCore(tmpDir, '0.0.15');+ writeAgentBlock(tmpDir, 'AGENTS.md', '0.0.1');++ const res = await upgrade({from: '0.0.15', apply: true}, {cwd: tmpDir});++ expect(res.type).toBe('upgrade.status');+ expect(res.data.status).toBe('up_to_date');+ expect(res.data.from).toBe('0.0.15');+ expect(res.data.to).toBe('0.0.15');+ expect(res.data.agentDocs.action).toBe('refreshed');+ expect(res.data.agentDocs.refreshed).toBe(true);+ expect(res.data.agentDocs.files).toContain('AGENTS.md');+ // The file at the *cwd* fixture was rewritten to the installed version.+ const content = fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8');+ expect(content).toMatch(/Astryx v0\.0\.15 ·/);+ expect(content).not.toMatch(/Astryx v0\.0\.1 ·/);+ });++ it('reports would-refresh on a dry run without writing (honors cwd)', async () => {+ writePkg(tmpDir);+ writeInstalledCore(tmpDir, '0.0.15');+ writeAgentBlock(tmpDir, 'AGENTS.md', '0.0.1');+ const before = fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8');++ const res = await upgrade({from: '0.0.15'}, {cwd: tmpDir});++ expect(res.data.status).toBe('up_to_date');+ expect(res.data.agentDocs.action).toBe('would-refresh');+ expect(res.data.agentDocs.refreshed).toBe(false);+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(before);+ });++ it('returns upgrade.run for an applicable range', async () => {+ // Codemod scanning is process.cwd()-relative, so chdir into the fixture.+ writePkg(tmpDir);+ writeInstalledCore(tmpDir, '0.0.15');+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, 'src', 'index.ts'), 'const x = 1;\n');+ process.chdir(tmpDir);++ const res = await upgrade({from: '0.0.1', apply: false, path: 'src'}, {cwd: tmpDir});++ expect(res.type).toBe('upgrade.run');+ expect(res.data.from).toBe('0.0.1');+ expect(res.data.to).toBe('0.0.15');+ expect(typeof res.data.codemods).toBe('number');+ expect(res.data.agentDocs).toBeDefined();+ });+});++describe('upgrade() — honors cwd for codemod scanning (no chdir)', () => {+ it('scans the cwd source tree, not process.cwd()', async () => {+ // Fixture lives in tmpDir; process.cwd() stays the repo root (NO chdir).+ // The codemod runner resolves --path against the API cwd, so it must scan+ // tmpDir/src — regression guard for the earlier process.cwd()-relative bug.+ writePkg(tmpDir);+ writeInstalledCore(tmpDir, '0.0.15');+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, 'src', 'index.ts'), 'const x = 1;\n');++ // Capture stdout: the runner logs the directory it scans. A non-noop logger+ // (distinct object from the module's noopLogger) keeps the runner non-silent.+ const out = [];+ vi.spyOn(console, 'log').mockImplementation((...a) => out.push(a.join(' ')));+ vi.spyOn(process.stdout, 'write').mockImplementation(c => {+ out.push(typeof c === 'string' ? c : c.toString());+ return true;+ });+ const noop = () => {};+ const logger = {+ intro: noop, step: noop, info: noop, warn: noop, success: noop, error: noop, outro: noop,+ };++ const res = await upgrade({from: '0.0.1', apply: false, path: 'src'}, {cwd: tmpDir, logger});++ const joined = out.join('\n');+ expect(res.type).toBe('upgrade.run');+ // Scanned the cwd tree…+ expect(joined).toContain(path.join(tmpDir, 'src'));+ // …and did NOT report the path missing (which is what the old,+ // process.cwd()-relative resolution produced here).+ expect(joined).not.toMatch(/Source path not found/);+ });+});++describe('upgrade() — errors throw AstryxError', () => {+ it('missing --from → ERR_INVALID_ARGUMENT', async () => {+ writePkg(tmpDir);+ writeInstalledCore(tmpDir, '0.0.15');+ await expect(upgrade({}, {cwd: tmpDir})).rejects.toMatchObject({+ name: 'AstryxError',+ code: ERROR_CODES.ERR_INVALID_ARGUMENT,+ });+ await expect(upgrade({}, {cwd: tmpDir})).rejects.toThrow(/Missing required --from/);+ });++ it('invalid --from → ERR_INVALID_VERSION', async () => {+ writePkg(tmpDir);+ writeInstalledCore(tmpDir, '0.0.15');+ await expect(upgrade({from: 'not-a-version'}, {cwd: tmpDir})).rejects.toMatchObject({+ code: ERROR_CODES.ERR_INVALID_VERSION,+ });+ });++ it('no installed core → ERR_VERSION_DETECT (uses the cwd option to look)', async () => {+ // Empty cwd (no node_modules/@astryxdesign/core) — detection must fail here,+ // proving the cwd option routes version detection.+ writePkg(tmpDir);+ const err = await upgrade({from: '0.0.1'}, {cwd: tmpDir}).catch(e => e);+ expect(err).toBeInstanceOf(AstryxError);+ expect(err.code).toBe(ERROR_CODES.ERR_VERSION_DETECT);+ });+});++describe('upgrade() — silent by default (noopLogger)', () => {+ it('prints nothing to stdout when called programmatically', async () => {+ writePkg(tmpDir);+ writeInstalledCore(tmpDir, '0.0.15');+ writeAgentBlock(tmpDir, 'AGENTS.md', '0.0.1');++ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const outSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);++ const res = await upgrade({from: '0.0.15', apply: true}, {cwd: tmpDir});++ // The receipt still comes back…+ expect(res.data.agentDocs.action).toBe('refreshed');+ // …but a scripted caller sees zero human output (default noopLogger).+ expect(logSpy).not.toHaveBeenCalled();+ expect(outSpy).not.toHaveBeenCalled();+ expect(errSpy).not.toHaveBeenCalled();+ });+});diff --git a/packages/cli/cli/commands/upgrade.mjs b/packages/cli/cli/commands/upgrade.mjsindex 4840cc6a8d..029ef57423 100644--- a/packages/cli/cli/commands/upgrade.mjs+++ b/packages/cli/cli/commands/upgrade.mjs@@ -1,861 +1,67 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file upgrade command — Full version-to-version upgrade pipeline+ * @file upgrade command — thin wrapper around api/upgrade.*- * `astryx upgrade` runs codemods that migrate source code from a previous- * Astryx version to the currently installed version.+ * `astryx upgrade` runs codemods that migrate source between Astryx versions and+ * refreshes the managed agent-docs block. All logic lives in api/upgrade; this+ * handler only parses flags, wires the progress logger (term output in human+ * mode, silent in --json), and renders the result / exit code.*- * Consumers should bump/install their Astryx packages first, then run:+ * Consumers bump/install their Astryx packages first, then run:* astryx upgrade --from <old-version> --path <source-dir> --apply- *- * Pipeline (--apply):- * 1. Read installed @astryxdesign/core (or legacy @xds/core) version- * 2. Refresh the managed agent-docs block (AGENTS.md / CLAUDE.md) to the- * installed version — runs on EVERY path (including the up-to-date /- * no-codemods short-circuits), because the block documents the installed- * library, not the codemod outcome. Dry-run reports without writing.- * 3. Run codemods for --from → installed version- *- * Options:- * --from <version> Previous version before the dependency upgrade- * --apply Write changes to disk (default: dry-run)- * --force Run codemods even when from >= installed version- * --codemod <name> Run a specific transform only- * --skip-codemod <name…> Exclude named codemods (variadic). Use this to- * re-run past a codemod that failed at execution time.- * --integration <spec> Load an explicit integration package or file- * --path <dir> Source directory (default: ./src)- * --install-deps Auto-install jscodeshift without prompting (for CI/LLM)- *- * Integration error policy:- * - A DISCOVERY/definition error for an integration (bad manifest/export,- * duplicate ids, missing root) SKIPS that integration's codemods and warns- * (via the integration-issue nudge) — it does NOT hard-fail the upgrade.- * - An EXECUTION-time failure (a transform THROWS while rewriting files)- * ABORTS the upgrade (nonzero exit) so a partial write never proceeds.*/-import * as fs from 'node:fs';-import * as path from 'node:path';-import {execFile} from 'node:child_process';-import {promisify} from 'node:util';-import * as p from '../../lib/term-log.mjs';-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 {jsonOut, jsonError} from '../../lib/json.mjs';-import {Project} from '../../lib/project.mjs';-import {loadIntegrations} from '../../lib/integrations.mjs';-import {warnOnIntegrationIssues} from '../../lib/integration-warnings.mjs';-import {ERROR_CODES} from '../../lib/error-codes.mjs';--const execFileAsync = promisify(execFile);--/**- * Detect the installed target version from node_modules.- * @returns {{version: string, packageName: string}|null}- */-function detectInstalledTargetVersion() {- for (const packageName of ['@astryxdesign/core', '@xds/core']) {- const pkgPath = path.resolve(- process.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 or unreadable package.json — 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).- *- * Each hook's `buildCommand({packageDir, files})` returns a command to run- * (or a nullish value to skip). In dry-run mode we only PREVIEW — buildCommand- * is called (so a throw still fails the run) but the command is never executed.- * In apply mode the commands run in order via execFile; a nonzero exit (or a- * buildCommand throw) fails the upgrade.- *- * @param {import('../../types/config').PostCodemodHook[]} hooks- * @param {{packageDir: string, files: string[], apply: boolean}} context- * @param {boolean} silent- */-async function runPostCodemodHooks(hooks, context, silent) {- if (!hooks || hooks.length === 0) return;-- const log = silent ? {info() {}, warn() {}, success() {}, error() {}} : p.log;- 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) {- log.info(`Post-codemod hook ${label} produced no command; skipping.`);- continue;- }-- if (!apply) {- const preview = [cmd.command, ...(cmd.args ?? [])].join(' ');- log.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 ?? {})},- }),- );- log.success(`Post-codemod hook ${label} completed.`);- }-}+import {termLogger, noopLogger} from '../../lib/term-log.mjs';+import {AstryxError} from '../../api/error.mjs';+import {upgrade as upgradeApi} from '../../api/upgrade/upgrade.mjs';/**- * Refresh (or, in dry-run, report) the managed agent-docs block after a version- * bump. The block (`<!-- ASTRYX:START --> … <!-- ASTRYX:END -->`) documents the- * INSTALLED library — its version, component index, and agent rules — so it must- * be re-synced on EVERY upgrade path, including the up-to-date / no-codemods- * short-circuits where no source file changes. That was the gap in #4168: an- * agent reading a stale index queries missing components and follows superseded- * rules. Three cases, one detection pass:- *- * - `stale` — a managed block records an older version (or a legacy XDS- * marker). `--apply` rewrites it; dry-run reports the pending- * refresh as a loud next step and writes nothing.- * - `missing` — core is installed but no managed block exists anywhere (the repo- * never ran `init`, or its agent docs were never marked). We never- * silently create docs mid-upgrade; we nudge to run `init`.- * - `current` — every block already matches the installed version: stay silent.- *- * @param {{cwd: string, installedVersion: string, apply: boolean, json: boolean}} ctx- * @returns {import('../../types/upgrade').AgentDocsSummary}- */-export function refreshAgentDocs({cwd, installedVersion, apply, json}) {- 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';- if (!json) {- p.log.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) {- // Dry-run: report the pending change, never write.- summary.action = 'would-refresh';- if (!json) {- p.log.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';- if (!json) {- p.log.success(- `Agent docs refreshed → v${installedVersion} (from ${fromLabel}): ${written.join(', ')}`,- );- }- } else {- // We detected a stale marked block but rewrote nothing, and- // installAgentDocs did not throw — the block markers are malformed (e.g. a- // START with no matching END, so the writer can't safely splice it). Don't- // fail silently: the block is exactly the artifact agents rely on.- summary.action = 'error';- if (!json) {- p.log.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';- if (!json) {- p.log.warn(- `Could not refresh agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,- );- }- }- return summary;-}--/**- * A single core transform entry as produced by the registry manifests. The- * registry's declared return type omits the optional `optional` flag and the- * `pr`/`codemodType` meta fields that the transform modules actually carry;- * this local shape captures what the upgrade command reads. Remove once- * codemods/registry.mjs declares these fields on its return type.- * @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]- */--/**- * A version-scoped group of core transforms from the registry.- * @typedef {{version: string, transforms: CoreTransformEntry[]}} CoreVersionManifest- */--/**- * Register the `upgrade` command (codemod-driven version migration).* @param {import('commander').Command} program*/export function registerUpgrade(program) {program.command('upgrade').description('Run codemods to migrate between versions')- .option(- '--from <version>',- 'Previous version before the dependency upgrade',- )+ .option('--from <version>', 'Previous version before the dependency upgrade').option('--apply', 'Write changes to disk (default: dry-run)', false)- .option(- '--force',- 'Run codemods even if --from is newer than the installed version',- false,- )+ .option('--force', 'Run codemods even if --from is newer than the installed version', false).option('--codemod <name>', 'Run a specific transform only')- .option(- '--skip-codemod <name...>',- 'Exclude named codemods (repeatable). Re-run past a failed codemod by skipping it.',- )- .option(- '--integration <package-or-file>',- 'Explicit integration package name or integration file path (repeatable)',- /**- * @param {string} value- * @param {string[]} previous- */- (value, previous) => [...(previous ?? []), value],- [],- )+ .option('--skip-codemod <name...>', 'Exclude named codemods (repeatable). Re-run past a failed codemod by skipping it.')+ .option('--integration <package-or-file>', 'Explicit integration package name or integration file path (repeatable)',+ /** @param {string} value @param {string[]} previous */+ (value, previous) => [...(previous ?? []), value], []).option('--path <dir>', 'Source directory to scan', './src')- .option(- '--install-deps',- 'Auto-install jscodeshift without prompting',- false,- )+ .option('--install-deps', 'Auto-install jscodeshift without prompting', false).option('--list', 'List available codemods', false).action(/**- * @param {{- * list?: boolean,- * from?: string,- * apply: boolean,- * force?: boolean,- * codemod?: string,- * skipCodemod?: string[],- * integration?: string[],- * path: string,- * installDeps?: boolean,- * }} options+ * @param {import('../../api/upgrade/upgrade.mjs').UpgradeOptions} options*/async options => {- const json = program.opts().json || false;- if (!json) p.intro('Upgrade');-- if (!options.list && !options.from) {- const msg =- `Missing required --from. Install the target version first, then run \`${getCliInvocation()} upgrade --from <old-version>\`.`;- if (json)- return jsonError(msg, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);- p.log.error(msg);- p.outro('Aborted');- process.exitCode = 1;- return;- }-- // Validate --from upfront so callers don't silently accept typos.- if (!options.list && !isValidSemver(options.from)) {- const msg = `Invalid --from value: "${options.from}". Expected a semver string like 0.0.5.`;- if (json)- return jsonError(msg, undefined, ERROR_CODES.ERR_INVALID_VERSION);- p.log.error(msg);- p.outro('Aborted');- process.exitCode = 1;- return;- }- if (options.list) {- const codemods = [];- // Walk the registry once from 0.0.0 → latest. Earlier this looped- // over every version and re-walked getTransformsBetween('0.0.0', v),- // so each codemod was printed once per release that included it- // (31 unique × 9 ≈ 201 lines on the current registry).- 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,- });- }- }- if (json)- return jsonOut(- 'upgrade.list',- codemods.map(({name, title, version, optional}) => ({- name,- title,- version,- optional,- })),- );- p.log.step('Available codemods:');- for (const {name, title, pr, optional} of codemods) {- p.log.info(- ` ${name} — ${title}${optional ? ' (optional)' : ''} (${pr})`,- );- }- p.outro('Done');- return;- }-- // Guarded above: reaching here means --from passed isValidSemver, so it's a string.- const currentVersion = /** @type {string} */ (options.from);- const installed = detectInstalledTargetVersion();- 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>\`.`;- if (json)- return jsonError(msg, undefined, ERROR_CODES.ERR_VERSION_DETECT);- p.log.error(msg);- p.outro('Aborted');- process.exitCode = 1;- return;- }- const targetVersion = installed.version;-- if (!json) {- p.log.info(`From version: ${currentVersion}`);- p.log.info(- `Installed target: ${targetVersion} (${installed.packageName})`,- );- }-- // Sync the managed agent-docs block to the installed version FIRST. It- // documents the installed library (version + component index + rules),- // independent of any source codemods, so it must be refreshed on every- // path below — including the up-to-date / no-codemods short-circuits that- // return before codemods ever run (issue #4168). Dry-run reports without- // writing. Folded into every terminal payload as `agentDocs`.- const agentDocs = refreshAgentDocs({- cwd: process.cwd(),- installedVersion: targetVersion,- apply: options.apply,- json,- });-- // ───────────────────────────────────────────────────────────────────- // PIPELINE ORDERING- //- // CORE codemods run BEFORE the consumer's config is loaded. `Project.load`- // STRICT-validates astryx.config.* and THROWS on unknown keys — but a core- // CONFIG codemod (e.g. v0.1.3 migrate-layout-components, signalled by- // `meta.codemodType === 'config'`) is precisely what repairs an otherwise- // -invalid config. Loading first created a chicken-and-egg: the config was- // rejected before the codemod that would fix it ever ran. Core codemods- // read files directly (config codemods via runConfigCodemod read- // astryx.config.*; code codemods scan --path), so they do NOT need the- // loaded config. We run them here, then load config, then sequence the- // integration codemods (which DO require a valid loaded config).- // ───────────────────────────────────────────────────────────────────-- if (!options.force && semverGte(currentVersion, targetVersion)) {- if (json) {- return jsonOut('upgrade.status', {- status: 'up_to_date',- from: currentVersion,- to: targetVersion,- agentDocs,- });- }- p.log.success('Already up to date — no codemods to run.');- p.log.info('Use --force to run codemods anyway.');- p.outro('Done');- return;- }-- // Resolve CORE transforms from the registry. These do not need the loaded- // config. Integration codemods are discovered later, AFTER the config- // loads successfully (they require a valid config to resolve).- const versionManifests = /** @type {CoreVersionManifest[]} */ ([- ...(await getTransformsBetween(currentVersion, targetVersion)),- ]);-- // Does the selected core set include >=1 CONFIG codemod? A config codemod- // is the established convention `meta.codemodType === 'config'` (see- // `toUnifiedEntry` in runner.mjs). This drives the graceful dry-run catch- // around `Project.load` below: a fixable config error is only "expected"- // when a pending core config codemod would repair it.- 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;-- // Codemods explicitly excluded via --skip-codemod, matched by the same- // identifier the run loop uses (core transform `t.name`, integration- // codemod `c.id`). Lets a user re-run past a codemod that failed at- // execution time.- const skipCodemods = new Set(options.skipCodemod ?? []);-- // Count CORE transforms (optional codemods only count when explicitly- // requested). Integration counts are added after discovery below.- 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++;- }- }- }-- // Ensure jscodeshift is available before running any codemod.- const ready = await ensureJscodeshift({- installDeps: options.installDeps,- silent: json,- });- if (!ready) {- if (json)- return jsonError(- 'jscodeshift is required but could not be installed.',- undefined,- ERROR_CODES.ERR_DEP_MISSING,- );- p.outro('Aborted');- process.exitCode = 1;- return;- }-- // STEP 3 — Run CORE codemods FIRST (before loading config). In --apply,- // core config codemods WRITE the repaired config to disk; in dry-run they- // only PREVIEW. This is what makes the v0.1.3 config codemod reachable on- // a config that the strict loader would otherwise reject.- const codemodResult = await runCodemods(versionManifests, {- apply: options.apply,- path: options.path,- codemod: options.codemod,- skipCodemods,- silent: json,- });- // runCodemods returns either a success accounting or a- // {ok: false, reason} sentinel (e.g. source_path_missing). Narrow to the- // success shape so downstream property reads type-check; the sentinel- // branch collapses to null and the `?? 0`/`?? []` fallbacks below treat- // it as "no files changed", matching the existing runtime behavior.- const coreResult =- codemodResult && 'totalFilesChanged' in codemodResult- ? codemodResult- : null;-- // STEP 4 — Load the consumer's config (STRICT validation; unchanged). On- // --apply this now sees the repaired config the core codemod just wrote.- // We need `hooks.postCodemod` and the configured integration specs from- // here. Wrap in a graceful dry-run catch (see below).- // Assigned inside the try below; every catch branch returns, so these- // are always set before any later read.- /** @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(process.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 the- // EXPECTED, fixable case ONLY when we are in dry-run AND a pending core- // config codemod just PREVIEWED a change to the config — i.e. the very- // codemod that would repair it. (Merely having a config codemod in the- // range is not enough: it may be a no-op on this config, in which case- // the validation error is genuine and we must abort. A config codemod- // that THREW reports zero would-change files, so it also fails this- // gate and aborts below — preserving the strictness contract.) This is- // the reason this PR reorders the pipeline.- const codemodWouldFixConfig =- hasCoreConfigCodemod && (coreResult?.totalFilesChanged ?? 0) > 0;- if (!options.apply && codemodWouldFixConfig) {- const codemodFlags = coreConfigCodemodNames- .map(name => `--codemod ${name}`)- .join(' ');- // Canonical (bare) form — this is a structured, machine-executable- // field in the --json envelope. The human print below is made- // install-aware via formatCliCommand.- 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:';- if (json) {- return jsonOut('upgrade.status', {- 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,- });- }- p.log.warn(guidance);- p.log.info(` ${formatCliCommand(suggestedCommand)}`);- p.log.info(- 'Integrations are skipped in this preview; they will be processed on the --apply run.',- );- p.outro('Dry run complete');- return;- }- // Genuine config error (apply mode, OR dry-run with no pending core- // config codemod that would fix it): abort as before. The agent-docs- // refresh already ran (it's independent of config), so surface it.- if (json)- return jsonError(- configErr.message,- /** @type {import('../../types/base').Suggestion[]} */ (/** @type {unknown} */ ({agentDocs})),- ERROR_CODES.ERR_INVALID_ARGUMENT,- );- p.log.error(configErr.message);- p.outro('Aborted');- process.exitCode = 1;- return;- }-- if (!json && integrations.length > 0) {- p.log.info(- `Integrations: ${integrations.map(i => i.name ?? i.__spec).join(', ')}`,- );- }+ const json = program.opts().json || false;+ const logger = json ? noopLogger : termLogger;- // Non-blocking nudge: if any configured integration has validation- // issues, print one compact line to stderr pointing at- // validate-integration. Best-effort; suppressed in --json mode. This- // depends on integrations being loaded, so it lives after the successful- // config load (it is skipped on the graceful dry-run path above, where- // integrations were never loaded).- try {- await warnOnIntegrationIssues(integrations, {json});- } catch {- // Never let the nudge break the upgrade.- }-- // STEP 5 — Discover + run INTEGRATION codemods (only reached on a- // successful config load). A broken integration (bad export, invalid- // schema, duplicate id, missing root) is a DEFINITION error: skip that- // integration's codemods and warn (via the nudge above), rather than- // hard-failing the upgrade. An EXECUTION-time failure (a transform- // throwing) is handled later by the codemod-error gate, which still- // aborts the upgrade.- /** @type {Map<string, Array<import('../../types/codemod').CodemodEntry>>} */- const integrationCodemodsByVersion = new Map();- for (const integration of integrations) {- if (!integration?.codemods) continue;+ /** @type {import('../../types/upgrade').UpgradeListResponse | import('../../types/upgrade').UpgradeStatusResponse | import('../../types/upgrade').UpgradeRunResponse} */+ let result;try {- const byVersion = await discoverIntegrationCodemods([integration]);- for (const [version, rawList] of byVersion) {- // discoverIntegrationCodemods declares `codemod: object` (loose); the- // runtime entries carry the full CodemodEntry.codemod shape. Narrow- // to the map's element type. Report: integration-discovery.mjs's- // @returns should declare CodemodEntry instead of the loose object.- 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; the validate-integration nudge- // above surfaces the underlying issue. Best-effort, non-blocking.- }- }- integrationVersionGroups =- /** @type {Array<{version: string, codemods: import('../../types/codemod').CodemodEntry[]}>} */ (- selectIntegrationCodemods(- integrationCodemodsByVersion,- currentVersion,- targetVersion,- )- );- const hasIntegrationCodemods = integrationVersionGroups.some(- g => g.codemods.length > 0,- );-- // Add integration transforms to the run counts.- 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++;+ result = await upgradeApi(options, {cwd: process.cwd(), logger});+ } catch (e) {+ // Handled failures throw AstryxError: --json emits the structured+ // envelope (byte-identical to the old inline jsonError) + exits 1;+ // human mode already saw the error line + outro via the logger, so we+ // just set the exit code. Anything else is unexpected — let the+ // top-level boundary in bin/astryx.mjs format it as before.+ if (e instanceof AstryxError) {+ if (json) jsonError(e.message, undefined, e.code);+ else process.exitCode = 1;+ return;}+ throw e;}- }-- // No codemods at all for this range (neither core nor integration).- if (versionManifests.length === 0 && !hasIntegrationCodemods) {- if (json) {- return jsonOut('upgrade.status', {- status: 'no_codemods',- from: currentVersion,- to: targetVersion,- agentDocs,- });- }- p.log.success('No codemods available for this version range.');- p.outro('Done');- return;- }-- // A named `--codemod` that matched nothing (across core + integration).- if (totalTransforms === 0 && totalOptional === 0) {- const msg = `Codemod "${options.codemod}" not found. Use --list to see available codemods.`;- if (json)- return jsonError(msg, /** @type {import('../../types/base').Suggestion[]} */ (/** @type {unknown} */ ({agentDocs})), ERROR_CODES.ERR_UNKNOWN_CODEMOD);- p.log.error(msg);- p.outro('Aborted');- process.exitCode = 1;- return;- }-- if (!json) {- if (totalTransforms > 0) {- p.log.step(- `${totalTransforms} codemod${totalTransforms === 1 ? '' : 's'} to run${options.apply ? '' : ' (dry run)'}`,- );- } else {- p.log.step('No automatic codemods to run for this version range.');- }- }-- /**- * Terminal upgrade receipt. NOTE: the shape emitted here (with- * `integrations`, `filesChanged`, `transformsApplied`, `errors`) is what- * the command has always produced and what upgrade.test/config-ordering- * assert on; it does NOT match `UpgradeRunResponse.data` in- * types/upgrade.d.ts (which declares a stale `depsUpdated` field and omits- * these). The jsonOut call below is cast to bridge that drift. See the- * report: types/upgrade.d.ts needs reconciling with the real envelope.- * @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),- // Refreshed up front (before the gates above), so the receipt just- // reports what happened. `agentDocsRefreshed` kept for back-compat.- agentDocsRefreshed: agentDocs.refreshed,- agentDocs,- };- // Run file-based integration codemods alongside the core registry- // codemods (config codemods first, then code codemods), ordered by- // version. Their results are merged into the receipt below.- let integrationResult = null;- if (hasIntegrationCodemods) {- if (!json) p.log.step('Applying integration codemods...');- const jscodeshift = (await import('jscodeshift')).default;- integrationResult = runIntegrationCodemods(integrationVersionGroups, {- apply: options.apply,- path: options.path,- codemod: options.codemod,- skipCodemods,- jscodeshift,- silent: json,- });- }--- // Merge core + integration codemod results into a single accounting so- // hooks, receipts, and error gating see both.- 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 ?? []),- ];-- // Post-codemod hooks come from the app config (config.hooks.postCodemod).- // They run only when codemods actually changed files. In apply mode the- // commands execute (nonzero exit fails the upgrade); in dry-run mode we- // only preview the resolved command (a buildCommand throw still fails).- const changedFileCount = mergedFilesChanged;- if (postCodemodHooks.length > 0 && changedFileCount > 0) {- const absoluteChangedFiles = uniqueFiles(mergedWrittenFiles);- const files = absoluteChangedFiles.map(file =>- path.relative(process.cwd(), file),- );- try {- await runPostCodemodHooks(- postCodemodHooks,- {- packageDir: process.cwd(),- files,- apply: options.apply,- },- json,- );- } catch (err) {- const hookErr = /** @type {Error} */ (err);- if (json)- return jsonError(- `Post-codemod hook failed: ${hookErr.message}`,- /** @type {import('../../types/base').Suggestion[]} */ (/** @type {unknown} */ ({receipt})),- ERROR_CODES.ERR_CODEMOD_FAILED,- );- p.log.error(`Post-codemod hook failed: ${hookErr.message}`);- p.outro('Upgrade failed');- process.exitCode = 1;- return;- }- }-- // NOTE: the managed agent-docs block was already refreshed up front (see- // refreshAgentDocs after installed-version detection), so it stays in sync- // even on the short-circuit paths that return before this point.-- 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'}.`;- if (json) {- return jsonError(msg, /** @type {import('../../types/base').Suggestion[]} */ (/** @type {unknown} */ ({receipt})), ERROR_CODES.ERR_CODEMOD_FAILED);- }- p.outro('Upgrade failed');- process.exitCode = 1;- return;- }-- if (json) {- // The emitted receipt intentionally differs from UpgradeRunResponse.data- // (see the typedef note above and the report): cast to the declared- // envelope shape until types/upgrade.d.ts is reconciled.- return jsonOut(- 'upgrade.run',- /** @type {import('../../types/upgrade').UpgradeRunResponse['data']} */ (- /** @type {unknown} */ (receipt)- ),- );- }- p.outro(options.apply ? 'Upgrade complete' : 'Dry run complete');- });+ if (json) jsonOut(result.type, result.data);+ },+ );}diff --git a/packages/cli/lib/term-log.mjs b/packages/cli/lib/term-log.mjsindex 03f52f2bab..5f32bf4788 100644--- a/packages/cli/lib/term-log.mjs+++ b/packages/cli/lib/term-log.mjs@@ -17,6 +17,12 @@** Call sites use it as `import * as p from './term-log.mjs'` and call* `p.log.info(...)`, `p.intro(...)`, `p.outro(...)`.+ *+ * For API functions that emit progress without knowing how it's rendered, this+ * module also exports an *injectable* flat logger (`CliLogger`): the CLI passes+ * `termLogger` (routes here → stdout, suppressed in --json); programmatic+ * callers get the silent `noopLogger` default, so a scripted API call stays+ * quiet even though it isn't in --json mode.*/import {humanLog} from './json.mjs';@@ -55,3 +61,41 @@ export function intro(title) {export function outro(message) {humanLog(`${toStr(message)}\n`);}++/**+ * Injectable flat logger for API functions (side-effecting/long-running+ * commands like upgrade). The API calls `logger.step(...)` etc. and defaults to+ * `noopLogger`; the CLI hands it `termLogger`. Purely presentation — the API+ * still returns its `{type, data}` result / throws.+ *+ * @typedef {object} CliLogger+ * @property {(m?: unknown) => void} intro+ * @property {(m?: unknown) => void} step+ * @property {(m?: unknown) => void} info+ * @property {(m?: unknown) => void} warn+ * @property {(m?: unknown) => void} success+ * @property {(m?: unknown) => void} error+ * @property {(m?: unknown) => void} outro+ */++/** Silent logger — the default for programmatic API callers. @type {CliLogger} */+export const noopLogger = {+ intro() {},+ step() {},+ info() {},+ warn() {},+ success() {},+ error() {},+ outro() {},+};++/** term-log-backed logger — used by the CLI in human (non --json) mode. @type {CliLogger} */+export const termLogger = {+ intro: msg => intro(msg),+ step: msg => log.step(msg),+ info: msg => log.info(msg),+ warn: msg => log.warn(msg),+ success: msg => log.success(msg),+ error: msg => log.error(msg),+ outro: msg => outro(msg),+};diff --git a/packages/cli/types/api.d.ts b/packages/cli/types/api.d.tsindex 7bd6bfa4d6..d24b78fb86 100644--- a/packages/cli/types/api.d.ts+++ b/packages/cli/types/api.d.ts@@ -54,6 +54,11 @@ import type {ValidateIntegrationResponse} from './validate-integration';import type {AstryxIntegrationIssue} from './integration';import type {BuildHelpResponse, BuildKitResponse} from './build';import type {SwizzleListResponse, SwizzleCopyResponse} from './swizzle';+import type {+ UpgradeListResponse,+ UpgradeStatusResponse,+ UpgradeRunResponse,+} from './upgrade';import type {Suggestion} from './base';/** Structured API error with a stable machine-readable code. */@@ -301,3 +306,36 @@ export declare function summarizeIssues(issues: AstryxIntegrationIssue[]): {errors: number;warnings: number;};++// ── Upgrade ──────────────────────────────────────────────────────────++export interface UpgradeOptions {+ /** Version before the dependency bump (required unless `list`). */+ from?: string;+ /** Write changes to disk (default: dry-run). */+ apply?: boolean;+ /** Run codemods even if `from` >= installed. */+ force?: boolean;+ /** Run a single named transform. */+ codemod?: string;+ /** Exclude named codemods (re-run past a failure). */+ skipCodemod?: string[];+ /** Explicit integration package names / file paths. */+ integration?: string[];+ /** Source directory to scan (default `./src`). */+ path?: string;+ /** Auto-install jscodeshift without prompting. */+ installDeps?: boolean;+ /** Return the available codemods instead of running. */+ list?: boolean;+}++/**+ * Run the version-to-version upgrade pipeline (codemods + agent-docs refresh).+ * Performs the effect in `apply` mode and returns a receipt; throws AstryxError+ * on failure.+ */+export declare function upgrade(+ options?: UpgradeOptions,+ ctx?: {cwd?: string},+): Promise<UpgradeListResponse | UpgradeStatusResponse | UpgradeRunResponse>;