@astryxdesign/cli 0.7.5-canary.577e8ca → 0.7.5-canary.6322d94

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.
@@ -39,6 +39,7 @@ import {
39
39
  warnIntegrationIssues,
40
40
  selectIntegrationCodemodsFor,
41
41
  runIntegrationCodemodsStep,
42
+ withCodemodOutcomes,
42
43
  } from '../_adapter.mjs';
43
44
  import {
44
45
  logRegistryCompositionSummary,
@@ -94,42 +95,222 @@ function summarizeProtectedFiles(rows) {
94
95
  .sort((a, b) => a.file.localeCompare(b.file));
95
96
  }
96
97
 
98
+ /** Every declined finding for a manual migration starts with this. */
99
+ const MANUAL_MIGRATION_REASON = 'manual migration needed';
100
+
101
+ /**
102
+ * Where one declined finding ends and the next begins inside a folded
103
+ * `reason`: `; ` before a finding's own prefix.
104
+ */
105
+ const NEXT_FINDING =
106
+ /; (?=(?:unparseable protected file|manual migration needed) \()/;
107
+
108
+ /** The suffix of a folded finding that has no location of its own. */
109
+ const LOCATION_UNKNOWN = '(location unknown)';
110
+
97
111
  /**
98
112
  * Collapse per-codemod declined candidates into one row per file, in the
99
113
  * receipt's `{file, location?, reason}` shape. A file the receipt lists under
100
114
  * `protectedFiles` is left out: a codemod still requires a change to it, and
101
115
  * that already makes the run incomplete.
116
+ *
117
+ * Every distinct finding for a file is kept, whatever its kind: a single
118
+ * finding is the row as it arrived; several are folded into the one row,
119
+ * each keeping its own prefix (`unparseable protected file (<category>): ...`
120
+ * or `manual migration needed (<codemod>): ...`), joined by `; ` in arrival
121
+ * order. `location` is the first finding's own location (absent when it has
122
+ * none). A later finding whose own location differs from the row's says so at
123
+ * its end: ` (at <location>)` when known, ` (location unknown)` when not; a
124
+ * later finding without a suffix is at the row's location. So no finding is
125
+ * ever read at another finding's location.
126
+ *
127
+ * Rows are grouped by their `/`-separated path, which is also the spelling
128
+ * the row carries: a runner's row keeps the platform separator (backslashes on
129
+ * Windows), while a manual row already uses `/`.
102
130
  * @param {Array<{file: string, codemod: string, location?: string, reason: string}>} rows
103
131
  * @param {Array<{file: string}>} [protectedRows]
132
+ * @param {string} [sep] The platform path separator (a parameter for tests).
104
133
  * @returns {Array<{file: string, location?: string, reason: string}>}
105
134
  */
106
- function summarizeDeclinedCandidates(rows, protectedRows = []) {
107
- /** @type {Map<string, {file: string, location?: string, reason: string}>} */
135
+ export function summarizeDeclinedCandidates(
136
+ rows,
137
+ protectedRows = [],
138
+ sep = path.sep,
139
+ ) {
140
+ /** @type {Map<string, Array<{location?: string, reason: string}>>} */
108
141
  const byFile = new Map();
109
- for (const {file, location, reason} of withoutProtected(
142
+ for (const {file: raw, location, reason} of withoutProtected(
110
143
  rows,
111
144
  protectedRows,
112
145
  )) {
113
- if (byFile.has(file)) continue;
114
- byFile.set(file, {file, ...(location ? {location} : {}), reason});
146
+ const file = raw.split(sep).join('/');
147
+ const findings = byFile.get(file) ?? [];
148
+ if (!findings.some(f => f.reason === reason && f.location === location)) {
149
+ findings.push({...(location ? {location} : {}), reason});
150
+ }
151
+ byFile.set(file, findings);
115
152
  }
116
- return [...byFile.values()].sort((a, b) => a.file.localeCompare(b.file));
153
+ return [...byFile.entries()]
154
+ .map(([file, findings]) => {
155
+ const location = findings[0].location;
156
+ return {
157
+ file,
158
+ ...(location ? {location} : {}),
159
+ reason: findings
160
+ .map((f, index) =>
161
+ index === 0 || f.location === location
162
+ ? f.reason
163
+ : f.location
164
+ ? `${f.reason} (at ${f.location})`
165
+ : `${f.reason} ${LOCATION_UNKNOWN}`,
166
+ )
167
+ .join('; '),
168
+ };
169
+ })
170
+ .sort((a, b) => a.file.localeCompare(b.file));
171
+ }
172
+
173
+ /**
174
+ * The findings a folded declined row carries, each with its own location.
175
+ * @param {{location?: string, reason: string}} row
176
+ * @returns {Array<{location?: string, text: string}>}
177
+ */
178
+ function declinedFindings(row) {
179
+ return row.reason.split(NEXT_FINDING).map((text, index) => {
180
+ if (index === 0) {
181
+ return {...(row.location ? {location: row.location} : {}), text};
182
+ }
183
+ if (text.endsWith(` ${LOCATION_UNKNOWN}`)) {
184
+ return {text: text.slice(0, -LOCATION_UNKNOWN.length - 1)};
185
+ }
186
+ const at = / \(at ([^)]+)\)$/.exec(text);
187
+ return at
188
+ ? {location: at[1], text: text.slice(0, at.index)}
189
+ : {...(row.location ? {location: row.location} : {}), text};
190
+ });
191
+ }
192
+
193
+ /**
194
+ * Declined candidates for code a codemod identified but cannot migrate safely
195
+ * (`ManualMigrationRequired`): one row per finding, in the per-codemod row
196
+ * shape the runners use, for `summarizeDeclinedCandidates` to fold with the
197
+ * file's other declined findings. A person makes the change; like every
198
+ * declined candidate, it never fails the run or makes it incomplete
199
+ * (spec:AST-040 FR7).
200
+ * @param {import('../_adapter.mjs').CodemodOutcomeRecord[]} outcomes
201
+ * @returns {Array<{file: string, codemod: string, location?: string, reason: string}>}
202
+ */
203
+ function manualDeclinedRows(outcomes) {
204
+ /** @type {Array<{file: string, codemod: string, location?: string, reason: string}>} */
205
+ const rows = [];
206
+ for (const outcome of outcomes) {
207
+ if (outcome.kind !== 'manual') continue;
208
+ rows.push({
209
+ file: outcome.file,
210
+ codemod: outcome.codemod,
211
+ ...(typeof outcome.line === 'number'
212
+ ? {location: String(outcome.line)}
213
+ : {}),
214
+ reason: `${MANUAL_MIGRATION_REASON} (${outcome.codemod}): ${outcome.message}`,
215
+ });
216
+ }
217
+ return rows;
218
+ }
219
+
220
+ /**
221
+ * How many manual migrations the declined rows carry: every finding, not every
222
+ * file (a folded row lists several).
223
+ * @param {Array<{location?: string, reason: string}>} declined
224
+ */
225
+ function countManualMigrations(declined) {
226
+ return declined
227
+ .flatMap(declinedFindings)
228
+ .filter(f => f.text.startsWith(MANUAL_MIGRATION_REASON)).length;
117
229
  }
118
230
 
119
231
  /**
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.
232
+ * Print the final declined list (files it reports as protected are already
233
+ * left out), so the text output carries what the receipt lists: protected
234
+ * files the run skipped because a codemod could not parse them, and code a
235
+ * codemod could not migrate. Each finding of a folded row is printed under
236
+ * its own kind.
123
237
  * @param {Array<{file: string, location?: string, reason: string}>} declined
124
238
  */
125
239
  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:`,
240
+ /** @type {Array<{file: string, location?: string, text: string}>} */
241
+ const manual = [];
242
+ /** @type {Array<{file: string, location?: string, text: string}>} */
243
+ const unparseable = [];
244
+ for (const row of declined) {
245
+ for (const finding of declinedFindings(row)) {
246
+ (finding.text.startsWith(MANUAL_MIGRATION_REASON)
247
+ ? manual
248
+ : unparseable
249
+ ).push({file: row.file, ...finding});
250
+ }
251
+ }
252
+ /** @param {Array<{file: string, location?: string, text: string}>} rows */
253
+ const lines = rows => {
254
+ for (const {file, location, text} of rows) {
255
+ logger.warn(` ${file}${location ? `:${location}` : ''} - ${text}`);
256
+ }
257
+ };
258
+ /** @param {Array<{file: string}>} rows */
259
+ const files = rows => new Set(rows.map(row => row.file)).size;
260
+ if (unparseable.length > 0) {
261
+ const n = files(unparseable);
262
+ logger.warn(
263
+ `${n} protected file${n === 1 ? ' was' : 's were'} skipped because ${n === 1 ? 'it does' : 'they do'} not parse; review manually:`,
264
+ );
265
+ lines(unparseable);
266
+ }
267
+ if (manual.length > 0) {
268
+ const n = files(manual);
269
+ logger.warn(
270
+ `${n} file${n === 1 ? ' needs' : 's need'} a manual migration that upgrade cannot make; review manually:`,
271
+ );
272
+ lines(manual);
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Print protected files that still require a codemod change, each with the
278
+ * declarations that protect it and the commands that rebuild it.
279
+ * @param {string} header
280
+ * @param {import('../upgrade.type.mjs').ProtectedCodemodFile[]} protectedFiles
281
+ */
282
+ function logProtectedFiles(header, protectedFiles) {
283
+ if (protectedFiles.length === 0) return;
284
+ logger.error(header);
285
+ for (const item of protectedFiles) {
286
+ logger.error(` ${item.file} — ${item.declarations.join('; ')}`);
287
+ for (const command of item.commands) {
288
+ logger.log(` Regenerate with: ${command}`);
289
+ }
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Print the generated files to rebuild, each with why and the commands that
295
+ * rebuild it, so the text output carries what `regenerate` lists. Files
296
+ * already printed with their commands (protected files) are skipped.
297
+ * @param {import('../upgrade.type.mjs').RegenerateFile[]} regenerate
298
+ * @param {Array<{file: string}>} [printed]
299
+ */
300
+ function logRegenerate(regenerate, printed = []) {
301
+ const skip = new Set(printed.map(item => item.file));
302
+ const rows = regenerate.filter(item => !skip.has(item.file));
303
+ if (rows.length === 0) return;
304
+ logger.error(
305
+ `${rows.length} generated file${rows.length === 1 ? '' : 's'} must be regenerated:`,
130
306
  );
131
- for (const {file, location, reason} of declined) {
132
- logger.warn(` ${file}${location ? `:${location}` : ''} - ${reason}`);
307
+ for (const item of rows) {
308
+ logger.error(
309
+ ` ${item.file}${item.messages.length > 0 ? ` — ${item.messages.join(' ')}` : ''}`,
310
+ );
311
+ for (const command of item.commands) {
312
+ logger.log(` Regenerate with: ${command}`);
313
+ }
133
314
  }
134
315
  }
135
316
 
@@ -159,6 +340,118 @@ function loadFileProtection(cwd) {
159
340
  }
160
341
  }
161
342
 
343
+ /**
344
+ * Generated files that must be rebuilt before the upgrade is complete, one row
345
+ * per file: protected generated files a codemod still needs to change, and
346
+ * generated outputs a codemod reported out of date. `commands` are the exact
347
+ * rebuild commands known for the file (its header's `Command:` line, or the
348
+ * command the codemod names).
349
+ * @param {Array<{file: string, codemods: string[], reasons: string[], commands: string[]}>} protectedFiles
350
+ * @param {import('../_adapter.mjs').CodemodOutcomeRecord[]} outcomes
351
+ * @returns {import('../upgrade.type.mjs').RegenerateFile[]}
352
+ */
353
+ function summarizeRegenerate(protectedFiles, outcomes) {
354
+ /** @type {Map<string, {codemods: Set<string>, commands: Set<string>, messages: Set<string>}>} */
355
+ const byFile = new Map();
356
+ /** @param {string} file */
357
+ const row = file => {
358
+ const current = byFile.get(file) ?? {
359
+ codemods: new Set(),
360
+ commands: new Set(),
361
+ messages: new Set(),
362
+ };
363
+ byFile.set(file, current);
364
+ return current;
365
+ };
366
+ for (const item of protectedFiles) {
367
+ if (!item.reasons.includes('generated')) continue;
368
+ const current = row(item.file);
369
+ for (const codemod of item.codemods) current.codemods.add(codemod);
370
+ for (const command of item.commands) current.commands.add(command);
371
+ }
372
+ for (const outcome of outcomes) {
373
+ if (outcome.kind !== 'regenerate') continue;
374
+ const current = row(outcome.file);
375
+ current.codemods.add(outcome.codemod);
376
+ for (const command of outcome.commands) current.commands.add(command);
377
+ current.messages.add(outcome.message);
378
+ }
379
+ return [...byFile.entries()]
380
+ .map(([file, item]) => ({
381
+ file,
382
+ codemods: [...item.codemods].sort(),
383
+ commands: [...item.commands].sort(),
384
+ messages: [...item.messages].sort(),
385
+ }))
386
+ .sort((a, b) => a.file.localeCompare(b.file));
387
+ }
388
+
389
+ /**
390
+ * Protection rows for generated outputs a codemod reported out of date, from
391
+ * the run's protection resolver, in the shape the runners report blocked
392
+ * protected candidates. A reported file the project protects (an `@generated`
393
+ * header, `linguist-generated`, ...) is a protected file that still requires a
394
+ * change, so it is listed in `protectedFiles` with the declaration that
395
+ * protects it (spec:AST-040 FR6), and the command the codemod names is one of
396
+ * its `commands`. A reported file nothing protects gets no row here: it is a
397
+ * codemod error (`regenerationErrors`) and stays in `regenerate`.
398
+ * @param {import('../_adapter.mjs').CodemodOutcomeRecord[]} outcomes
399
+ * @param {{classify: (file: string) => import('../../../foundation/fs/file-protection.mjs').FileProtection[]}} protection
400
+ * @param {string} cwd
401
+ * @returns {Array<{file: string, codemod: string, reason: string, declaration: string, generated: boolean, command?: string}>}
402
+ */
403
+ function regenerationProtectionRows(outcomes, protection, cwd) {
404
+ /** @type {Array<{file: string, codemod: string, reason: string, declaration: string, generated: boolean, command?: string}>} */
405
+ const rows = [];
406
+ for (const outcome of outcomes) {
407
+ if (outcome.kind !== 'regenerate') continue;
408
+ for (const item of protection.classify(path.resolve(cwd, outcome.file))) {
409
+ const base = {
410
+ file: item.file,
411
+ codemod: outcome.codemod,
412
+ reason: item.reason,
413
+ declaration: item.declaration,
414
+ generated: item.reason === 'generated',
415
+ };
416
+ const commands = [
417
+ ...(item.command ? [item.command] : []),
418
+ ...outcome.commands,
419
+ ];
420
+ if (commands.length === 0) rows.push(base);
421
+ for (const command of commands) rows.push({...base, command});
422
+ }
423
+ }
424
+ return rows;
425
+ }
426
+
427
+ /**
428
+ * Error rows for generated outputs a codemod reported out of date that nothing
429
+ * protects. No protected consumer file blocks such a change, so it is not an
430
+ * ERR_CODEMOD_PROTECTED outcome: the codemod required a change it could not
431
+ * make, which is a codemod failure (ERR_CODEMOD_FAILED), as it was before the
432
+ * outcome was typed. The file stays in `regenerate` with its command.
433
+ * @param {import('../_adapter.mjs').CodemodOutcomeRecord[]} outcomes
434
+ * @param {{classify: (file: string) => import('../../../foundation/fs/file-protection.mjs').FileProtection[]}} protection
435
+ * @param {string} cwd
436
+ * @returns {Array<{file: string, codemod: string, error: string}>}
437
+ */
438
+ function regenerationErrors(outcomes, protection, cwd) {
439
+ /** @type {Array<{file: string, codemod: string, error: string}>} */
440
+ const rows = [];
441
+ for (const outcome of outcomes) {
442
+ if (outcome.kind !== 'regenerate') continue;
443
+ if (protection.classify(path.resolve(cwd, outcome.file)).length > 0) {
444
+ continue;
445
+ }
446
+ rows.push({
447
+ file: outcome.file,
448
+ codemod: outcome.codemod,
449
+ error: outcome.message,
450
+ });
451
+ }
452
+ return rows;
453
+ }
454
+
162
455
  /**
163
456
  * The receipt of a run that stopped after codemods ran. Whatever the codemods
164
457
  * already wrote stays on disk, so the error the run throws carries this
@@ -166,7 +459,7 @@ function loadFileProtection(cwd) {
166
459
  * report nothing changed while the files it lists remain modified
167
460
  * (spec:AST-040 FR7).
168
461
  *
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
462
+ * @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}>, outcomes?: import('../_adapter.mjs').CodemodOutcomeRecord[], 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
463
  * @returns {import('../upgrade.type.mjs').UpgradeRunResponse['data']}
171
464
  */
172
465
  function stoppedReceipt({
@@ -179,15 +472,20 @@ function stoppedReceipt({
179
472
  changedFiles,
180
473
  transformsApplied,
181
474
  protectedRows,
475
+ outcomes = [],
182
476
  errors,
183
477
  declinedRows = [],
184
478
  errorCode,
185
479
  cliBehindCore,
186
480
  registryCompositions,
187
481
  }) {
482
+ const protectedFiles = summarizeProtectedFiles(protectedRows);
188
483
  const modifiedFiles = uniqueFiles(changedFiles).map(file =>
189
484
  path.relative(cwd, file).split(path.sep).join('/'),
190
485
  );
486
+ const regenerate = summarizeRegenerate(protectedFiles, outcomes);
487
+ // The run stopped early; the text still names every file to rebuild.
488
+ logRegenerate(regenerate);
191
489
  return /** @type {import('../upgrade.type.mjs').UpgradeRunResponse['data']} */ ({
192
490
  from,
193
491
  to,
@@ -206,10 +504,14 @@ function stoppedReceipt({
206
504
  filesChanged: modifiedFiles.length,
207
505
  transformsApplied,
208
506
  modifiedFiles,
209
- protectedFiles: summarizeProtectedFiles(protectedRows),
507
+ protectedFiles,
210
508
  declinedCandidates: logged(
211
- summarizeDeclinedCandidates(declinedRows, protectedRows),
509
+ summarizeDeclinedCandidates(
510
+ [...declinedRows, ...manualDeclinedRows(outcomes)],
511
+ protectedRows,
512
+ ),
212
513
  ),
514
+ regenerate,
213
515
  complete: false,
214
516
  errorCode,
215
517
  errors,
@@ -393,16 +695,22 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
393
695
  }
394
696
 
395
697
  // CORE codemods run FIRST (before loading config) so a core CONFIG codemod can
396
- // repair a config the strict loader would otherwise reject.
397
- const codemodResult = await runCoreCodemods(versionManifests, {
398
- apply,
399
- path: path_,
400
- codemod: options.codemod,
401
- skipCodemods,
402
- root: cwd,
403
- protection,
404
- coversTarget: !cliBehindCore,
405
- });
698
+ // repair a config the strict loader would otherwise reject. Manual-migration
699
+ // and regeneration outcomes they report are collected, not counted as errors.
700
+ const initialOutcomes = withCodemodOutcomes(versionManifests, cwd);
701
+ const codemodResult = await runCoreCodemods(
702
+ initialOutcomes.versionManifests,
703
+ {
704
+ apply,
705
+ path: path_,
706
+ codemod: options.codemod,
707
+ skipCodemods,
708
+ root: cwd,
709
+ protection,
710
+ coversTarget: !cliBehindCore,
711
+ outcomes: initialOutcomes.outcomes,
712
+ },
713
+ );
406
714
  const coreResult =
407
715
  codemodResult && 'totalFilesChanged' in codemodResult
408
716
  ? codemodResult
@@ -424,15 +732,30 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
424
732
  iconSets = projectContext.iconSets;
425
733
  } catch (err) {
426
734
  const configErr = /** @type {Error} */ (err);
427
- const allProtected = coreResult?.protectedFiles ?? [];
735
+ const allProtected = [
736
+ ...(coreResult?.protectedFiles ?? []),
737
+ ...regenerationProtectionRows(initialOutcomes.outcomes, protection, cwd),
738
+ ];
739
+ const staleErrors = regenerationErrors(
740
+ initialOutcomes.outcomes,
741
+ protection,
742
+ cwd,
743
+ );
744
+ // A protected file to regenerate blocks the run like any protected file,
745
+ // so it keeps this incomplete result rather than the config error.
428
746
  if (allProtected.length > 0) {
429
747
  const protectedFiles = summarizeProtectedFiles(allProtected);
430
- logger.error(
748
+ const regenerate = summarizeRegenerate(
749
+ protectedFiles,
750
+ initialOutcomes.outcomes,
751
+ );
752
+ // The protected result wins, but the config error stays visible.
753
+ logger.error(configErr.message);
754
+ logProtectedFiles(
431
755
  `${ERROR_CODES.ERR_CODEMOD_PROTECTED}: protected codemod changes remain while loading the Astryx config.`,
756
+ protectedFiles,
432
757
  );
433
- for (const item of protectedFiles) {
434
- logger.error(` ${item.file} — ${item.declarations.join('; ')}`);
435
- }
758
+ logRegenerate(regenerate, protectedFiles);
436
759
  if (cliBehindCore) logCliBehindCore(cliBehindCore, targetVersion);
437
760
  logger.log('Upgrade incomplete: protected changes remain\n');
438
761
  return {
@@ -460,13 +783,21 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
460
783
  protectedFiles,
461
784
  declinedCandidates: logged(
462
785
  summarizeDeclinedCandidates(
463
- coreResult?.declinedCandidates ?? [],
786
+ [
787
+ ...(coreResult?.declinedCandidates ?? []),
788
+ ...manualDeclinedRows(initialOutcomes.outcomes),
789
+ ],
464
790
  allProtected,
465
791
  ),
466
792
  ),
793
+ regenerate,
467
794
  complete: false,
468
795
  errorCode: 'ERR_CODEMOD_PROTECTED',
469
- errors: coreResult?.errors ?? [],
796
+ errors: [
797
+ ...(coreResult?.errors ?? []),
798
+ ...staleErrors,
799
+ {file: '.', codemod: 'config', error: configErr.message},
800
+ ],
470
801
  ...(cliBehindCore ? {cliBehindCore} : {}),
471
802
  },
472
803
  };
@@ -500,8 +831,12 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
500
831
  // Genuine config error: abort.
501
832
  logger.error(configErr.message);
502
833
  logger.log('Aborted\n');
503
- if ((coreResult?.writtenFiles.length ?? 0) > 0) {
504
- // Core codemods already wrote: the error carries what they changed.
834
+ if (
835
+ (coreResult?.writtenFiles.length ?? 0) > 0 ||
836
+ initialOutcomes.outcomes.length > 0
837
+ ) {
838
+ // Core codemods already wrote, or reported files to regenerate or
839
+ // migrate by hand: the error carries what they changed and found.
505
840
  if (cliBehindCore) logCliBehindCore(cliBehindCore, targetVersion);
506
841
  const stopped = stoppedReceipt({
507
842
  from: currentVersion,
@@ -513,8 +848,10 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
513
848
  changedFiles: coreResult?.changedFiles ?? [],
514
849
  transformsApplied: coreResult?.totalTransformsApplied ?? 0,
515
850
  protectedRows: [],
851
+ outcomes: initialOutcomes.outcomes,
516
852
  errors: [
517
853
  ...(coreResult?.errors ?? []),
854
+ ...staleErrors,
518
855
  {file: '.', codemod: 'config', error: configErr.message},
519
856
  ],
520
857
  declinedRows: coreResult?.declinedCandidates ?? [],
@@ -675,15 +1012,21 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
675
1012
  ];
676
1013
  const registryFilesChanged = registryResult?.writtenFiles.length ?? 0;
677
1014
  const generatedChangeBlocked = initialProtected.some(item => item.generated);
1015
+ // Generated outputs a codemod reported out of date: the project's declared
1016
+ // regeneration may rebuild them, exactly like a blocked generated change.
1017
+ const reportedRegeneration = initialOutcomes.outcomes.filter(
1018
+ outcome => outcome.kind === 'regenerate',
1019
+ );
678
1020
  const shouldRunHooks =
679
1021
  postCodemodHooks.length > 0 &&
680
1022
  (mergedFilesChanged > 0 ||
681
1023
  registryFilesChanged > 0 ||
682
- generatedChangeBlocked);
1024
+ generatedChangeBlocked ||
1025
+ reportedRegeneration.length > 0);
683
1026
  /** @type {Map<string, Buffer>} */
684
1027
  const protectedBeforeHooks = new Map();
685
1028
  if (apply && shouldRunHooks) {
686
- for (const item of initialProtected) {
1029
+ for (const item of [...initialProtected, ...reportedRegeneration]) {
687
1030
  const absolute = path.resolve(cwd, item.file);
688
1031
  const relative = path.relative(cwd, absolute);
689
1032
  if (
@@ -718,7 +1061,12 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
718
1061
  const hookErr = /** @type {Error} */ (err);
719
1062
  const msg = `Post-codemod hook failed: ${hookErr.message}`;
720
1063
  logger.error(msg);
721
- if (initialProtected.length === 0) {
1064
+ const protectedRegeneration = regenerationProtectionRows(
1065
+ initialOutcomes.outcomes,
1066
+ protection,
1067
+ cwd,
1068
+ );
1069
+ if (initialProtected.length === 0 && protectedRegeneration.length === 0) {
722
1070
  logger.log('Upgrade failed\n');
723
1071
  throw failWithReceipt(
724
1072
  msg,
@@ -733,8 +1081,10 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
733
1081
  changedFiles: mergedChangedFiles,
734
1082
  transformsApplied: mergedTransformsApplied,
735
1083
  protectedRows: [],
1084
+ outcomes: initialOutcomes.outcomes,
736
1085
  errors: [
737
1086
  ...mergedErrors,
1087
+ ...regenerationErrors(initialOutcomes.outcomes, protection, cwd),
738
1088
  {file: '.', codemod: 'post-codemod-hook', error: msg},
739
1089
  ],
740
1090
  declinedRows: [
@@ -776,6 +1126,8 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
776
1126
  ...(coreResult?.declinedCandidates ?? []),
777
1127
  ...(integrationResult?.declinedCandidates ?? []),
778
1128
  ];
1129
+ let finalOutcomes = initialOutcomes.outcomes;
1130
+ let finalProtection = protection;
779
1131
  if (apply && shouldRunHooks && !hookFailure) {
780
1132
  let refreshedProtection;
781
1133
  try {
@@ -793,9 +1145,18 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
793
1145
  cwd,
794
1146
  changedFiles: [...mergedChangedFiles, ...hookModifiedFiles],
795
1147
  transformsApplied: mergedTransformsApplied,
796
- protectedRows: initialProtected,
1148
+ protectedRows: [
1149
+ ...initialProtected,
1150
+ ...regenerationProtectionRows(
1151
+ initialOutcomes.outcomes,
1152
+ protection,
1153
+ cwd,
1154
+ ),
1155
+ ],
1156
+ outcomes: initialOutcomes.outcomes,
797
1157
  errors: [
798
1158
  ...mergedErrors,
1159
+ ...regenerationErrors(initialOutcomes.outcomes, protection, cwd),
799
1160
  {file: '.', codemod: 'file-protection', error: err.message},
800
1161
  ],
801
1162
  declinedRows: [
@@ -810,7 +1171,8 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
810
1171
  });
811
1172
  throw failWithReceipt(err.message, err.code, stopped);
812
1173
  }
813
- const coreCheck = await runCoreCodemods(versionManifests, {
1174
+ const recheckOutcomes = withCodemodOutcomes(versionManifests, cwd);
1175
+ const coreCheck = await runCoreCodemods(recheckOutcomes.versionManifests, {
814
1176
  apply: false,
815
1177
  path: path_,
816
1178
  codemod: options.codemod,
@@ -866,6 +1228,8 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
866
1228
  ...(checkedCore?.declinedCandidates ?? []),
867
1229
  ...(integrationCheck?.declinedCandidates ?? []),
868
1230
  ];
1231
+ finalOutcomes = recheckOutcomes.outcomes;
1232
+ finalProtection = refreshedProtection;
869
1233
  finalErrors = [
870
1234
  ...mergedErrors,
871
1235
  ...(checkedCore?.errors ?? []),
@@ -873,7 +1237,10 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
873
1237
  ];
874
1238
  }
875
1239
 
876
- const protectedFiles = summarizeProtectedFiles(remainingProtected);
1240
+ const protectedFiles = summarizeProtectedFiles([
1241
+ ...remainingProtected,
1242
+ ...regenerationProtectionRows(finalOutcomes, finalProtection, cwd),
1243
+ ]);
877
1244
  receipt.filesChanged = mergedFilesChanged;
878
1245
  receipt.transformsApplied = mergedTransformsApplied;
879
1246
  receipt.modifiedFiles = uniqueFiles([
@@ -881,11 +1248,28 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
881
1248
  ...hookModifiedFiles,
882
1249
  ]).map(file => path.relative(cwd, file).split(path.sep).join('/'));
883
1250
  receipt.protectedFiles = protectedFiles;
884
- receipt.declinedCandidates = logged(
885
- summarizeDeclinedCandidates(remainingDeclined, remainingProtected),
1251
+ const declinedCandidates = logged(
1252
+ summarizeDeclinedCandidates(
1253
+ [...remainingDeclined, ...manualDeclinedRows(finalOutcomes)],
1254
+ // The complete final set, regeneration rows included: a file listed
1255
+ // under protectedFiles is never also declined.
1256
+ protectedFiles,
1257
+ ),
886
1258
  );
887
- receipt.complete = protectedFiles.length === 0 && finalErrors.length === 0;
888
- if (protectedFiles.length > 0) {
1259
+ receipt.declinedCandidates = declinedCandidates;
1260
+ const regenerate = summarizeRegenerate(protectedFiles, finalOutcomes);
1261
+ receipt.regenerate = regenerate;
1262
+ // A protected file to rebuild blocks the run like any protected file
1263
+ // (spec:AST-040 FR6). An unprotected one is a required change the codemod
1264
+ // could not make: a codemod error. A declined candidate, a manual
1265
+ // migration included, never blocks (FR7).
1266
+ finalErrors = [
1267
+ ...finalErrors,
1268
+ ...regenerationErrors(finalOutcomes, finalProtection, cwd),
1269
+ ];
1270
+ const blocked = protectedFiles.length > 0;
1271
+ receipt.complete = !blocked && finalErrors.length === 0;
1272
+ if (blocked) {
889
1273
  receipt.errorCode = 'ERR_CODEMOD_PROTECTED';
890
1274
  } else if (finalErrors.length > 0) {
891
1275
  // Only on the receipt the thrown error carries (below).
@@ -895,19 +1279,15 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
895
1279
  if (registryResult) receipt.registryCompositions = registryResult.summary;
896
1280
  if (cliBehindCore) receipt.cliBehindCore = cliBehindCore;
897
1281
 
898
- if (protectedFiles.length > 0) {
899
- logger.error(
900
- `${ERROR_CODES.ERR_CODEMOD_PROTECTED}: ${protectedFiles.length} protected file${protectedFiles.length === 1 ? '' : 's'} still require${protectedFiles.length === 1 ? 's' : ''} a codemod change:`,
901
- );
902
- for (const item of protectedFiles) {
903
- logger.error(` ${item.file} — ${item.declarations.join('; ')}`);
904
- for (const command of item.commands) {
905
- logger.log(` Regenerate with: ${command}`);
906
- }
907
- }
908
- }
1282
+ logProtectedFiles(
1283
+ `${ERROR_CODES.ERR_CODEMOD_PROTECTED}: ${protectedFiles.length} protected file${protectedFiles.length === 1 ? '' : 's'} still require${protectedFiles.length === 1 ? 's' : ''} a codemod change:`,
1284
+ protectedFiles,
1285
+ );
1286
+ // Generated outputs a codemod reported out of date, beyond the protected
1287
+ // files already listed above.
1288
+ logRegenerate(regenerate, protectedFiles);
909
1289
 
910
- if (finalErrors.length > 0 && protectedFiles.length === 0) {
1290
+ if (finalErrors.length > 0 && !blocked) {
911
1291
  const msg = `Upgrade completed with ${finalErrors.length} codemod error${finalErrors.length === 1 ? '' : 's'}.`;
912
1292
  logger.log('Upgrade failed\n');
913
1293
  // The error carries the receipt: every file the codemods wrote before the
@@ -944,14 +1324,19 @@ export async function run(options = {}, {cwd = process.cwd(), origin} = {}) {
944
1324
  : apply
945
1325
  ? 'Upgrade complete'
946
1326
  : 'Dry run complete';
1327
+ const manualCount = countManualMigrations(declinedCandidates);
1328
+ const manualNote =
1329
+ manualCount > 0
1330
+ ? `; ${manualCount} manual migration${manualCount === 1 ? '' : 's'} listed above`
1331
+ : '';
947
1332
  logger.log(
948
1333
  protectedFiles.length > 0
949
1334
  ? 'Upgrade incomplete: protected changes remain\n'
950
1335
  : !registryOk
951
1336
  ? 'Upgrade finished with unresolved registry items\n'
952
1337
  : sourcePathFound
953
- ? done + '\n'
954
- : `${done}, but ${path.relative(cwd, path_) || '.'} does not exist, so no source files were scanned. ` +
1338
+ ? done + manualNote + '\n'
1339
+ : `${done}${manualNote}, but ${path.relative(cwd, path_) || '.'} does not exist, so no source files were scanned. ` +
955
1340
  `Pass --path <your source directory> if your code does not live in ./src.\n`,
956
1341
  );
957
1342
  return {