@astryxdesign/cli 0.7.5-canary.7cb897b → 0.7.5-canary.85e48a0

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 (44) hide show
  1. package/README.md +1 -1
  2. package/api/integration/pack-check.lifecycle-output.test.mjs +24 -1
  3. package/api/integration/pack-check.mjs +10 -4
  4. package/api/integration/pack-check.test.mjs +5 -1
  5. package/api/upgrade/_adapter.d.mts +2 -0
  6. package/api/upgrade/run/failure-receipt.test.mjs +212 -0
  7. package/api/upgrade/run/run.mjs +251 -10
  8. package/api/upgrade/upgrade.doc.mjs +4 -4
  9. package/api/upgrade/upgrade.mjs +19 -4
  10. package/api/upgrade/upgrade.type.d.mts +12 -1
  11. package/api/upgrade/upgrade.type.mjs +17 -4
  12. package/assets/codemods/__tests__/runner.symlinks.test.mjs +205 -0
  13. package/assets/codemods/__tests__/runner.unparseable.test.mjs +457 -0
  14. package/assets/codemods/integration-runner.mjs +8 -2
  15. package/assets/codemods/integration-runner.protection.test.mjs +53 -0
  16. package/assets/codemods/parse.mjs +94 -0
  17. package/assets/codemods/run-codemod.mjs +109 -5
  18. package/assets/codemods/runner.mjs +108 -10
  19. package/assets/codemods/transform-prop.mjs +99 -49
  20. package/assets/codemods/transform-prop.test.mjs +36 -1
  21. package/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs +216 -2
  22. package/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs +88 -6
  23. package/assets/codemods/transforms/v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs +4 -3
  24. package/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs +207 -6
  25. package/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +123 -70
  26. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface-v0.6-data.mjs +6 -1
  27. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +244 -42
  28. package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +19 -77
  29. package/assets/docs/tree/styling-advanced.doc.mjs +1 -1
  30. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.doc.mjs +1 -1
  31. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.tsx +10 -2
  32. package/assets/templates/pages/library/page.tsx +1 -2
  33. package/authoring/codemod/type.ts +10 -0
  34. package/clients/cli/commands/upgrade.doc.mjs +27 -0
  35. package/clients/cli/commands/upgrade.file-protection.test.mjs +175 -0
  36. package/clients/cli/commands/upgrade.flag-help.test.mjs +37 -0
  37. package/clients/cli/commands/upgrade.integration-policy.test.mjs +103 -0
  38. package/clients/cli/commands/upgrade.mjs +9 -2
  39. package/foundation/response/base.d.ts +7 -0
  40. package/foundation/response/error-codes.doc.mjs +3 -2
  41. package/foundation/response/error-codes.mjs +1 -1
  42. package/foundation/response/json.d.mts +10 -3
  43. package/foundation/response/json.mjs +16 -4
  44. 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. |
@@ -1,6 +1,6 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
- import {afterEach, beforeEach, describe, expect, it} from 'vitest';
3
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
4
4
  import {spawnSync} from 'node:child_process';
5
5
  import * as fs from 'node:fs';
6
6
  import * as path from 'node:path';
@@ -123,4 +123,27 @@ describe('integrationPackCheck with lifecycle script output', () => {
123
123
  expect(failure?.message).toContain('npm pack failed (exit 3)');
124
124
  expect(failure?.message).toContain('prepack exploded');
125
125
  });
126
+
127
+ it.skipIf(process.platform === 'win32')(
128
+ 'packs with npm itself when an earlier npm on the PATH refuses every command',
129
+ async () => {
130
+ writeThemePackage({});
131
+ const refusing = path.join(tmpDir, '.refusing-bin');
132
+ fs.mkdirSync(refusing);
133
+ fs.writeFileSync(
134
+ path.join(refusing, 'npm'),
135
+ "#!/bin/sh\necho 'npm commands are not allowed on this machine'\nexit 1\n",
136
+ {mode: 0o755},
137
+ );
138
+ vi.stubEnv('PATH', `${refusing}${path.delimiter}${process.env.PATH}`);
139
+ try {
140
+ const result = await integrationPackCheck({cwd: tmpDir});
141
+
142
+ expect(result.data.issues).toEqual([]);
143
+ expect(result.data.packable).toBe(true);
144
+ } finally {
145
+ vi.unstubAllEnvs();
146
+ }
147
+ },
148
+ );
126
149
  });
@@ -25,6 +25,7 @@ import * as os from 'node:os';
25
25
  import {fileURLToPath} from 'node:url';
26
26
  import {spawnSync} from 'node:child_process';
27
27
  import {assertWithin} from '../../foundation/fs/path-safety.mjs';
28
+ import {npmCommand} from '../../foundation/release/cache.mjs';
28
29
  import {commandTokensIn} from '../../foundation/doc-compiler/doc-syntax.mjs';
29
30
  import {resolvePackageDir} from '../../foundation/integrations/integrations.mjs';
30
31
  import {
@@ -265,17 +266,22 @@ function npmPackErrorDetail(output) {
265
266
  /**
266
267
  * Run `npm pack --json` with output directed to `destDir` so no preexisting
267
268
  * tgz is overwritten. This intentionally runs the package lifecycle, matching
268
- * the artifact `npm publish` would produce. Uses spawnSync with an args array —
269
- * no shell — so paths with metacharacters cannot inject.
269
+ * the artifact `npm publish` would produce. npm starts the way the CLI starts
270
+ * it everywhere else (`npmCommand`): npm's own entry file run with this Node
271
+ * when one is found, so an `npm` earlier on the PATH that is not npm itself
272
+ * cannot answer for it. Uses spawnSync with an args array — no shell — so
273
+ * paths with metacharacters cannot inject.
270
274
  *
271
275
  * @param {string} packageDir
272
276
  * @param {string} destDir
273
277
  * @returns {{filename: string, fileCount: number, size: number, unpackedSize: number, packedPaths: Set<string>}}
274
278
  */
275
279
  function runNpmPack(packageDir, destDir) {
280
+ const npm = npmCommand();
276
281
  const result = spawnSync(
277
- 'npm',
282
+ npm.command,
278
283
  [
284
+ ...npm.prefix,
279
285
  'pack',
280
286
  '--json',
281
287
  '--silent',
@@ -284,7 +290,7 @@ function runNpmPack(packageDir, destDir) {
284
290
  '--foreground-scripts=false',
285
291
  `--pack-destination=${destDir}`,
286
292
  ],
287
- {cwd: packageDir, encoding: 'utf-8', timeout: 60_000},
293
+ {cwd: packageDir, encoding: 'utf-8', shell: false, timeout: 60_000},
288
294
  );
289
295
  if (result.error) {
290
296
  throw new Error(`Could not start npm pack: ${result.error.message}`);
@@ -2125,10 +2125,13 @@ describe('integrationPackCheck', () => {
2125
2125
  ).toThrow(/without a files array/);
2126
2126
  });
2127
2127
 
2128
- it('reports npm missing from PATH as pack_failed', async () => {
2128
+ it('reports pack_failed when no npm can be found', async () => {
2129
2129
  writePackage({files: ['astryx.integration.mjs', 'themes']});
2130
2130
  const originalPath = process.env.PATH;
2131
+ const originalExecPath = process.execPath;
2131
2132
  process.env.PATH = '';
2133
+ // A Node with no npm beside it, and no npm on the PATH.
2134
+ process.execPath = path.join(tmpDir, 'no-npm', 'bin', 'node');
2132
2135
  try {
2133
2136
  const result = await integrationPackCheck({cwd: tmpDir});
2134
2137
  expect(result.data.packable).toBe(false);
@@ -2140,6 +2143,7 @@ describe('integrationPackCheck', () => {
2140
2143
  );
2141
2144
  } finally {
2142
2145
  process.env.PATH = originalPath;
2146
+ process.execPath = originalExecPath;
2143
2147
  }
2144
2148
  });
2145
2149
 
@@ -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,