An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): add the upgrade receipt to the codemod failure error (#7993)
EJ Hammond04434e7dedce
diff --git a/.changeset/upgrade-receipt-on-failure.md b/.changeset/upgrade-receipt-on-failure.mdnew file mode 100644index 0000000000..71e9491d48--- /dev/null+++ b/.changeset/upgrade-receipt-on-failure.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] A failed `astryx upgrade` now says which files it already changed. When a codemod or post-codemod hook fails, the upgrade still writes every other change; the `--json` error (`{"error", "code": "ERR_CODEMOD_FAILED"}`) now adds a `receipt` with the same fields a finished run returns (`modifiedFiles`, `errors`, `protectedFiles`, `complete: false`, `errorCode`), and the error `upgrade()` rejects with carries it as `receipt`. The change is additive: the error code, the error shape, `isError()`, the rejection and exit code 1 are unchanged. An error that stops the run after codemods have written files, such as an astryx.config that fails validation, carries a `receipt` too.++@ejhammonddiff --git a/packages/cli/README.md b/packages/cli/README.mdindex ceb1476183..8860c10903 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -209,7 +209,7 @@ if (isError(result)) {| `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to init. || `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. || `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |-| `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |+| `ERR_CODEMOD_FAILED` | A codemod or post-codemod hook failed during an upgrade run; the error carries a `receipt` that lists the files the run already changed. || `ERR_CODEMOD_PROTECTED` | A required codemod change remains blocked by a protected consumer file. || `ERR_CODEMOD_PROTECTION_SOURCE` | A working-tree protection declaration could not be read or parsed. || `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |diff --git a/packages/cli/api/upgrade/run/failure-receipt.test.mjs b/packages/cli/api/upgrade/run/failure-receipt.test.mjsnew file mode 100644index 0000000000..e2520083bc--- /dev/null+++ b/packages/cli/api/upgrade/run/failure-receipt.test.mjs@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file A failed upgrade keeps its error contract and adds the receipt: the+ * thrown AstryxError still carries ERR_CODEMOD_FAILED, and its `receipt`+ * names the files the run already changed, from the folder the command ran+ * in. Core codemods come from a stubbed registry so the contract is tested+ * apart from any one shipped codemod.+ */++import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++vi.mock('../../../assets/codemods/registry.mjs', async importOriginal => {+ const actual = /** @type {Record<string, unknown>} */ (+ await importOriginal()+ );+ return {+ ...actual,+ getTransformsBetween: async () => [+ {+ version: '0.2.0',+ transforms: [+ {+ name: 'rename-foo',+ meta: {title: 'Rename foo', fileExtensions: ['.ts']},+ /** @param {{source: string}} file */+ transform: file => file.source.replace(/foo/g, 'bar'),+ },+ {+ name: 'fail-on-boom',+ meta: {title: 'Fail on boom', fileExtensions: ['.ts']},+ /** @param {{source: string}} file */+ transform(file) {+ if (file.source.includes('boom')) throw new Error('codemod boom');+ return undefined;+ },+ },+ ],+ },+ ],+ };+});++const {upgrade} = await import('../upgrade.mjs');+const {AstryxError} = await import('../../error.mjs');+const {toErrorEnvelope} = await import('../../../foundation/response/json.mjs');+const {isError} = await import('../../json/parse.mjs');++let dir;++/** @param {string} rel @param {string} body */+function write(rel, body) {+ fs.mkdirSync(path.dirname(path.join(dir, rel)), {recursive: true});+ fs.writeFileSync(path.join(dir, rel), body);+}++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-failure-receipt-'));+ write(+ 'package.json',+ JSON.stringify({name: 'x', dependencies: {'@astryxdesign/core': '0.2.0'}}),+ );+ write(+ 'node_modules/@astryxdesign/core/package.json',+ JSON.stringify({name: '@astryxdesign/core', version: '0.2.0'}),+ );+ write('src/index.ts', 'const foo = 1;\n');+ write('src/broken.ts', 'const boom = 1;\n');+});++afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));++/** @param {Promise<unknown>} promise */+async function rejection(promise) {+ try {+ await promise;+ } catch (err) {+ return /** @type {any} */ (err);+ }+ throw new Error('expected upgrade() to reject');+}++describe('a failed upgrade', () => {+ it('still rejects with ERR_CODEMOD_FAILED, and the error carries the receipt', async () => {+ const err = await rejection(+ upgrade({from: '0.1.0', apply: true, path: 'src'}, {cwd: dir}),+ );++ expect(err).toBeInstanceOf(AstryxError);+ expect(err.code).toBe('ERR_CODEMOD_FAILED');+ expect(err.message).toBe('Upgrade completed with 1 codemod error.');+ expect(err.receipt).toMatchObject({+ complete: false,+ errorCode: 'ERR_CODEMOD_FAILED',+ filesChanged: 1,+ modifiedFiles: ['src/index.ts'],+ errors: [+ {+ file: 'src/broken.ts',+ codemod: 'core:fail-on-boom',+ error: 'codemod boom',+ },+ ],+ });+ expect(fs.readFileSync(path.join(dir, 'src/index.ts'), 'utf8')).toBe(+ 'const bar = 1;\n',+ );+ });++ it('names receipt files from the folder the command ran in', async () => {+ const err = await rejection(+ upgrade(+ {from: '0.1.0', apply: true, path: '.'},+ {cwd: path.join(dir, 'src')},+ ),+ );++ expect(err.code).toBe('ERR_CODEMOD_FAILED');+ expect(err.receipt.modifiedFiles).toEqual(['index.ts']);+ expect(err.receipt.errors).toEqual([+ expect.objectContaining({file: 'broken.ts'}),+ ]);+ });++ it('becomes an error envelope that keeps its code and adds the receipt', async () => {+ const err = await rejection(+ upgrade({from: '0.1.0', path: 'src'}, {cwd: dir}),+ );++ const envelope = toErrorEnvelope(err);+ expect(isError(envelope)).toBe(true);+ expect(envelope).toMatchObject({+ apiVersion: 1,+ code: 'ERR_CODEMOD_FAILED',+ error: 'Upgrade completed with 1 codemod error.',+ receipt: {modifiedFiles: ['src/index.ts'], complete: false},+ });+ expect(fs.readFileSync(path.join(dir, 'src/index.ts'), 'utf8')).toBe(+ 'const foo = 1;\n',+ );+ });+});++describe('the error envelope', () => {+ it('has no receipt for an error that carries none', () => {+ expect(+ toErrorEnvelope(+ new AstryxError('nope', undefined, 'ERR_INVALID_ARGUMENT'),+ ),+ ).toEqual({apiVersion: 1, error: 'nope', code: 'ERR_INVALID_ARGUMENT'});+ });+});diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjsindex 2cc10c17f3..705ca3aca4 100644--- a/packages/cli/api/upgrade/run/run.mjs+++ b/packages/cli/api/upgrade/run/run.mjs@@ -109,6 +109,80 @@ function loadFileProtection(cwd) {}}+/**+ * The receipt of a run that stopped after codemods ran. Whatever the codemods+ * already wrote stays on disk, so the error the run throws carries this+ * receipt (`failWithReceipt`): a caller that reads only the error would+ * report nothing changed while the files it lists remain modified+ * (spec:AST-040 FR7).+ *+ * @param {{from: string, to: string, codemods: number, integrations: string[], sourcePathFound: boolean, cwd: string, changedFiles: string[], transformsApplied: number, protectedRows: Array<{file: string, codemod: string, reason: string, declaration: string, generated: boolean, command?: string}>, errors: Array<{file: string, codemod: string, error: string}>, errorCode: string, cliBehindCore?: import('../upgrade.type.mjs').CliBehindCore | null, registryCompositions?: import('../upgrade.type.mjs').RegistryCompositionSummary}} facts+ * @returns {import('../upgrade.type.mjs').UpgradeRunResponse['data']}+ */+function stoppedReceipt({+ from,+ to,+ codemods,+ integrations,+ sourcePathFound,+ cwd,+ changedFiles,+ transformsApplied,+ protectedRows,+ errors,+ errorCode,+ cliBehindCore,+ registryCompositions,+}) {+ const modifiedFiles = uniqueFiles(changedFiles).map(file =>+ path.relative(cwd, file).split(path.sep).join('/'),+ );+ return /** @type {import('../upgrade.type.mjs').UpgradeRunResponse['data']} */ ({+ from,+ to,+ codemods,+ integrations,+ agentDocsRefreshed: false,+ agentDocs: {+ status: 'current',+ installedVersion: to,+ fromVersions: [],+ files: [],+ refreshed: false,+ action: 'none',+ },+ sourcePathFound,+ filesChanged: modifiedFiles.length,+ transformsApplied,+ modifiedFiles,+ protectedFiles: summarizeProtectedFiles(protectedRows),+ declinedCandidates: [],+ complete: false,+ errorCode,+ errors,+ ...(registryCompositions ? {registryCompositions} : {}),+ ...(cliBehindCore ? {cliBehindCore} : {}),+ });+}++/**+ * The error a run throws once codemods have run: the same message and stable+ * code as always, plus the run's receipt on `receipt`, so the JSON error+ * envelope and a programmatic caller can still see what was written.+ * @param {string} message+ * @param {string} code+ * @param {import('../upgrade.type.mjs').UpgradeRunResponse['data']} receipt+ * @returns {AstryxError & {receipt: import('../upgrade.type.mjs').UpgradeRunResponse['data']}}+ */+function failWithReceipt(message, code, receipt) {+ const err =+ /** @type {AstryxError & {receipt: import('../upgrade.type.mjs').UpgradeRunResponse['data']}} */ (+ new AstryxError(message, undefined, code)+ );+ err.receipt = receipt;+ return err;+}+/*** Run the upgrade pipeline for a validated, non-list invocation. Returns the* terminal run receipt, or one of the status short-circuits; throws AstryxError@@ -368,6 +442,32 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {// Genuine config error: abort.logger.error(configErr.message);logger.log('Aborted\n');+ if ((coreResult?.writtenFiles.length ?? 0) > 0) {+ // Core codemods already wrote: the error carries what they changed.+ if (cliBehindCore) logCliBehindCore(cliBehindCore, targetVersion);+ const stopped = stoppedReceipt({+ from: currentVersion,+ to: targetVersion,+ codemods: totalTransforms,+ integrations: [],+ sourcePathFound,+ cwd,+ changedFiles: coreResult?.changedFiles ?? [],+ transformsApplied: coreResult?.totalTransformsApplied ?? 0,+ protectedRows: [],+ errors: [+ ...(coreResult?.errors ?? []),+ {file: '.', codemod: 'config', error: configErr.message},+ ],+ errorCode: ERROR_CODES.ERR_INVALID_ARGUMENT,+ cliBehindCore,+ });+ throw failWithReceipt(+ configErr.message,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ stopped,+ );+ }throw new AstryxError(configErr.message,undefined,@@ -561,7 +661,30 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {logger.error(msg);if (initialProtected.length === 0) {logger.log('Upgrade failed\n');- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);+ throw failWithReceipt(+ msg,+ ERROR_CODES.ERR_CODEMOD_FAILED,+ stoppedReceipt({+ from: currentVersion,+ to: targetVersion,+ codemods: totalTransforms,+ integrations: receipt.integrations,+ sourcePathFound,+ cwd,+ changedFiles: mergedChangedFiles,+ transformsApplied: mergedTransformsApplied,+ protectedRows: [],+ errors: [+ ...mergedErrors,+ {file: '.', codemod: 'post-codemod-hook', error: msg},+ ],+ errorCode: ERROR_CODES.ERR_CODEMOD_FAILED,+ cliBehindCore,+ ...(registryResult+ ? {registryCompositions: registryResult.summary}+ : {}),+ }),+ );}hookFailure = msg;finalErrors = [@@ -587,7 +710,35 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {// to distinguish resolved outputs from changes that remain blocked.let remainingProtected = initialProtected;if (apply && shouldRunHooks && !hookFailure) {- const refreshedProtection = loadFileProtection(cwd);+ let refreshedProtection;+ try {+ refreshedProtection = loadFileProtection(cwd);+ } catch (err) {+ if (!(err instanceof AstryxError)) throw err;+ // The hooks ran after the codemods wrote; the error carries their receipt.+ if (cliBehindCore) logCliBehindCore(cliBehindCore, targetVersion);+ const stopped = stoppedReceipt({+ from: currentVersion,+ to: targetVersion,+ codemods: totalTransforms,+ integrations: receipt.integrations,+ sourcePathFound,+ cwd,+ changedFiles: [...mergedChangedFiles, ...hookModifiedFiles],+ transformsApplied: mergedTransformsApplied,+ protectedRows: initialProtected,+ errors: [+ ...mergedErrors,+ {file: '.', codemod: 'file-protection', error: err.message},+ ],+ errorCode: err.code,+ cliBehindCore,+ ...(registryResult+ ? {registryCompositions: registryResult.summary}+ : {}),+ });+ throw failWithReceipt(err.message, err.code, stopped);+ }const coreCheck = await runCoreCodemods(versionManifests, {apply: false,path: path_,@@ -654,9 +805,12 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {]).map(file => path.relative(cwd, file).split(path.sep).join('/'));receipt.protectedFiles = protectedFiles;receipt.declinedCandidates = [];- receipt.complete = protectedFiles.length === 0;- if (!receipt.complete) {+ receipt.complete = protectedFiles.length === 0 && finalErrors.length === 0;+ if (protectedFiles.length > 0) {receipt.errorCode = 'ERR_CODEMOD_PROTECTED';+ } else if (finalErrors.length > 0) {+ // Only on the receipt the thrown error carries (below).+ receipt.errorCode = 'ERR_CODEMOD_FAILED';}receipt.errors = finalErrors;if (registryResult) receipt.registryCompositions = registryResult.summary;@@ -674,14 +828,22 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {}}- if (receipt.errors?.length > 0 && protectedFiles.length === 0) {- const msg = `Upgrade completed with ${receipt.errors.length} codemod error${receipt.errors.length === 1 ? '' : 's'}.`;+ if (finalErrors.length > 0 && protectedFiles.length === 0) {+ const msg = `Upgrade completed with ${finalErrors.length} codemod error${finalErrors.length === 1 ? '' : 's'}.`;logger.log('Upgrade failed\n');- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);+ // The error carries the receipt: every file the codemods wrote before the+ // failure stays changed, and the caller keeps or reverts them knowingly.+ throw failWithReceipt(+ msg,+ ERROR_CODES.ERR_CODEMOD_FAILED,+ /** @type {import('../upgrade.type.mjs').UpgradeRunResponse['data']} */ (+ /** @type {unknown} */ (receipt)+ ),+ );}// Only refresh managed docs after all required codemod changes are complete.- if (protectedFiles.length === 0) {+ if (receipt.complete) {const agentDocsPlan = await prepareAgentDocsRefresh({cwd,origin,diff --git a/packages/cli/api/upgrade/upgrade.doc.mjs b/packages/cli/api/upgrade/upgrade.doc.mjsindex 279a5f1ef1..41a3a23631 100644--- a/packages/cli/api/upgrade/upgrade.doc.mjs+++ b/packages/cli/api/upgrade/upgrade.doc.mjs@@ -128,13 +128,13 @@ export const doc = {{type: 'upgrade.run',description:- 'The terminal run receipt: from, to, codemods (count), integrations, agentDocs, agentDocsRefreshed, registryCompositions (when receipts are found), sourcePathFound (false when the resolved `path` does not exist, so nothing was scanned), filesChanged, transformsApplied, modifiedFiles, protectedFiles, declinedCandidates, errors, and complete. When a protected file still requires a change, complete is false and errorCode is ERR_CODEMOD_PROTECTED; the CLI exits nonzero while preserving the structured receipt. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run, and command runs the same upgrade with the matching CLI.',+ 'The terminal run receipt: from, to, codemods (count), integrations, agentDocs, agentDocsRefreshed, registryCompositions (when receipts are found), sourcePathFound (false when the resolved `path` does not exist, so nothing was scanned), filesChanged, transformsApplied, modifiedFiles, protectedFiles, declinedCandidates, errors, and complete. When a protected file still requires a change, complete is false and errorCode is ERR_CODEMOD_PROTECTED; the CLI exits nonzero while preserving the structured receipt. A run that fails after its codemods ran throws instead (see throws), and the thrown AstryxError carries the same receipt on `receipt`, with complete false and errorCode set to its code. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run, and command runs the same upgrade with the matching CLI.',},],throws: [{code: 'ERR_INVALID_ARGUMENT',- when: '`from` is missing (and neither `list` nor `registry` is set); `list` and `registry` are both set; `list` is combined with `from`, `force`, `apply`, `path` (non-default), `codemod`, `skipCodemod`, `integration` or `installDeps`; `registry` is combined with `from`, `force`, `codemod`, `skipCodemod`, `integration` or `installDeps`; an `integration` specifier is invalid or not installed; or astryx.config fails to load or validate and no pending config codemod repairs it',+ when: '`from` is missing (and neither `list` nor `registry` is set); `list` and `registry` are both set; `list` is combined with `from`, `force`, `apply`, `path` (non-default), `codemod`, `skipCodemod`, `integration` or `installDeps`; `registry` is combined with `from`, `force`, `codemod`, `skipCodemod`, `integration` or `installDeps`; an `integration` specifier is invalid or not installed; or astryx.config fails to load or validate and no pending config codemod repairs it (when core codemods already wrote files, the error carries their receipt on `receipt`)',},{code: 'ERR_INVALID_VERSION', when: '`from` is not a valid semver string'},{@@ -155,11 +155,11 @@ export const doc = {},{code: 'ERR_CODEMOD_FAILED',- when: 'one or more codemods failed, or a post-codemod hook failed, and no protected file still needs a change (otherwise an upgrade.run receipt with complete: false is returned)',+ when: "one or more codemods failed, or a post-codemod hook failed, and no protected file still needs a change (otherwise an upgrade.run receipt with complete: false is returned). The error carries the run's receipt on `receipt`: the files already changed, each failure in errors, complete: false",},{code: 'ERR_CODEMOD_PROTECTION_SOURCE',- when: 'a working-tree protection declaration cannot be read or parsed before writes begin',+ when: 'a working-tree protection declaration cannot be read or parsed before writes begin, or after post-codemod hooks rewrite it (the error then carries the receipt on `receipt`)',},],examples: [diff --git a/packages/cli/api/upgrade/upgrade.mjs b/packages/cli/api/upgrade/upgrade.mjsindex d2101dd603..7ecb56b49a 100644--- a/packages/cli/api/upgrade/upgrade.mjs+++ b/packages/cli/api/upgrade/upgrade.mjs@@ -120,8 +120,23 @@ export async function upgrade(options = {}, {cwd = process.cwd()} = {}) {// A run from a subfolder upgrades the project the folder belongs to, and// names files relative to the folder it ran in.const scoped = scopeToProject(options, cwd);- return relativeToOrigin(- await run(scoped.options, {cwd: scoped.cwd, origin: scoped.origin}),- scoped,- );+ let result;+ try {+ result = await run(scoped.options, {+ cwd: scoped.cwd,+ origin: scoped.origin,+ });+ } catch (err) {+ // A failure after codemods wrote carries their receipt; name its files+ // from the folder the command ran in, as a returned receipt does.+ const receipt = /** @type {any} */ (err)?.receipt;+ if (err instanceof AstryxError && receipt) {+ /** @type {any} */ (err).receipt = relativeToOrigin(+ {type: 'upgrade.run', data: receipt},+ scoped,+ ).data;+ }+ throw err;+ }+ return relativeToOrigin(result, scoped);}diff --git a/packages/cli/api/upgrade/upgrade.type.mjs b/packages/cli/api/upgrade/upgrade.type.mjsindex f5644bdf51..d36a807f69 100644--- a/packages/cli/api/upgrade/upgrade.type.mjs+++ b/packages/cli/api/upgrade/upgrade.type.mjs@@ -131,17 +131,30 @@* @property {AgentDocsSummary} data.agentDocs* @property {boolean} data.sourcePathFound Whether the resolved source directory (`path`, default `./src`) exists. False means no source file was read, so a zero `filesChanged` says nothing about the project being migrated.* @property {RegistryCompositionSummary} [data.registryCompositions]- * @property {boolean} [data.complete] False when protected required changes remain.- * @property {'ERR_CODEMOD_PROTECTED'} [data.errorCode] Stable incomplete-result code when complete is false.+ * @property {boolean} [data.complete] False when protected required changes remain. Also false on the receipt a failed run's error carries (`UpgradeFailureReceipt`).+ * @property {string} [data.errorCode] Stable incomplete-result code when complete is false: `ERR_CODEMOD_PROTECTED` on a returned receipt; on the receipt a failed run's error carries, the error's own code.* @property {number} [data.filesChanged] Distinct files changed across core + integration codemods (apply mode). One file that four codemods each changed counts once.* @property {string[]} [data.modifiedFiles] Files changed or previewed, relative to the folder the command ran in.* @property {ProtectedCodemodFile[]} [data.protectedFiles] Protected files that still require a codemod change after regeneration.* @property {Array<{file: string, location?: string, reason: string}>} [data.declinedCandidates] Candidates left unchanged because proof was insufficient. Each `file` is relative to the folder the command ran in.* @property {number} [data.transformsApplied] Total codemod changes. A code or config codemod counts once for each file it changed, so one file changed by four of them counts four times; a project codemod counts once, however many files it writes.- * @property {Array<{file: string, codemod: string, error: string}>} [data.errors] Per-codemod errors, when any codemod failed. Each `file` is relative to the folder the command ran in.+ * @property {Array<{file: string, codemod: string, error: string}>} [data.errors] Per-codemod errors, when any codemod failed. On the receipt a failed run's error carries, also a post-codemod hook failure (`codemod: 'post-codemod-hook'`) or the error that stopped the run after codemods wrote files. Each `file` is relative to the folder the command ran in.* @property {CliBehindCore} [data.cliBehindCore] Present only when the installed Core is newer than this CLI: codemods for the releases after `cliBehindCore.cliVersion` did not run.*/+/**+ * What a failed upgrade had already done. When a run fails after its codemods+ * ran (a codemod or post-codemod hook failed, or an error stopped it after+ * codemods wrote files), the failure keeps its usual shape: the --json error+ * envelope `{apiVersion, error, code}` and a rejected `upgrade()` with that+ * `code`. The envelope adds `receipt`, and the thrown AstryxError a `receipt`+ * property: the same `upgrade.run` data a completed run returns, with+ * `complete: false` and `errorCode` equal to the error's `code`. Files in+ * `modifiedFiles` stay changed.+ *+ * @typedef {UpgradeRunResponse['data']} UpgradeFailureReceipt+ */+/*** astryx --json upgrade — short-circuit status results.*diff --git a/packages/cli/clients/cli/commands/upgrade.doc.mjs b/packages/cli/clients/cli/commands/upgrade.doc.mjsindex 587f64c2d3..dda9a1a700 100644--- a/packages/cli/clients/cli/commands/upgrade.doc.mjs+++ b/packages/cli/clients/cli/commands/upgrade.doc.mjs@@ -201,5 +201,15 @@ export const doc = {'`Command:` line in its header, such as `// Command: pnpm run gen:panel`; upgrade prints it as ' +'`Regenerate with: <command>` and lists it in `commands`.',},+ {type: 'heading', level: 3, text: 'A failed codemod'},+ {+ type: 'prose',+ text:+ 'When a codemod or a `hooks.postCodemod` command fails, upgrade still makes every other change, exits 1 with ERR_CODEMOD_FAILED, and does not refresh the agent docs. ' ++ 'With --json, the result is the usual error, `{"error": ..., "code": "ERR_CODEMOD_FAILED"}`, plus a `receipt`: the same fields a finished run returns, with `complete: false`, ' ++ 'each failure in `errors`, and every file upgrade changed (or would change) in `modifiedFiles`, so a script can review, keep, or revert them. ' ++ 'An error that stops the run after codemods have written files, such as an astryx.config that fails validation, carries a `receipt` too. ' ++ 'Rerun past a failed codemod with --skip-codemod.',+ },],};diff --git a/packages/cli/clients/cli/commands/upgrade.file-protection.test.mjs b/packages/cli/clients/cli/commands/upgrade.file-protection.test.mjsindex 6eda9be6cf..b772ae067d 100644--- a/packages/cli/clients/cli/commands/upgrade.file-protection.test.mjs+++ b/packages/cli/clients/cli/commands/upgrade.file-protection.test.mjs@@ -199,6 +199,35 @@ describe('upgrade protected-file contract', () => {});});+ it('keeps the error and adds the receipt when a hook leaves a protection declaration unreadable', () => {+ seed();+ write(+ 'astryx.config.mjs',+ `export default {hooks: {postCodemod: [{name: 'regenerate', buildCommand: () => ({command: process.execPath, args: ['-e', ${JSON.stringify("require('node:fs').writeFileSync('.hgignore', 'syntax: regexp\\n[bad\\n')")}]})}]}};\n`,+ );++ const applied = run([...ARGS, '--apply']);++ expect(applied.status).toBe(1);+ expect(applied.envelope).not.toHaveProperty('type');+ expect(applied.envelope).toMatchObject({+ code: 'ERR_CODEMOD_PROTECTION_SOURCE',+ error: expect.stringContaining('.hgignore'),+ receipt: {+ complete: false,+ errorCode: 'ERR_CODEMOD_PROTECTION_SOURCE',+ modifiedFiles: ['src/owned.tsx'],+ protectedFiles: [+ expect.objectContaining({file: 'generated/panel.tsx'}),+ ],+ errors: [expect.objectContaining({codemod: 'file-protection'})],+ },+ });+ expect(fs.readFileSync(path.join(root, 'src/owned.tsx'), 'utf8')).toContain(+ 'minSize: 200',+ );+ });+it('runs declared regeneration and clears a generated-file block after reevaluation', () => {seed({hook: true});diff --git a/packages/cli/clients/cli/commands/upgrade.flag-help.test.mjs b/packages/cli/clients/cli/commands/upgrade.flag-help.test.mjsindex db78e1ab41..83afe92d14 100644--- a/packages/cli/clients/cli/commands/upgrade.flag-help.test.mjs+++ b/packages/cli/clients/cli/commands/upgrade.flag-help.test.mjs@@ -175,6 +175,43 @@ describe('astryx upgrade exit codes', () => {expect(status).toBe(1);expect(envelope.code).toBe('ERR_CODEMOD_FAILED');expect(envelope.error).toMatch(/Post-codemod hook failed/);+ // Additive: the receipt names what the run had already changed.+ expect(envelope).toMatchObject({+ receipt: {+ complete: false,+ errorCode: 'ERR_CODEMOD_FAILED',+ modifiedFiles: ['src/panel.tsx'],+ errors: [+ expect.objectContaining({+ codemod: 'post-codemod-hook',+ error: expect.stringMatching(/Post-codemod hook failed/),+ }),+ ],+ },+ });+ }, SLOW);++ it('reports what core codemods wrote when astryx.config then fails validation', async () => {+ installPackage('@astryxdesign/core', '0.6.0');+ write(+ 'src/panel.tsx',+ "import {useResizable} from '@astryxdesign/core';\nexport const r = () => useResizable({minSizePx: 200});\n",+ );+ write('astryx.config.mjs', "export default {theme: 'neutral'};\n");+ const {status, envelope} = await upgradeJson(['--from', '0.5.0', '--apply']);+ expect(status).toBe(1);+ expect(envelope).toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ receipt: {+ complete: false,+ errorCode: 'ERR_INVALID_ARGUMENT',+ modifiedFiles: ['src/panel.tsx'],+ errors: [expect.objectContaining({codemod: 'config'})],+ },+ });+ expect(fs.readFileSync(path.join(tmpDir, 'src/panel.tsx'), 'utf8')).toContain(+ 'minSize: 200',+ );}, SLOW);it('lists a missing jscodeshift and the refused flag combinations', () => {diff --git a/packages/cli/clients/cli/commands/upgrade.integration-policy.test.mjs b/packages/cli/clients/cli/commands/upgrade.integration-policy.test.mjsindex 21311b6c3d..69e4a21664 100644--- a/packages/cli/clients/cli/commands/upgrade.integration-policy.test.mjs+++ b/packages/cli/clients/cli/commands/upgrade.integration-policy.test.mjs@@ -17,6 +17,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {Command} from 'commander';import {registerUpgrade} from './upgrade.mjs';+import {isError} from '../../../api/json/parse.mjs';import {Project} from '../../../foundation/config/project.mjs';import {generateCompressedIndex,@@ -47,6 +48,7 @@ beforeEach(() => {});afterEach(() => {+ process.exitCode = undefined;process.chdir(originalCwd);fs.rmSync(tmpDir, {recursive: true, force: true});vi.restoreAllMocks();@@ -298,6 +300,13 @@ describe('upgrade integration error policy (skip + warn)', () => {]);expect(result.code).toBe('ERR_CODEMOD_FAILED');+ expect(result.receipt).toMatchObject({+ complete: false,+ errorCode: 'ERR_CODEMOD_FAILED',+ agentDocsRefreshed: false,+ modifiedFiles: ['src/index.ts'],+ errors: [expect.objectContaining({codemod: 'post-codemod-hook'})],+ });expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(before,);@@ -476,3 +485,97 @@ describe('upgrade integration error policy (skip + warn)', () => {expect(out).not.toContain('bar');});});++describe('upgrade failure receipt when a codemod fails', () => {+ const codemods = {+ '0.2.0/drop-foo.mjs': `export default {type: 'code', title: 'Drop foo', transform: file => file.source.replace(/foo/g, 'bar')};\n`,+ '0.2.0/fail.mjs': `export default {type: 'code', title: 'Fail on boom', transform: file => { if (file.source.includes('boom')) throw new Error('codemod boom'); return undefined; }};\n`,+ };++ function scaffold() {+ scaffoldIntegration(codemods);+ writeInstalledCore('0.2.0');+ writeSource();+ fs.writeFileSync(path.join(tmpDir, 'src', 'broken.ts'), 'const boom = 1;\n');+ }++ const ARGS = ['upgrade', '--from', '0.1.0', '--path', 'src'];++ it('keeps the error envelope and adds the receipt of what was written', async () => {+ scaffold();++ const result = await runJson(['--json', ...ARGS, '--apply']);++ expect(exitCode).toBe(1);+ expect(isError(result)).toBe(true);+ expect(result).not.toHaveProperty('type');+ expect(result).toMatchObject({+ apiVersion: 1,+ code: 'ERR_CODEMOD_FAILED',+ error: 'Upgrade completed with 1 codemod error.',+ receipt: {+ complete: false,+ errorCode: 'ERR_CODEMOD_FAILED',+ filesChanged: 1,+ modifiedFiles: ['src/index.ts'],+ protectedFiles: [],+ errors: [+ {+ file: 'src/broken.ts',+ codemod: '@acme/widgets:fail',+ error: 'codemod boom',+ },+ ],+ },+ });+ expect(fs.readFileSync(path.join(tmpDir, 'src', 'index.ts'), 'utf-8')).toBe(+ 'const bar = 1;\n',+ );+ });++ it('previews the same receipt in a dry run without writing', async () => {+ scaffold();++ const result = await runJson(['--json', ...ARGS]);++ expect(result.code).toBe('ERR_CODEMOD_FAILED');+ expect(result.receipt).toMatchObject({+ complete: false,+ modifiedFiles: ['src/index.ts'],+ errors: [expect.objectContaining({file: 'src/broken.ts'})],+ });+ expect(fs.readFileSync(path.join(tmpDir, 'src', 'index.ts'), 'utf-8')).toBe(+ 'const foo = 1;\n',+ );+ });++ it('still returns the protected-file receipt when a protected file remains', async () => {+ scaffold();+ fs.writeFileSync(+ path.join(tmpDir, 'src', 'gen.ts'),+ '// @generated\nconst foo = 2;\n',+ );++ const result = await runJson(['--json', ...ARGS, '--apply']);++ expect(result).toMatchObject({+ type: 'upgrade.run',+ data: {+ complete: false,+ errorCode: 'ERR_CODEMOD_PROTECTED',+ protectedFiles: [expect.objectContaining({file: 'src/gen.ts'})],+ errors: [expect.objectContaining({file: 'src/broken.ts'})],+ },+ });+ });++ it('keeps the human output and exit status in text mode', async () => {+ scaffold();++ await runJson([...ARGS, '--apply']);++ expect(process.exitCode).toBe(1);+ expect(logCalls.join('\n')).toMatch(/Upgrade failed/);+ expect(logCalls.join('\n')).not.toMatch(/"receipt"/);+ });+});diff --git a/packages/cli/clients/cli/commands/upgrade.mjs b/packages/cli/clients/cli/commands/upgrade.mjsindex aea6ea4a46..85731c7075 100644--- a/packages/cli/clients/cli/commands/upgrade.mjs+++ b/packages/cli/clients/cli/commands/upgrade.mjs@@ -57,8 +57,15 @@ export function registerUpgrade(program) {// already printed the error before throwing.logger.setSilent(json);if (e instanceof AstryxError) {- if (json) jsonError(e.message, undefined, e.code);- else {+ if (json) {+ // A failed migration still names the files it already changed.+ jsonError(+ e.message,+ undefined,+ e.code,+ /** @type {any} */ (e).receipt,+ );+ } else {// The logger was silent only for --list; replay the error there.// Non-list failures were already printed by the API.if (isList) logger.error(e.message);diff --git a/packages/cli/foundation/response/base.d.ts b/packages/cli/foundation/response/base.d.tsindex 0f816420eb..a2c6707214 100644--- a/packages/cli/foundation/response/base.d.ts+++ b/packages/cli/foundation/response/base.d.ts@@ -34,6 +34,13 @@ export interface CLIError {error: string;code: ErrorCode;suggestions?: Suggestion[];+ /**+ * What the command had already done when it failed, present only on errors+ * from a command that changes files before it can fail (for example the+ * `upgrade.run` data of a failed `astryx upgrade`). The error is still an+ * error: branch on `code`.+ */+ receipt?: Record<string, unknown>;}/** Returned by the fallback hook for commands without --json support. */diff --git a/packages/cli/foundation/response/error-codes.doc.mjs b/packages/cli/foundation/response/error-codes.doc.mjsindex f529e32042..e0ff41521d 100644--- a/packages/cli/foundation/response/error-codes.doc.mjs+++ b/packages/cli/foundation/response/error-codes.doc.mjs@@ -150,7 +150,8 @@ export const doc = {},{value: 'ERR_CODEMOD_FAILED',- description: 'One or more codemods failed during an upgrade run.',+ description:+ 'A codemod or post-codemod hook failed during an upgrade run; the error carries a `receipt` that lists the files the run already changed.',},{value: 'ERR_CODEMOD_PROTECTED',@@ -282,7 +283,7 @@ export const doc = {{value: 'ERR_VERSIONS_UNAVAILABLE',description:- 'Nothing could answer this run, and nothing was written: the project\'s own CLI could not start and nothing else could answer, or the Core a command needs outside a project could not be installed.',+ "Nothing could answer this run, and nothing was written: the project's own CLI could not start and nothing else could answer, or the Core a command needs outside a project could not be installed.",},{value: 'ERR_PROJECT_REQUIRED',diff --git a/packages/cli/foundation/response/error-codes.mjs b/packages/cli/foundation/response/error-codes.mjsindex fbb36fdcac..abd6e833d9 100644--- a/packages/cli/foundation/response/error-codes.mjs+++ b/packages/cli/foundation/response/error-codes.mjs@@ -172,7 +172,7 @@ export const ERROR_CODES = Object.freeze({ERR_UNKNOWN_FEATURE: 'ERR_UNKNOWN_FEATURE',/** A `--codemod` value did not match any registered codemod (upgrade). */ERR_UNKNOWN_CODEMOD: 'ERR_UNKNOWN_CODEMOD',- /** One or more codemods failed during an upgrade run. */+ /** One or more codemods, or a post-codemod hook, failed during an upgrade run. */ERR_CODEMOD_FAILED: 'ERR_CODEMOD_FAILED',/** A required codemod change remains blocked by a protected consumer file. */ERR_CODEMOD_PROTECTED: 'ERR_CODEMOD_PROTECTED',diff --git a/packages/cli/foundation/response/json.mjs b/packages/cli/foundation/response/json.mjsindex 55b1f2920e..9552c17cff 100644--- a/packages/cli/foundation/response/json.mjs+++ b/packages/cli/foundation/response/json.mjs@@ -134,9 +134,13 @@ export function jsonOut(response) {* @param {import('./base').Suggestion[]} [suggestions]* @param {string} [code] - Explicit stable error code. Overrides any code* carried on a thrown Error.- * @returns {{apiVersion: number, error: string, code: string, suggestions?: import('./base').Suggestion[]}}+ * @param {Record<string, unknown>} [receipt] - What the failed command had+ * already done, for a command that changes files before it can fail.+ * Overrides a `receipt` carried on a thrown Error. Additive: the envelope+ * is still an error with its `code`.+ * @returns {{apiVersion: number, error: string, code: string, suggestions?: import('./base').Suggestion[], receipt?: Record<string, unknown>}}*/-export function toErrorEnvelope(err, suggestions, code) {+export function toErrorEnvelope(err, suggestions, code, receipt) {const message =err instanceof Error ? err.message : typeof err === 'string' ? err : String(err);const carried =@@ -145,6 +149,12 @@ export function toErrorEnvelope(err, suggestions, code) {/** @type {any} */const env = {apiVersion: API_VERSION, error: message, code: resolvedCode};if (Array.isArray(suggestions) && suggestions.length) env.suggestions = suggestions;+ const carriedReceipt =+ err && typeof err === 'object' ? /** @type {any} */ (err).receipt : undefined;+ const resolvedReceipt = receipt ?? carriedReceipt;+ if (resolvedReceipt && typeof resolvedReceipt === 'object') {+ env.receipt = resolvedReceipt;+ }return env;}@@ -153,10 +163,12 @@ export function toErrorEnvelope(err, suggestions, code) {* @param {string} message* @param {import('./base').Suggestion[]} [suggestions]* @param {string} [code] - Stable machine-readable error code (error-codes.mjs).+ * @param {Record<string, unknown>} [receipt] - What the command had already+ * done before it failed (see toErrorEnvelope).*/-export function jsonError(message, suggestions, code) {+export function jsonError(message, suggestions, code, receipt) {process.__xdsJsonHandled = true;- const err = toErrorEnvelope(message, suggestions, code);+ const err = toErrorEnvelope(message, suggestions, code, receipt);// No-op when cliError already classified this failure — first outcome wins.setOutcome('error', {exitCode: 1, error: new Error(message), code: err.code});console.log(JSON.stringify(err, null, 2));