@astryxdesign/cli 0.7.5-canary.d4f09c2 → 0.7.5-canary.d695efb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +1 -1
  2. package/api/upgrade/_adapter.d.mts +2 -0
  3. package/api/upgrade/run/failure-receipt.test.mjs +212 -0
  4. package/api/upgrade/run/run.mjs +251 -10
  5. package/api/upgrade/upgrade.doc.mjs +4 -4
  6. package/api/upgrade/upgrade.mjs +19 -4
  7. package/api/upgrade/upgrade.type.d.mts +12 -1
  8. package/api/upgrade/upgrade.type.mjs +17 -4
  9. package/assets/codemods/__tests__/runner.symlinks.test.mjs +205 -0
  10. package/assets/codemods/__tests__/runner.unparseable.test.mjs +457 -0
  11. package/assets/codemods/integration-runner.mjs +8 -2
  12. package/assets/codemods/integration-runner.protection.test.mjs +53 -0
  13. package/assets/codemods/parse.mjs +94 -0
  14. package/assets/codemods/run-codemod.mjs +109 -5
  15. package/assets/codemods/runner.mjs +108 -10
  16. package/assets/codemods/transform-prop.mjs +99 -49
  17. package/assets/codemods/transform-prop.test.mjs +36 -1
  18. package/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs +216 -2
  19. package/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs +88 -6
  20. package/assets/codemods/transforms/v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs +4 -3
  21. package/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs +207 -6
  22. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface-v0.6-data.mjs +6 -1
  23. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +244 -42
  24. package/assets/docs/tree/styling-advanced.doc.mjs +1 -1
  25. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.doc.mjs +1 -1
  26. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.tsx +10 -2
  27. package/assets/templates/pages/library/page.tsx +1 -2
  28. package/authoring/codemod/type.ts +10 -0
  29. package/clients/cli/commands/upgrade.doc.mjs +27 -0
  30. package/clients/cli/commands/upgrade.file-protection.test.mjs +175 -0
  31. package/clients/cli/commands/upgrade.flag-help.test.mjs +37 -0
  32. package/clients/cli/commands/upgrade.integration-policy.test.mjs +103 -0
  33. package/clients/cli/commands/upgrade.mjs +9 -2
  34. package/foundation/response/base.d.ts +7 -0
  35. package/foundation/response/error-codes.doc.mjs +3 -2
  36. package/foundation/response/error-codes.mjs +1 -1
  37. package/foundation/response/json.d.mts +10 -3
  38. package/foundation/response/json.mjs +16 -4
  39. package/package.json +10 -9
package/README.md CHANGED
@@ -209,7 +209,7 @@ if (isError(result)) {
209
209
  | `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to init. |
210
210
  | `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. |
211
211
  | `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |
212
- | `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |
212
+ | `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. |
213
213
  | `ERR_CODEMOD_PROTECTED` | A required codemod change remains blocked by a protected consumer file. |
214
214
  | `ERR_CODEMOD_PROTECTION_SOURCE` | A working-tree protection declaration could not be read or parsed. |
215
215
  | `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |
@@ -206,6 +206,7 @@ export function runCoreCodemods(versionManifests: CoreVersionManifest[], { apply
206
206
  writtenFiles: string[];
207
207
  stagedContents: Map<string, string>;
208
208
  protectedFiles: import("../../authoring/codemod/type").CodemodRunResult["protectedFiles"];
209
+ declinedCandidates: NonNullable<import("../../authoring/codemod/type").CodemodRunResult["declinedCandidates"]>;
209
210
  errors: Array<{
210
211
  file: string;
211
212
  codemod: string;
@@ -301,6 +302,7 @@ export function runIntegrationCodemodsStep(versionGroups: Array<{
301
302
  writtenFiles: string[];
302
303
  stagedContents: Map<string, string>;
303
304
  protectedFiles: import("../../authoring/codemod/type").CodemodRunResult["protectedFiles"];
305
+ declinedCandidates: NonNullable<import("../../authoring/codemod/type").CodemodRunResult["declinedCandidates"]>;
304
306
  errors: Array<{
305
307
  file: string;
306
308
  codemod: string;
@@ -0,0 +1,212 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file A failed upgrade keeps its error contract and adds the receipt: the
5
+ * thrown AstryxError still carries ERR_CODEMOD_FAILED, and its `receipt`
6
+ * names the files the run already changed, from the folder the command ran
7
+ * in. Core codemods come from a stubbed registry so the contract is tested
8
+ * apart from any one shipped codemod.
9
+ */
10
+
11
+ import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
12
+ import * as fs from 'node:fs';
13
+ import * as os from 'node:os';
14
+ import * as path from 'node:path';
15
+
16
+ vi.mock('../../../assets/codemods/registry.mjs', async importOriginal => {
17
+ const actual = /** @type {Record<string, unknown>} */ (
18
+ await importOriginal()
19
+ );
20
+ return {
21
+ ...actual,
22
+ getTransformsBetween: async () => [
23
+ {
24
+ version: '0.2.0',
25
+ transforms: [
26
+ {
27
+ name: 'rename-foo',
28
+ meta: {title: 'Rename foo', fileExtensions: ['.ts']},
29
+ /** @param {{source: string}} file */
30
+ transform: file => file.source.replace(/foo/g, 'bar'),
31
+ },
32
+ {
33
+ name: 'parse-js',
34
+ meta: {title: 'Parse JavaScript', fileExtensions: ['.js']},
35
+ /** @param {{source: string}} file @param {{jscodeshift: (source: string) => unknown}} api */
36
+ transform(file, api) {
37
+ api.jscodeshift(file.source);
38
+ return undefined;
39
+ },
40
+ },
41
+ {
42
+ name: 'fail-on-boom',
43
+ meta: {title: 'Fail on boom', fileExtensions: ['.ts']},
44
+ /** @param {{source: string}} file */
45
+ transform(file) {
46
+ if (file.source.includes('boom')) throw new Error('codemod boom');
47
+ return undefined;
48
+ },
49
+ },
50
+ ],
51
+ },
52
+ ],
53
+ };
54
+ });
55
+
56
+ const {upgrade} = await import('../upgrade.mjs');
57
+ const {AstryxError} = await import('../../error.mjs');
58
+ const {toErrorEnvelope} = await import('../../../foundation/response/json.mjs');
59
+ const {isError} = await import('../../json/parse.mjs');
60
+
61
+ let dir;
62
+
63
+ /** @param {string} rel @param {string} body */
64
+ function write(rel, body) {
65
+ fs.mkdirSync(path.dirname(path.join(dir, rel)), {recursive: true});
66
+ fs.writeFileSync(path.join(dir, rel), body);
67
+ }
68
+
69
+ beforeEach(() => {
70
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-failure-receipt-'));
71
+ write(
72
+ 'package.json',
73
+ JSON.stringify({name: 'x', dependencies: {'@astryxdesign/core': '0.2.0'}}),
74
+ );
75
+ write(
76
+ 'node_modules/@astryxdesign/core/package.json',
77
+ JSON.stringify({name: '@astryxdesign/core', version: '0.2.0'}),
78
+ );
79
+ write('src/index.ts', 'const foo = 1;\n');
80
+ write('src/broken.ts', 'const boom = 1;\n');
81
+ });
82
+
83
+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));
84
+
85
+ /** @param {Promise<unknown>} promise */
86
+ async function rejection(promise) {
87
+ try {
88
+ await promise;
89
+ } catch (err) {
90
+ return /** @type {any} */ (err);
91
+ }
92
+ throw new Error('expected upgrade() to reject');
93
+ }
94
+
95
+ describe('a failed upgrade', () => {
96
+ it('still rejects with ERR_CODEMOD_FAILED, and the error carries the receipt', async () => {
97
+ const err = await rejection(
98
+ upgrade({from: '0.1.0', apply: true, path: 'src'}, {cwd: dir}),
99
+ );
100
+
101
+ expect(err).toBeInstanceOf(AstryxError);
102
+ expect(err.code).toBe('ERR_CODEMOD_FAILED');
103
+ expect(err.message).toBe('Upgrade completed with 1 codemod error.');
104
+ expect(err.receipt).toMatchObject({
105
+ complete: false,
106
+ errorCode: 'ERR_CODEMOD_FAILED',
107
+ filesChanged: 1,
108
+ modifiedFiles: ['src/index.ts'],
109
+ errors: [
110
+ {
111
+ file: 'src/broken.ts',
112
+ codemod: 'core:fail-on-boom',
113
+ error: 'codemod boom',
114
+ },
115
+ ],
116
+ });
117
+ expect(fs.readFileSync(path.join(dir, 'src/index.ts'), 'utf8')).toBe(
118
+ 'const bar = 1;\n',
119
+ );
120
+ });
121
+
122
+ it('lists a protected file a codemod could not parse in the receipt', async () => {
123
+ write('.gitattributes', 'src/vendor/** linguist-vendored\n');
124
+ write('src/vendor/bundle.js', 'export const x = {;\n');
125
+
126
+ const err = await rejection(
127
+ upgrade({from: '0.1.0', apply: true, path: 'src'}, {cwd: dir}),
128
+ );
129
+
130
+ expect(err.code).toBe('ERR_CODEMOD_FAILED');
131
+ expect(err.receipt.errors).toEqual([
132
+ expect.objectContaining({file: 'src/broken.ts'}),
133
+ ]);
134
+ expect(err.receipt.declinedCandidates).toEqual([
135
+ {
136
+ file: 'src/vendor/bundle.js',
137
+ location: '1:19',
138
+ reason: expect.stringMatching(
139
+ /^unparseable protected file \(vendored\): /,
140
+ ),
141
+ },
142
+ ]);
143
+ });
144
+
145
+ it('names a declined file from the folder the command ran in, with no root-relative path in its reason', async () => {
146
+ write('.gitattributes', 'src/vendor/** linguist-vendored\n');
147
+ write('src/vendor/bundle.js', 'export const x = {;\n');
148
+
149
+ const err = await rejection(
150
+ upgrade(
151
+ {from: '0.1.0', apply: true, path: '.'},
152
+ {cwd: path.join(dir, 'src')},
153
+ ),
154
+ );
155
+
156
+ expect(err.receipt.declinedCandidates).toEqual([
157
+ {
158
+ file: 'vendor/bundle.js',
159
+ location: '1:19',
160
+ reason: expect.stringMatching(
161
+ /^unparseable protected file \(vendored\): /,
162
+ ),
163
+ },
164
+ ]);
165
+ expect(err.receipt.declinedCandidates[0].reason).not.toContain(
166
+ '.gitattributes',
167
+ );
168
+ });
169
+
170
+ it('names receipt files from the folder the command ran in', async () => {
171
+ const err = await rejection(
172
+ upgrade(
173
+ {from: '0.1.0', apply: true, path: '.'},
174
+ {cwd: path.join(dir, 'src')},
175
+ ),
176
+ );
177
+
178
+ expect(err.code).toBe('ERR_CODEMOD_FAILED');
179
+ expect(err.receipt.modifiedFiles).toEqual(['index.ts']);
180
+ expect(err.receipt.errors).toEqual([
181
+ expect.objectContaining({file: 'broken.ts'}),
182
+ ]);
183
+ });
184
+
185
+ it('becomes an error envelope that keeps its code and adds the receipt', async () => {
186
+ const err = await rejection(
187
+ upgrade({from: '0.1.0', path: 'src'}, {cwd: dir}),
188
+ );
189
+
190
+ const envelope = toErrorEnvelope(err);
191
+ expect(isError(envelope)).toBe(true);
192
+ expect(envelope).toMatchObject({
193
+ apiVersion: 1,
194
+ code: 'ERR_CODEMOD_FAILED',
195
+ error: 'Upgrade completed with 1 codemod error.',
196
+ receipt: {modifiedFiles: ['src/index.ts'], complete: false},
197
+ });
198
+ expect(fs.readFileSync(path.join(dir, 'src/index.ts'), 'utf8')).toBe(
199
+ 'const foo = 1;\n',
200
+ );
201
+ });
202
+ });
203
+
204
+ describe('the error envelope', () => {
205
+ it('has no receipt for an error that carries none', () => {
206
+ expect(
207
+ toErrorEnvelope(
208
+ new AstryxError('nope', undefined, 'ERR_INVALID_ARGUMENT'),
209
+ ),
210
+ ).toEqual({apiVersion: 1, error: 'nope', code: 'ERR_INVALID_ARGUMENT'});
211
+ });
212
+ });
@@ -61,6 +61,7 @@ import {
61
61
  PathSafetyError,
62
62
  } from '../../../foundation/fs/path-safety.mjs';
63
63
  import {createFileProtectionResolver} from '../../../foundation/fs/file-protection.mjs';
64
+ import {withoutProtected} from '../../../assets/codemods/runner.mjs';
64
65
 
65
66
  /**
66
67
  * Collapse per-codemod protection hits into one stable row per file.
@@ -93,6 +94,55 @@ function summarizeProtectedFiles(rows) {
93
94
  .sort((a, b) => a.file.localeCompare(b.file));
94
95
  }
95
96
 
97
+ /**
98
+ * Collapse per-codemod declined candidates into one row per file, in the
99
+ * receipt's `{file, location?, reason}` shape. A file the receipt lists under
100
+ * `protectedFiles` is left out: a codemod still requires a change to it, and
101
+ * that already makes the run incomplete.
102
+ * @param {Array<{file: string, codemod: string, location?: string, reason: string}>} rows
103
+ * @param {Array<{file: string}>} [protectedRows]
104
+ * @returns {Array<{file: string, location?: string, reason: string}>}
105
+ */
106
+ function summarizeDeclinedCandidates(rows, protectedRows = []) {
107
+ /** @type {Map<string, {file: string, location?: string, reason: string}>} */
108
+ const byFile = new Map();
109
+ for (const {file, location, reason} of withoutProtected(
110
+ rows,
111
+ protectedRows,
112
+ )) {
113
+ if (byFile.has(file)) continue;
114
+ byFile.set(file, {file, ...(location ? {location} : {}), reason});
115
+ }
116
+ return [...byFile.values()].sort((a, b) => a.file.localeCompare(b.file));
117
+ }
118
+
119
+ /**
120
+ * Print the protected files the run skipped because a codemod could not parse
121
+ * them, from the final declined list (files it reports as protected are
122
+ * already left out), so the text output carries what the receipt lists.
123
+ * @param {Array<{file: string, location?: string, reason: string}>} declined
124
+ */
125
+ function logDeclined(declined) {
126
+ if (declined.length === 0) return;
127
+ const n = declined.length;
128
+ logger.warn(
129
+ `${n} protected file${n === 1 ? ' was' : 's were'} skipped because ${n === 1 ? 'it does' : 'they do'} not parse; review manually:`,
130
+ );
131
+ for (const {file, location, reason} of declined) {
132
+ logger.warn(` ${file}${location ? `:${location}` : ''} - ${reason}`);
133
+ }
134
+ }
135
+
136
+ /**
137
+ * @template {Array<{file: string, location?: string, reason: string}>} T
138
+ * @param {T} declined
139
+ * @returns {T}
140
+ */
141
+ function logged(declined) {
142
+ logDeclined(declined);
143
+ return declined;
144
+ }
145
+
96
146
  /** @param {string} cwd */
97
147
  function loadFileProtection(cwd) {
98
148
  try {
@@ -109,6 +159,83 @@ function loadFileProtection(cwd) {
109
159
  }
110
160
  }
111
161
 
162
+ /**
163
+ * The receipt of a run that stopped after codemods ran. Whatever the codemods
164
+ * already wrote stays on disk, so the error the run throws carries this
165
+ * receipt (`failWithReceipt`): a caller that reads only the error would
166
+ * report nothing changed while the files it lists remain modified
167
+ * (spec:AST-040 FR7).
168
+ *
169
+ * @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}>, declinedRows?: Array<{file: string, codemod: string, location?: string, reason: string}>, errorCode: string, cliBehindCore?: import('../upgrade.type.mjs').CliBehindCore | null, registryCompositions?: import('../upgrade.type.mjs').RegistryCompositionSummary}} facts
170
+ * @returns {import('../upgrade.type.mjs').UpgradeRunResponse['data']}
171
+ */
172
+ function stoppedReceipt({
173
+ from,
174
+ to,
175
+ codemods,
176
+ integrations,
177
+ sourcePathFound,
178
+ cwd,
179
+ changedFiles,
180
+ transformsApplied,
181
+ protectedRows,
182
+ errors,
183
+ declinedRows = [],
184
+ errorCode,
185
+ cliBehindCore,
186
+ registryCompositions,
187
+ }) {
188
+ const modifiedFiles = uniqueFiles(changedFiles).map(file =>
189
+ path.relative(cwd, file).split(path.sep).join('/'),
190
+ );
191
+ return /** @type {import('../upgrade.type.mjs').UpgradeRunResponse['data']} */ ({
192
+ from,
193
+ to,
194
+ codemods,
195
+ integrations,
196
+ agentDocsRefreshed: false,
197
+ agentDocs: {
198
+ status: 'current',
199
+ installedVersion: to,
200
+ fromVersions: [],
201
+ files: [],
202
+ refreshed: false,
203
+ action: 'none',
204
+ },
205
+ sourcePathFound,
206
+ filesChanged: modifiedFiles.length,
207
+ transformsApplied,
208
+ modifiedFiles,
209
+ protectedFiles: summarizeProtectedFiles(protectedRows),
210
+ declinedCandidates: logged(
211
+ summarizeDeclinedCandidates(declinedRows, protectedRows),
212
+ ),
213
+ complete: false,
214
+ errorCode,
215
+ errors,
216
+ ...(registryCompositions ? {registryCompositions} : {}),
217
+ ...(cliBehindCore ? {cliBehindCore} : {}),
218
+ });
219
+ }
220
+
221
+ /**
222
+ * The error a run throws once codemods have run: the same message and stable
223
+ * code as always, plus the run's receipt on `receipt`, so the JSON error
224
+ * envelope and a programmatic caller can still see what was written.
225
+ * @param {string} message
226
+ * @param {string} code
227
+ * @param {import('../upgrade.type.mjs').UpgradeRunResponse['data']} receipt
228
+ * @returns {AstryxError & {receipt: import('../upgrade.type.mjs').UpgradeRunResponse['data']}}
229
+ */
230
+ function failWithReceipt(message, code, receipt) {
231
+ const err =
232
+ /** @type {AstryxError & {receipt: import('../upgrade.type.mjs').UpgradeRunResponse['data']}} */ (
233
+ new AstryxError(message, undefined, code)
234
+ );
235
+ err.receipt = receipt;
236
+ return err;
237
+ }
238
+
112
239
  /**
113
240
  * Run the upgrade pipeline for a validated, non-list invocation. Returns the
114
241
  * terminal run receipt, or one of the status short-circuits; throws AstryxError
@@ -331,7 +458,12 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
331
458
  path.relative(cwd, file).split(path.sep).join('/'),
332
459
  ),
333
460
  protectedFiles,
334
- declinedCandidates: [],
461
+ declinedCandidates: logged(
462
+ summarizeDeclinedCandidates(
463
+ coreResult?.declinedCandidates ?? [],
464
+ allProtected,
465
+ ),
466
+ ),
335
467
  complete: false,
336
468
  errorCode: 'ERR_CODEMOD_PROTECTED',
337
469
  errors: coreResult?.errors ?? [],
@@ -368,6 +500,33 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
368
500
  // Genuine config error: abort.
369
501
  logger.error(configErr.message);
370
502
  logger.log('Aborted\n');
503
+ if ((coreResult?.writtenFiles.length ?? 0) > 0) {
504
+ // Core codemods already wrote: the error carries what they changed.
505
+ if (cliBehindCore) logCliBehindCore(cliBehindCore, targetVersion);
506
+ const stopped = stoppedReceipt({
507
+ from: currentVersion,
508
+ to: targetVersion,
509
+ codemods: totalTransforms,
510
+ integrations: [],
511
+ sourcePathFound,
512
+ cwd,
513
+ changedFiles: coreResult?.changedFiles ?? [],
514
+ transformsApplied: coreResult?.totalTransformsApplied ?? 0,
515
+ protectedRows: [],
516
+ errors: [
517
+ ...(coreResult?.errors ?? []),
518
+ {file: '.', codemod: 'config', error: configErr.message},
519
+ ],
520
+ declinedRows: coreResult?.declinedCandidates ?? [],
521
+ errorCode: ERROR_CODES.ERR_INVALID_ARGUMENT,
522
+ cliBehindCore,
523
+ });
524
+ throw failWithReceipt(
525
+ configErr.message,
526
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
527
+ stopped,
528
+ );
529
+ }
371
530
  throw new AstryxError(
372
531
  configErr.message,
373
532
  undefined,
@@ -561,7 +720,34 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
561
720
  logger.error(msg);
562
721
  if (initialProtected.length === 0) {
563
722
  logger.log('Upgrade failed\n');
564
- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
723
+ throw failWithReceipt(
724
+ msg,
725
+ ERROR_CODES.ERR_CODEMOD_FAILED,
726
+ stoppedReceipt({
727
+ from: currentVersion,
728
+ to: targetVersion,
729
+ codemods: totalTransforms,
730
+ integrations: receipt.integrations,
731
+ sourcePathFound,
732
+ cwd,
733
+ changedFiles: mergedChangedFiles,
734
+ transformsApplied: mergedTransformsApplied,
735
+ protectedRows: [],
736
+ errors: [
737
+ ...mergedErrors,
738
+ {file: '.', codemod: 'post-codemod-hook', error: msg},
739
+ ],
740
+ declinedRows: [
741
+ ...(coreResult?.declinedCandidates ?? []),
742
+ ...(integrationResult?.declinedCandidates ?? []),
743
+ ],
744
+ errorCode: ERROR_CODES.ERR_CODEMOD_FAILED,
745
+ cliBehindCore,
746
+ ...(registryResult
747
+ ? {registryCompositions: registryResult.summary}
748
+ : {}),
749
+ }),
750
+ );
565
751
  }
566
752
  hookFailure = msg;
567
753
  finalErrors = [
@@ -586,8 +772,44 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
586
772
  // selected codemods in preview mode against fresh bytes and fresh declarations
587
773
  // to distinguish resolved outputs from changes that remain blocked.
588
774
  let remainingProtected = initialProtected;
775
+ let remainingDeclined = [
776
+ ...(coreResult?.declinedCandidates ?? []),
777
+ ...(integrationResult?.declinedCandidates ?? []),
778
+ ];
589
779
  if (apply && shouldRunHooks && !hookFailure) {
590
- const refreshedProtection = loadFileProtection(cwd);
780
+ let refreshedProtection;
781
+ try {
782
+ refreshedProtection = loadFileProtection(cwd);
783
+ } catch (err) {
784
+ if (!(err instanceof AstryxError)) throw err;
785
+ // The hooks ran after the codemods wrote; the error carries their receipt.
786
+ if (cliBehindCore) logCliBehindCore(cliBehindCore, targetVersion);
787
+ const stopped = stoppedReceipt({
788
+ from: currentVersion,
789
+ to: targetVersion,
790
+ codemods: totalTransforms,
791
+ integrations: receipt.integrations,
792
+ sourcePathFound,
793
+ cwd,
794
+ changedFiles: [...mergedChangedFiles, ...hookModifiedFiles],
795
+ transformsApplied: mergedTransformsApplied,
796
+ protectedRows: initialProtected,
797
+ errors: [
798
+ ...mergedErrors,
799
+ {file: '.', codemod: 'file-protection', error: err.message},
800
+ ],
801
+ declinedRows: [
802
+ ...(coreResult?.declinedCandidates ?? []),
803
+ ...(integrationResult?.declinedCandidates ?? []),
804
+ ],
805
+ errorCode: err.code,
806
+ cliBehindCore,
807
+ ...(registryResult
808
+ ? {registryCompositions: registryResult.summary}
809
+ : {}),
810
+ });
811
+ throw failWithReceipt(err.message, err.code, stopped);
812
+ }
591
813
  const coreCheck = await runCoreCodemods(versionManifests, {
592
814
  apply: false,
593
815
  path: path_,
@@ -638,6 +860,12 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
638
860
  recheckedProtected.push(...(initialByFile.get(file) ?? []));
639
861
  }
640
862
  remainingProtected = recheckedProtected;
863
+ // Regenerated bytes decide what a codemod could not parse, as they decide
864
+ // what is still protected.
865
+ remainingDeclined = [
866
+ ...(checkedCore?.declinedCandidates ?? []),
867
+ ...(integrationCheck?.declinedCandidates ?? []),
868
+ ];
641
869
  finalErrors = [
642
870
  ...mergedErrors,
643
871
  ...(checkedCore?.errors ?? []),
@@ -653,10 +881,15 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
653
881
  ...hookModifiedFiles,
654
882
  ]).map(file => path.relative(cwd, file).split(path.sep).join('/'));
655
883
  receipt.protectedFiles = protectedFiles;
656
- receipt.declinedCandidates = [];
657
- receipt.complete = protectedFiles.length === 0;
658
- if (!receipt.complete) {
884
+ receipt.declinedCandidates = logged(
885
+ summarizeDeclinedCandidates(remainingDeclined, remainingProtected),
886
+ );
887
+ receipt.complete = protectedFiles.length === 0 && finalErrors.length === 0;
888
+ if (protectedFiles.length > 0) {
659
889
  receipt.errorCode = 'ERR_CODEMOD_PROTECTED';
890
+ } else if (finalErrors.length > 0) {
891
+ // Only on the receipt the thrown error carries (below).
892
+ receipt.errorCode = 'ERR_CODEMOD_FAILED';
660
893
  }
661
894
  receipt.errors = finalErrors;
662
895
  if (registryResult) receipt.registryCompositions = registryResult.summary;
@@ -674,14 +907,22 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
674
907
  }
675
908
  }
676
909
 
677
- if (receipt.errors?.length > 0 && protectedFiles.length === 0) {
678
- const msg = `Upgrade completed with ${receipt.errors.length} codemod error${receipt.errors.length === 1 ? '' : 's'}.`;
910
+ if (finalErrors.length > 0 && protectedFiles.length === 0) {
911
+ const msg = `Upgrade completed with ${finalErrors.length} codemod error${finalErrors.length === 1 ? '' : 's'}.`;
679
912
  logger.log('Upgrade failed\n');
680
- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
913
+ // The error carries the receipt: every file the codemods wrote before the
914
+ // failure stays changed, and the caller keeps or reverts them knowingly.
915
+ throw failWithReceipt(
916
+ msg,
917
+ ERROR_CODES.ERR_CODEMOD_FAILED,
918
+ /** @type {import('../upgrade.type.mjs').UpgradeRunResponse['data']} */ (
919
+ /** @type {unknown} */ (receipt)
920
+ ),
921
+ );
681
922
  }
682
923
 
683
924
  // Only refresh managed docs after all required codemod changes are complete.
684
- if (protectedFiles.length === 0) {
925
+ if (receipt.complete) {
685
926
  const agentDocsPlan = await prepareAgentDocsRefresh({
686
927
  cwd,
687
928
  origin,
@@ -128,13 +128,13 @@ export const doc = {
128
128
  {
129
129
  type: 'upgrade.run',
130
130
  description:
131
- '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.',
131
+ '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.',
132
132
  },
133
133
  ],
134
134
  throws: [
135
135
  {
136
136
  code: 'ERR_INVALID_ARGUMENT',
137
- 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',
137
+ 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`)',
138
138
  },
139
139
  {code: 'ERR_INVALID_VERSION', when: '`from` is not a valid semver string'},
140
140
  {
@@ -155,11 +155,11 @@ export const doc = {
155
155
  },
156
156
  {
157
157
  code: 'ERR_CODEMOD_FAILED',
158
- 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)',
158
+ 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",
159
159
  },
160
160
  {
161
161
  code: 'ERR_CODEMOD_PROTECTION_SOURCE',
162
- when: 'a working-tree protection declaration cannot be read or parsed before writes begin',
162
+ 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`)',
163
163
  },
164
164
  ],
165
165
  examples: [
@@ -120,8 +120,23 @@ export async function upgrade(options = {}, {cwd = process.cwd()} = {}) {
120
120
  // A run from a subfolder upgrades the project the folder belongs to, and
121
121
  // names files relative to the folder it ran in.
122
122
  const scoped = scopeToProject(options, cwd);
123
- return relativeToOrigin(
124
- await run(scoped.options, {cwd: scoped.cwd, origin: scoped.origin}),
125
- scoped,
126
- );
123
+ let result;
124
+ try {
125
+ result = await run(scoped.options, {
126
+ cwd: scoped.cwd,
127
+ origin: scoped.origin,
128
+ });
129
+ } catch (err) {
130
+ // A failure after codemods wrote carries their receipt; name its files
131
+ // from the folder the command ran in, as a returned receipt does.
132
+ const receipt = /** @type {any} */ (err)?.receipt;
133
+ if (err instanceof AstryxError && receipt) {
134
+ /** @type {any} */ (err).receipt = relativeToOrigin(
135
+ {type: 'upgrade.run', data: receipt},
136
+ scoped,
137
+ ).data;
138
+ }
139
+ throw err;
140
+ }
141
+ return relativeToOrigin(result, scoped);
127
142
  }
@@ -193,7 +193,7 @@ export type UpgradeRunResponse = {
193
193
  sourcePathFound: boolean;
194
194
  registryCompositions?: RegistryCompositionSummary | undefined;
195
195
  complete?: boolean | undefined;
196
- errorCode?: "ERR_CODEMOD_PROTECTED" | undefined;
196
+ errorCode?: string | undefined;
197
197
  filesChanged?: number | undefined;
198
198
  modifiedFiles?: string[] | undefined;
199
199
  protectedFiles?: ProtectedCodemodFile[] | undefined;
@@ -211,6 +211,17 @@ export type UpgradeRunResponse = {
211
211
  cliBehindCore?: CliBehindCore | undefined;
212
212
  };
213
213
  };
214
+ /**
215
+ * What a failed upgrade had already done. When a run fails after its codemods
216
+ * ran (a codemod or post-codemod hook failed, or an error stopped it after
217
+ * codemods wrote files), the failure keeps its usual shape: the --json error
218
+ * envelope `{apiVersion, error, code}` and a rejected `upgrade()` with that
219
+ * `code`. The envelope adds `receipt`, and the thrown AstryxError a `receipt`
220
+ * property: the same `upgrade.run` data a completed run returns, with
221
+ * `complete: false` and `errorCode` equal to the error's `code`. Files in
222
+ * `modifiedFiles` stay changed.
223
+ */
224
+ export type UpgradeFailureReceipt = UpgradeRunResponse["data"];
214
225
  /**
215
226
  * astryx --json upgrade — short-circuit status results.
216
227
  *