Repository navigation
Expand file tree
/
Copy pathmeta.ts
More file actions
2039 lines (1935 loc) · 95.5 KB
/
Copy pathmeta.ts
File metadata and controls
2039 lines (1935 loc) · 95.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Args, Command, Flags } from '@oclif/core';
import { writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { createInterface } from 'node:readline';
import chalk from 'chalk';
import { ALL_CONVERSIONS, ObjectStackDefinitionSchema, formatZodIssue, normalizeStackInput } from '@objectstack/spec';
import {
applyMetaMigrations,
composeSpecChanges,
MigrationFloorError,
MIGRATION_MAJORS,
MIGRATION_SUPPORT_FLOOR,
type MigrationApplication,
type MigrationChainResult,
type MigrationHopResult,
type MigrationTodo,
} from '@objectstack/spec/migrations';
import { PROTOCOL_MAJOR, PROTOCOL_VERSION } from '@objectstack/spec/kernel';
import { FILE_REFERENCE_TYPES, REFERENCE_VALUE_TYPES, STRUCTURED_JSON_TYPES } from '@objectstack/spec/data';
import { FILE_REFERENCES_MIGRATION_ID, VALUE_SHAPES_MIGRATION_ID } from '@objectstack/spec/system';
import { loadConfig } from '../../utils/config.js';
import { printNoneProvenAbsent, printUnansweredRelevance } from '../../utils/migrate-meta-relevance.js';
import { authoringRuleUnionStack } from '../../utils/stack-collections.js';
import {
printHeader,
printSuccess,
printWarning,
printError,
printInfo,
printStep,
createTimer,
emitJson,
errorCodeFields,
isExitSignal,
isReportedError,
} from '../../utils/format.js';
import { bootSchemaStack } from '../../utils/schema-migrate.js';
import { buildDataMigrationPlugins } from '../../utils/data-migration-plugins.js';
import { absentTableReads } from '../../utils/absent-table-reads.js';
import type { StoredMigrationReport } from '@objectstack/metadata-protocol';
import { OCCUPANCY_HINT, probeMigrationTarget } from '../../utils/migrate-occupancy-gate.js';
import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js';
import { checkProtocolCompat, type ProtocolHandshakeManifest } from '@objectstack/metadata-core';
import {
RANGE_ENTRY_ID,
planAuthoredSourceWrite,
restoreAuthoredSources,
verifyAuthoredSourceWrite,
writeAuthoredSources,
type AuthoredSourceWritePlan,
type CodemodRefusal,
type CodemodRefusalKind,
type RangeOutcome,
type RangeRewrite,
type WritePair,
type WriteVerification,
} from '../../utils/authored-source-codemod.js';
async function confirm(question: string): Promise<boolean> {
if (!process.stdin.isTTY) return false; // non-interactive → require --yes
const rl = createInterface({ input: process.stdin, output: process.stdout });
try {
const answer: string = await new Promise((res) => rl.question(question, res));
return /^y(es)?$/i.test(answer.trim());
} finally {
rl.close();
}
}
/** The protocol major that introduced the per-deployment value-shape gates. */
const VALUE_SHAPE_GATE_MAJOR = 17;
/**
* Where the chain ENDS when the author does not say — the highest major this
* build of `@objectstack/spec` carries a migration step for, never below the
* protocol major the runtime implements.
*
* ## Why not `PROTOCOL_MAJOR` (the answer this replaces)
*
* A tombstone closes with the house sentence "Run `os migrate meta --from N`
* to list the mechanical edits for existing sources", and its `N` is the major
* the source was AUTHORED against — one below the `toMajor` of the ADR-0087
* conversion that performs the rename. That template presumes the default
* terminus is at least the conversion's own `toMajor`.
*
* The presumption held only AFTER the next major shipped. Retirements land
* throughout a major's line: `@objectstack/spec@17.4.0` tombstones keys whose
* conversion is registered `toMajor: 18` and whose semantic siblings are
* already removed from its own exports — the build's authorable surface is
* ahead of the version it calls itself. Defaulting `--to` to `PROTOCOL_MAJOR`
* (17) then composed `17 → 17`, which selects NO step at all
* (`composeMigrationChain` keeps `m > fromMajor`), so the invocation 29
* shipped tombstones prescribe replayed an empty chain and reported
* `Nothing to migrate` — for the very conversions that sent the author here.
*
* Reading the terminus off `MIGRATION_MAJORS` makes the template's presumption
* true in every window instead of only after a major release, and it stays
* true one major later by construction: when 18 ships, `PROTOCOL_MAJOR`
* becomes 18, the 19 entries accumulating in the registry become the terminus,
* and `--from 18` lists them the same way.
*
* ⛔ Not "migrating past what the runtime runs": every conversion in the
* registry maps a shape the installed schemas REFUSE onto the one they accept
* (that is what makes it a conversion), so the terminus is the only target
* for which the command's own `schemaValid` verdict is reachable. `Math.max`
* keeps `PROTOCOL_MAJOR` as the floor for the reverse case — a runtime whose
* major moved past the last registered step.
*/
const CHAIN_TERMINUS_MAJOR = Math.max(PROTOCOL_MAJOR, ...MIGRATION_MAJORS);
const isRecord = (value: unknown): value is Record<string, unknown> =>
value !== null && typeof value === 'object' && !Array.isArray(value);
/**
* The migration chain over a stack AND each package body it carries — what
* `applyMetaMigrations` is for this command, at every call site.
*
* ## Why the bodies need their own run
*
* The conversions walk a stack's own collections (`objects[]`, `views[]`,
* `pages[]`, …) and do not descend into `packages[]`. A multi-package
* artifact built by `composeStacks(…, { manifest: 'preserve' })` carries each
* definition ONCE, under the package that owns it (ADR-0130 D4 addendum): its
* top level holds `manifest` and `packages` and no flattened copy. So a
* retired spelling inside a package was reached by no conversion — `applied`
* came back empty and the schema verdict refused the very spelling the chain
* exists to convert.
*
* A body (`packages[i].manifest`) is a stack-shaped bag — manifest fields and
* collections side by side — so the chain runs over each body as a stack, and
* each of its applications is listed under the body's own path
* (`packages[0].manifest.objects[0]…`), which names the package and is the
* path `--write` traces to the input that authored it. A conversion whose
* reach already includes `packages[].manifest` (the manifest's permission
* list) runs in the stack's own run and finds no `manifest` key in a body,
* so nothing is applied twice.
*
* ## The merged result
*
* - `applied` keeps application order hop by hop: the stack's own edits of a
* hop, then each body's, in package order.
* - `todos` is the stack's own list — every semantic entry of every hop
* crossed is in it whatever the stack holds, so a body's run lists the same
* entries again.
* - `absentTodos` keeps an entry only when every run names it — the stack's
* own and each body's — matched by hop and id. The relevance question
* already reads `packages[]` itself; what a body's run adds is its own
* applications, and an entry that judges a conversion which applied an
* edit is never named absent.
* - A stack without a `packages` list, which is every one-package project,
* gets the plain chain result back unchanged.
*/
export function applyMetaMigrationsToPackages(
stack: Record<string, unknown>,
fromMajor: number,
toMajor: number,
): MigrationChainResult {
const own = applyMetaMigrations(stack, fromMajor, toMajor);
const entries = own.stack.packages;
if (!Array.isArray(entries)) return own;
const bodies: Array<{ index: number; prefix: string; run: MigrationChainResult }> = [];
for (const [index, entry] of entries.entries()) {
if (!isRecord(entry) || !isRecord(entry.manifest)) continue;
bodies.push({
index,
prefix: `packages[${index}].manifest`,
run: applyMetaMigrations(entry.manifest, fromMajor, toMajor),
});
}
if (bodies.length === 0) return own;
const located = (prefix: string) => (application: MigrationApplication): MigrationApplication => ({
...application,
path: application.path ? `${prefix}.${application.path}` : prefix,
});
const todoKey = (todo: MigrationTodo) => `${todo.toMajor}:${todo.id}`;
const absentEverywhere = (absent: readonly MigrationTodo[], bodyAbsent: (run: MigrationChainResult) => readonly MigrationTodo[]) => {
const bodySets = bodies.map(({ run }) => new Set(bodyAbsent(run).map(todoKey)));
return absent.filter((todo) => bodySets.every((set) => set.has(todoKey(todo))));
};
/** `base` with each body replaced by its stack from `pick`, copied only where one changed. */
const withBodies = (base: Record<string, unknown>, pick: (run: MigrationChainResult) => Record<string, unknown>) => {
const list = base.packages;
if (!Array.isArray(list)) return base;
let changed = false;
const next = list.slice();
for (const { index, run } of bodies) {
const entry = next[index];
const body = pick(run);
if (!isRecord(entry) || entry.manifest === body) continue;
next[index] = { ...entry, manifest: body };
changed = true;
}
return changed ? { ...base, packages: next } : base;
};
const hops: MigrationHopResult[] = own.hops.map((hop, k) => ({
...hop,
stack: withBodies(hop.stack, (run) => run.hops[k]!.stack),
applied: [...hop.applied, ...bodies.flatMap(({ prefix, run }) => run.hops[k]!.applied.map(located(prefix)))],
absentTodos: absentEverywhere(hop.absentTodos, (run) => run.hops[k]!.absentTodos),
}));
return {
...own,
stack: withBodies(own.stack, (run) => run.stack),
applied: hops.flatMap((hop) => hop.applied),
absentTodos: absentEverywhere(own.absentTodos, (run) => run.absentTodos),
hops,
};
}
/** Flags that mean something only in `--stored` mode (#4327). */
const STORED_ONLY_FLAGS = ['apply', 'yes', 'force', 'type', 'database-url'] as const;
/**
* Which stored-only flags the operator actually TYPED.
*
* oclif's own `dependsOn` cannot answer this: a boolean with `default: false`
* and an `env`-backed string both read as "provided" to it, so declaring
* `dependsOn: ['stored']` on `--database-url` would make a merely-exported
* `OS_DATABASE_URL` break `os migrate meta --from N`. The raw argv is the only
* signal for intent, so the guard reads that.
*/
export function storedOnlyFlagsIn(argv: readonly string[]): string[] {
const typed = STORED_ONLY_FLAGS.filter((f) =>
argv.some((a) => a === `--${f}` || a.startsWith(`--${f}=`)),
) as string[];
if (argv.includes('-y') && !typed.includes('yes')) typed.push('yes');
return typed;
}
export interface PendingDataMigration {
/** `sys_migration` row id the run records. */
id: string;
command: string;
/** What staying un-run costs, in this deployment's terms. */
unlocks: string;
}
/**
* The DATA migrations a metadata chain crossing into {@link VALUE_SHAPE_GATE_MAJOR}
* leaves for the operator (ADR-0104's 2026-07-30 addendum, #3438).
*
* Metadata migration and data migration are different jobs with different
* subjects: this command reports the edits an author's source needs, while
* these two rewrite (or vouch for) a deployment's rows, one deployment at a
* time. Nothing here can run them, and — with no database in reach — nothing
* here can say whether they have run; the booting server reports that. What
* this can do is make sure the upgrade never *ends* without naming them,
* because a gate nobody is told about is served by nobody.
*
* Listed only when the author's own metadata declares the field classes each
* gate is about, so the advice is never noise.
*/
function pendingDataMigrations(stack: any, fromMajor: number, toMajor: number): PendingDataMigration[] {
if (!(fromMajor < VALUE_SHAPE_GATE_MAJOR && toMajor >= VALUE_SHAPE_GATE_MAJOR)) return [];
let media = false;
let covered = false;
for (const obj of (Array.isArray(stack?.objects) ? stack.objects : []) as any[]) {
for (const def of Object.values(obj?.fields ?? {}) as any[]) {
if (!def?.type) continue;
if (FILE_REFERENCE_TYPES.has(def.type)) media = true;
else if (REFERENCE_VALUE_TYPES.has(def.type) || STRUCTURED_JSON_TYPES.has(def.type)) covered = true;
}
if (media && covered) break;
}
const pending: PendingDataMigration[] = [];
if (media) {
pending.push({
id: FILE_REFERENCES_MIGRATION_ID,
command: 'os migrate files-to-references',
unlocks:
'converts legacy file values to sys_file references, then enforces media value shapes ' +
'and lets released files be collected. Until it passes here, media values only warn and ' +
'released files are kept forever.',
});
}
if (covered) {
pending.push({
id: VALUE_SHAPES_MIGRATION_ID,
command: 'os migrate value-shapes',
unlocks:
'scans stored reference and structured-JSON values against their field contracts. ' +
'Until it passes here, a malformed value only warns.',
});
}
return pending;
}
/**
* What a run that replayed NO migration step owes its reader (#17134), on both
* faces: the human run renders it ({@link printReplayedNothing}) and `--json`
* carries it as `replayedNothing` (#28947). One reading, so the two faces
* cannot disagree about whether a step ran or what a wider range holds.
*/
interface ReplayedNothing {
/**
* Why no step ran: `inverted-range` when `--from` is above `--to`, so no
* major can lie between them; `empty-range` when the range is well-formed
* but this build carries no step inside it.
*/
reason: 'empty-range' | 'inverted-range';
/**
* The widest range this build carries from the same `--from`, and how many
* mechanical and manual changes it holds for THIS stack (zero and zero when
* it has nothing either). `null` when no wider range is available: `--to`
* already reaches the terminus, or `--from` is at or above it, so any range
* from that `--from` to the terminus is itself empty or inverted.
*/
widestRange: { from: number; to: number; applied: number; manual: number } | null;
}
/**
* The answer a range holding NO migration step owes the author (#17134), or
* `null` when the run replayed at least one step.
*
* `composeMigrationChain` keeps the majors `m > fromMajor && m <= toMajor`, so
* `--from 17 --to 17` composes zero steps and every stack — canonical or not —
* comes back with an empty `applied` and an empty `todos`. Reporting that as
* `✓ Nothing to migrate — the metadata is already canonical for this range` is
* not merely unhelpful: it is a green verdict on a check that never ran, and
* it is the SECOND signal an upgrading author has already been told to trust
* (the first was the tombstone that named this command). So an empty range is
* answered as an empty range, and — when a wider one would rewrite this very
* stack — with the range that lists them, because "which `--to` do I need" is
* the question the author is left holding. An inverted range (`--from` above
* `--to`) composes zero steps the same way and is answered the same way, its
* reason naming the inversion; it is answered, never refused.
*
* The probe is exact rather than advisory: it replays the widest chain this
* build carries against the SAME normalized stack, so it can only speak up
* when there is real work for THIS source. A genuinely canonical stack in an
* empty range is still told its range was empty — that much is a fact about
* the invocation — but is offered no phantom conversions.
*
* ⛔ `--json` reads this function too. Its payload used to answer an empty
* range exactly like a clean replay (`applied: []`, `schemaValid: true`, exit
* 0), so a script with a wrong `--from` was told its metadata was migrated
* while the human run warned (#28947).
*/
function readReplayedNothing(
stack: Record<string, unknown>,
result: Pick<MigrationChainResult, 'hops' | 'fromMajor' | 'toMajor'>,
): ReplayedNothing | null {
if (result.hops.length > 0) return null;
const { fromMajor, toMajor } = result;
const reason = fromMajor > toMajor ? 'inverted-range' : 'empty-range';
if (toMajor >= CHAIN_TERMINUS_MAJOR || fromMajor >= CHAIN_TERMINUS_MAJOR) {
return { reason, widestRange: null };
}
const wider = applyMetaMigrationsToPackages(stack, fromMajor, CHAIN_TERMINUS_MAJOR);
return {
reason,
widestRange: {
from: fromMajor,
to: CHAIN_TERMINUS_MAJOR,
applied: wider.applied.length,
manual: listedTodos(wider.todos, wider.absentTodos).length,
},
};
}
/** The human face of {@link readReplayedNothing}. */
function printReplayedNothing(answer: ReplayedNothing, fromMajor: number, toMajor: number): void {
const notCanonical = 'this run replayed nothing — that is not a finding that the metadata is canonical.';
printWarning(
answer.reason === 'inverted-range'
? `--from ${fromMajor} is above --to ${toMajor}, so the range is inverted and ${notCanonical}`
: `No migration step exists for protocol ${fromMajor} → ${toMajor}, so ${notCanonical}`,
);
const { widestRange } = answer;
if (widestRange === null) {
printInfo(
`Protocol ${CHAIN_TERMINUS_MAJOR} is the highest major this build carries a step for, so no `
+ 'wider range is available; check `--from` against the major the metadata was authored '
+ 'against.',
);
return;
}
if (widestRange.applied === 0 && widestRange.manual === 0) {
printInfo(
`The widest range this build carries (protocol ${widestRange.from} → ${widestRange.to}) has `
+ 'nothing for this stack either.',
);
return;
}
printWarning(
`Protocol ${widestRange.from} → ${widestRange.to} has ${widestRange.applied} mechanical and `
+ `${widestRange.manual} manual change(s) for this stack — re-run with `
+ `\`--to ${widestRange.to}\` to list them.`,
);
}
/**
* The semantic TODOs the default list prints: every entry of `todos` except
* the ones `absentTodos` names (ADR-0087 D3 — an entry leaves the default list
* only on the chain's structured, stack-derived proof). Matched by hop and id,
* so a copy of a TODO is recognised as well as the chain's own object.
*/
function listedTodos(todos: readonly MigrationTodo[], absentTodos: readonly MigrationTodo[]): MigrationTodo[] {
if (absentTodos.length === 0) return [...todos];
const absent = new Set(absentTodos.map((t) => `${t.toMajor}:${t.id}`));
return todos.filter((t) => !absent.has(`${t.toMajor}:${t.id}`));
}
/** Print the data-migration advice — the last thing a crossing upgrade sees. */
function printPendingDataMigrations(pending: readonly PendingDataMigration[]): void {
if (pending.length === 0) return;
console.log(chalk.bold(' Then, against each deployment\'s database:'));
for (const m of pending) {
console.log(` ${chalk.cyan('→')} ${chalk.white(m.command)}`);
console.log(chalk.dim(` ${m.unlocks}`));
}
console.log(
chalk.dim(
' Both are dry-run by default and report what they would do; `--apply` is the only ' +
'writing mode. Not running them is safe — enforcement simply stays off here.',
),
);
console.log('');
}
/**
* `--out`: write the migrated stack as a JSON snapshot, and print the line that
* names it. The one writer for both exits of {@link printMigrationReport}: the
* main path, and the early return of a run with nothing to migrate (#22116).
* An operator or a CI step keeps this file as the record of the run, so a run
* that returned without it left no file, or an earlier run's file read as this
* one's, behind an exit 0. `--json` writes the same bytes on its own branch.
*/
function writeStackSnapshot(out: string, stack: Record<string, unknown>): void {
writeFileSync(out, JSON.stringify(stack, null, 2));
printInfo(`Wrote migrated stack snapshot → ${chalk.white(out)}`);
}
/**
* What the run owes the manifest's declared protocol range (#22219).
*
* `rewrite`: the load refuses the range under the major this run migrated the
* source to, so `--write` rewrites it (and a dry run names the edit).
* `behind-from`: the load refuses it, but the chain started ABOVE the major the
* range declares, so it never replayed the majors in between; the range is
* left as written, and the report says which `--from` would move it.
*/
export type ProtocolRangePlan =
| { kind: 'rewrite'; rewrite: RangeRewrite }
| { kind: 'behind-from'; path: string; range: string; declaredMajor: number };
/** A manifest value narrowed to the strings the handshake reads; anything else reads as absent. */
function handshakeSlice(manifest: Record<string, unknown>): ProtocolHandshakeManifest {
const str = (v: unknown) => (typeof v === 'string' ? v : undefined);
const obj = (v: unknown) => (v && typeof v === 'object' ? (v as Record<string, unknown>) : undefined);
const engines = obj(manifest.engines);
const engine = obj(manifest.engine);
return {
...(engines ? { engines: { protocol: str(engines.protocol), platform: str(engines.platform) } } : {}),
...(engine ? { engine: { objectstack: str(engine.objectstack) } } : {}),
};
}
/**
* The declared protocol range a migrated source owes, judged by the load's
* own handshake (#22219).
*
* ## Why this exists
*
* The load refuses a manifest whose range excludes the runtime's major, and the
* refusal names `objectstack migrate meta --from N` as the command that resolves
* it (`ProtocolIncompatibleDiagnostic.migrateCommand`, ADR-0087 P2). No
* conversion touches the range, so `--write` used to write the chain's edits,
* leave `'^N'` as it was, and hand the author back the same refusal.
*
* ## Which major the range is moved to
*
* `--to`, capped at the protocol this runtime implements. `--to` defaults to
* {@link CHAIN_TERMINUS_MAJOR}, which runs AHEAD of {@link PROTOCOL_MAJOR} while
* this build carries the next major's conversions — measured on a protocol-17
* build, `--from 16` replays 16 → 18. Those conversions map shapes the
* installed schemas refuse onto ones they accept, so the migrated source is
* what THIS runtime loads, and `'^18'` would be refused by the same handshake
* (measured: "targets protocol ^18 … Run: objectstack migrate meta --from 18").
* A `--to` below this runtime's major stops there, and so does the range: the
* source was not migrated past it.
*
* ## Where, and in what spelling
*
* At the key the handshake READ (`resolveDeclaredRange`: `engines.protocol`,
* else `engines.platform`, else the legacy `engine.objectstack`), in place. No
* chain step moves a range between those keys, and the schema accepts all three,
* so moving one would be a conversion the chain has not declared; the key the
* handshake read is the key it reads again. The spelling is the scaffold's and
* `os lint`'s, `'^N'` — except under `engine.objectstack`, whose schema refuses
* anything short of a full version, so `'^N.0.0'` there.
*
* ## What it never does
*
* It never lowers a range: one declaring a major at or above the target is
* left for the handshake to refuse, since moving it down would silence a real
* mismatch. It never touches a range the load admits, an absent one, or one
* the handshake cannot parse (the load admits those too). And it moves a range
* only across majors the chain replayed: when `--from` starts above the major
* the range declares (and above the chain's floor), the range is left and the
* report names the `--from` that would move it.
*/
export function planProtocolRange(
stack: Record<string, unknown>,
fromMajor: number,
toMajor: number,
): ProtocolRangePlan | undefined {
// The slice the load's handshake reads: the bundle's `manifest`, else the
// bundle itself (`AppPlugin`: `bundle.manifest || bundle`).
const nested = stack.manifest && typeof stack.manifest === 'object';
const manifest = (nested ? stack.manifest : stack) as Record<string, unknown>;
const slice = handshakeSlice(manifest);
const major = Math.min(toMajor, PROTOCOL_MAJOR);
const compat = checkProtocolCompat(slice, `${major}.0.0`);
if (compat.status !== 'incompatible') return undefined;
const declaredMajor = compat.diagnostic.targetMajor;
if (declaredMajor === null || declaredMajor >= major) return undefined;
const path = `${nested ? 'manifest.' : ''}${compat.source}`;
const authored = compat.source === 'engines.protocol'
? slice.engines?.protocol
: compat.source === 'engines.platform' ? slice.engines?.platform : slice.engine?.objectstack;
const from = authored ?? compat.requiredRange;
if (fromMajor > Math.max(declaredMajor, MIGRATION_SUPPORT_FLOOR)) {
return { kind: 'behind-from', path, range: from, declaredMajor };
}
const to = compat.source === 'engine.objectstack' ? `^${major}.0.0` : `^${major}`;
return { kind: 'rewrite', rewrite: { path, from, to, major } };
}
/** A range string as the report quotes it. */
function quotedRange(range: string): string {
return `'${range}'`;
}
/** A dry run's range line (#22219): the edit `--write` would make, and why it is owed. */
function printRangeDryRun(rewrite: RangeRewrite): void {
printWarning(
`${rewrite.path} ${quotedRange(rewrite.from)} does not admit protocol ${rewrite.major}, so the load `
+ `refuses this stack even after migrating; --write rewrites it to ${quotedRange(rewrite.to)}.`,
);
console.log('');
}
/** The range a run left because it started above the major the range declares (#22219). */
function printRangeLeft(plan: Extract<ProtocolRangePlan, { kind: 'behind-from' }>, fromMajor: number): void {
// The lowest `--from` that replays every major the range missed — never under the chain's floor.
const start = Math.max(plan.declaredMajor, MIGRATION_SUPPORT_FLOOR);
printWarning(
`${plan.path} ${quotedRange(plan.range)} declares protocol ${plan.declaredMajor}, below --from ${fromMajor}: `
+ `this run did not replay protocol ${start} → ${fromMajor}, so the range is left as written and `
+ `the load still refuses it. Run with --from ${start}.`,
);
console.log('');
}
/** What `--write` did with the declared range (#22219): written at its site, or left with the reason. */
function printRangeOutcome(range: RangeOutcome): void {
const { rewrite } = range;
const edit = `${rewrite.path}: ${quotedRange(rewrite.from)} → ${quotedRange(rewrite.to)}`;
if (range.status === 'written') {
console.log(chalk.bold(` Rewrote the declared protocol range, so the load admits protocol ${rewrite.major}:`));
console.log(` ${chalk.white(range.file)}${chalk.dim(`:${range.line}`)} ${edit}`);
console.log('');
return;
}
console.log(chalk.bold(chalk.yellow(
` The declared protocol range was left for you to change by hand; until then the load refuses it under protocol ${rewrite.major}:`,
)));
console.log(` ${chalk.yellow('•')} ${edit}`);
console.log(chalk.dim(` not written [${range.refusal.kind}]: ${range.refusal.reason}`));
console.log('');
}
/** One schema refusal of the migrated stack, in the shape `formatZodIssue` renders. */
export type MigrationRefusal = Parameters<typeof formatZodIssue>[0];
/** What `--write` did with the authored sources (#9591). */
export interface WriteOutcome {
plan: AuthoredSourceWritePlan;
/**
* `written` — the plan's files were written and the re-run agreed with it
* (units an earlier re-run disagreed with are on `manual` as `unverified`,
* #38922); `restored` — they were written, the re-run disagreed in a way no
* written unit could be tied to, and every one was put back; `unwritten` —
* writing was refused before any file changed.
* A plan with no file to write is `written` with an empty `rewrites`.
*/
status: 'written' | 'restored' | 'unwritten';
/** The re-run's verdict, when files were written. */
verification?: WriteVerification;
/** Why the write was refused or undone. */
error?: string;
}
/**
* The written entries a re-check over the written sources disagreed with, by
* `path (conversionId)`, each with the refusal it is left with (#38922): an
* entry the re-run still converts, and every written entry of a conversion
* one of whose left entries the re-run no longer converts (the write of that
* conversion's other sites took away what produced it). Empty when the
* disagreement names no written entry.
*/
export function disagreeingUnits(plan: AuthoredSourceWritePlan, verification: WriteVerification): Map<string, CodemodRefusal> {
const key = (a: { path: string; conversionId: string }) => `${a.path} (${a.conversionId})`;
const written = [...plan.written.map((w) => w.application), ...(plan.range?.status === 'written' ? [rangeEntry(plan.range)] : [])];
const out = new Map<string, CodemodRefusal>();
const still = new Set(verification.stillApplied);
for (const a of written) {
if (!still.has(key(a))) continue;
out.set(key(a), {
kind: 'unverified',
reason: 'it was written, and re-running the chain over the written sources still converted it, so its edits were put back',
});
}
const gone = verification.vanished.flatMap((k) => {
const left = [...plan.manual.map((m) => m.application), ...(plan.range?.status === 'manual' ? [rangeEntry(plan.range)] : [])];
return left.filter((a) => key(a) === k);
});
for (const v of gone) {
for (const a of written) {
if (a.conversionId !== v.conversionId || out.has(key(a))) continue;
out.set(key(a), {
kind: 'unverified',
reason: `it was written, and re-running the chain over the written sources no longer converted \`${v.path}\`, `
+ 'which this write left by hand, so its edits were put back',
});
}
}
return out;
}
/** The declared range as the planner lists it among the chain's entries (`rangeApplication` in the codemod). */
function rangeEntry(range: RangeOutcome): { path: string; conversionId: string } {
return { path: range.rewrite.path, conversionId: RANGE_ENTRY_ID };
}
/** The `--json` face of a {@link WriteOutcome}. */
export function writeOutcomeJson(outcome: WriteOutcome) {
const { plan } = outcome;
return {
status: outcome.status,
files: plan.rewrites.map((r) => ({
file: r.file,
sites: plan.written.filter((w) => w.file === r.file).length,
})),
written: plan.written.map((w) => ({
conversionId: w.application.conversionId,
path: w.application.path,
file: w.file,
line: w.line,
})),
manual: plan.manual.map((m) => ({
conversionId: m.application.conversionId,
path: m.application.path,
kind: m.refusal.kind,
reason: m.refusal.reason,
})),
unexplained: plan.unexplained,
// The declared protocol range (#22219), only when the run owed it an edit.
// Not one of `written` / `manual`: those list the chain's `applied`
// entries, and the range is not one.
...(plan.range ? { range: rangeOutcomeJson(plan.range) } : {}),
...(outcome.verification ? { verification: outcome.verification } : {}),
...(outcome.error ? { error: outcome.error } : {}),
// The pairs left whole (#38922), only when the plan held one. Each site is
// also on `manual`; here they are grouped as the one change they are.
...(plan.pairs ? { pairs: plan.pairs.map((p) => ({ sites: p.sites.map(pairSiteJson), files: pairFiles(plan, p) })) } : {}),
};
}
/** The `--json` face of one site of a {@link WritePair}. */
function pairSiteJson(site: WritePair['sites'][number]) {
return {
conversionId: site.application.conversionId,
path: site.application.path,
...(site.at ? { file: site.at.file, line: site.at.line } : {}),
...(site.refusal ? { kind: site.refusal.kind, reason: site.refusal.reason } : {}),
};
}
/** The files a pair's sites are in: where each would be written, and where a held one is found. */
function pairFiles(plan: AuthoredSourceWritePlan, pair: WritePair): string[] {
const files = pair.sites.flatMap((site) => {
if (site.at) return [site.at.file];
const found = plan.manual.find((m) => m.application === site.application)?.found;
return found ? [found.file] : [];
});
return [...new Set(files)].sort();
}
/** Whether a `--write` left any mechanical change, or the declared range, for the author. */
export function leftByHand(outcome: WriteOutcome): boolean {
return outcome.plan.manual.length > 0 || outcome.plan.range?.status === 'manual';
}
/** Why a site was left, as the first line of a partial write counts it: one noun phrase per refusal kind. */
const LEFT_BECAUSE: Readonly<Record<CodemodRefusalKind, string>> = {
computed: 'a value computed, not written as a literal',
helper: 'a value built by a helper call --write does not follow',
spread: 'a key a spread supplies or may override',
shared: 'a literal something else also references',
'outside-project': 'a site outside the project',
mismatch: 'a literal that does not match the loaded value',
injected: 'a key the loader supplied, not the literal',
unspellable: 'a value no literal can spell',
layout: 'an edit that would touch bytes outside its site',
unattributed: 'no edit tied to the site',
entangled: 'a linked site that was refused',
unverified: 'the re-run over the written sources disagreeing with it',
};
/**
* What a partial write's first line says was left, and why (#38922): the
* pairs left whole first, then the rest by what built them or by refusal kind,
* in first-seen order, each with its count.
*/
function leftBecause(plan: AuthoredSourceWritePlan): string {
const inPair = new Set((plan.pairs ?? []).flatMap((p) => p.sites.map((s) => s.application)));
const causes = new Map<string, number>();
const count = (cause: string) => causes.set(cause, (causes.get(cause) ?? 0) + 1);
const paired = plan.manual.filter((m) => inPair.has(m.application)).length;
if (paired > 0) {
causes.set(`${plan.pairs!.length} pair(s) written together or not at all, each with a site that cannot be written`, paired);
}
for (const m of plan.manual) {
if (inPair.has(m.application)) continue;
count(m.refusal.builder !== undefined
? `a value built by \`${m.refusal.builder}\`, which --write cannot follow to the sources`
: LEFT_BECAUSE[m.refusal.kind]);
}
return [...causes].map(([cause, n]) => `${cause} (${n})`).join('; ');
}
/**
* The pairs left whole (#38922): each site with where it would be written, or
* why it cannot be, and the files the pair is in.
*/
function printPairs(plan: AuthoredSourceWritePlan): void {
const pairs = plan.pairs ?? [];
if (pairs.length === 0) return;
console.log(chalk.bold(chalk.yellow(
` ${pairs.length} pair(s) left whole — re-running the chain shows each pair's sites are one change, written `
+ 'together or not at all, and a site of it cannot be written:',
)));
for (const pair of pairs) {
const shown = new Set<string>();
let first = true;
for (const site of pair.sites) {
const a = site.application;
const key = `${a.path} (${a.conversionId})`;
if (shown.has(key)) continue;
shown.add(key);
const names = site.items ? ` (where ${site.items.map((i) => `${i.at} is \`${i.name}\``).join(', ')})` : '';
const where = site.at
? `${site.at.file}:${site.at.line}`
: `not written [${site.refusal?.kind ?? 'entangled'}]: ${site.refusal?.reason ?? ''}`;
console.log(` ${first ? chalk.yellow('•') : ' '} ${a.path}${chalk.dim(names)} ${chalk.dim(`(${a.conversionId})`)} → ${chalk.dim(where)}`);
first = false;
}
console.log(chalk.dim(` files: ${pairFiles(plan, pair).join(', ')}`));
}
console.log('');
}
/** The `--json` face of a {@link RangeOutcome}. */
function rangeOutcomeJson(range: RangeOutcome) {
const { path, from, to } = range.rewrite;
return range.status === 'written'
? { status: range.status, path, from, to, file: range.file, line: range.line }
: { status: range.status, path, from, to, kind: range.refusal.kind, reason: range.refusal.reason };
}
/**
* The `--write` group's first line when none of the chain's edits was written:
* `0 of N … written`, then what the stack is built by — the distinct calls the
* walk could not follow, in first-seen order (each site below still names its
* own) — or, when no such call blocked it, that none was traced to a literal.
*/
function noneWrittenLine(plan: AuthoredSourceWritePlan, appliedCount: number): string {
const builders = [...new Set(plan.manual.flatMap((m) => (m.refusal.builder !== undefined ? [m.refusal.builder] : [])))];
const cause = builders.length > 0
? `your stack is built by ${builders.map((b) => `\`${b}\``).join(', ')}, which --write cannot follow to the sources`
: 'none of them could be traced to one literal in a project file';
return `0 of ${appliedCount} mechanical change(s) written — ${cause}; apply these by hand (each one's file and line, where found, is listed below):`;
}
/**
* The `--write` group: what was written where, what was left and why, and
* whether the re-run over the written sources agreed. Printed after the
* semantic notices and before the data-migration advice, which stays last.
*/
function printWriteOutcome(outcome: WriteOutcome, appliedCount: number): void {
const { plan } = outcome;
if (appliedCount === 0 && !plan.range) {
printInfo('--write: the chain made no mechanical change here, so no file was written.');
console.log('');
return;
}
if (outcome.status === 'unwritten') {
printError(`--write wrote nothing: ${outcome.error}`);
console.log('');
return;
}
const files = plan.rewrites.length;
if (outcome.status === 'restored') {
printError(
`--write wrote ${files} file(s), but re-running the chain over them did not match this report, so `
+ `every one was restored to its previous bytes: ${outcome.error}`,
);
console.log('');
return;
}
if (appliedCount === 0) {
// #22219: a stack with nothing to convert still owes the range its refusal names.
printInfo('--write: the chain made no mechanical change here; the declared protocol range is the one edit it owes.');
console.log('');
} else if (plan.written.length === 0) {
// Nothing of the chain's was written: the first line of the group says so,
// and what the stack is built by, so no "Applied" above it reads as done.
console.log(chalk.bold(chalk.yellow(` ${noneWrittenLine(plan, appliedCount)}`)));
console.log('');
} else {
// The files holding the chain's edits; a file holding only the range is the range group's.
const chainFiles = plan.rewrites.filter((r) => plan.written.some((w) => w.file === r.file));
// A partial write says so on its first line, and what it left and why (#38922).
const left = plan.manual.length > 0 ? `; ${plan.manual.length} left because of ${leftBecause(plan)}, listed below` : '';
console.log(chalk.bold(
` Wrote ${plan.written.length} of ${appliedCount} mechanical change(s) into ${chainFiles.length} file(s)${left}:`,
));
for (const r of chainFiles) {
console.log(` ${chalk.white(r.file)}`);
for (const w of plan.written.filter((x) => x.file === r.file)) {
console.log(` ${chalk.dim(`:${w.line}`)} ${w.application.path} ${chalk.dim(`(${w.application.conversionId})`)}`);
}
}
console.log('');
}
if (plan.range) printRangeOutcome(plan.range);
printPairs(plan);
if (plan.manual.length > 0) {
console.log(chalk.bold(chalk.yellow(` ${plan.manual.length} mechanical change(s) left for you to apply by hand:`)));
for (const m of plan.manual) {
const a = m.application;
console.log(` ${chalk.yellow('•')} ${a.path}: ${a.from} → ${a.to} ${chalk.dim(`(${a.conversionId})`)}`);
// The path names its items by position; the line names them as the author does.
if (m.items) console.log(chalk.dim(` where ${m.items.map((i) => `${i.at} is \`${i.name}\``).join(', ')}`));
console.log(chalk.dim(` not written [${m.refusal.kind}]: ${m.refusal.reason}`));
if (m.found) {
console.log(chalk.dim(
` found at ${m.found.file}:${m.found.line} — the one project literal whose content matches this site; `
+ 'edit it there (matched by content, not traced, so --write leaves it)',
));
}
}
console.log('');
}
if (plan.unexplained.length > 0) {
printWarning(
`${plan.unexplained.length} change(s) in the migrated stack are named by no applied entry and were not `
+ `written: ${plan.unexplained.join(', ')}`,
);
}
if (files > 0) {
// The re-check holds the range as it holds the chain's edits (#22219).
const range = plan.range?.status === 'written'
? ` The declared protocol range now admits protocol ${plan.range.rewrite.major}.`
: '';
printSuccess(
`Re-ran the chain over the written sources: ${plan.manual.length === 0
? 'no mechanical change remains.'
: `only the ${plan.manual.length} change(s) left above remain.`}${range}`,
);
console.log('');
}
}
/**
* Group ⑤: with `--write`, what it wrote; without it, the range edit it would
* make (#22219). A range the run left alone says so either way.
*/
function printWriteGroup(report: MigrationReport, appliedCount: number): void {
if (report.range?.kind === 'behind-from') printRangeLeft(report.range, report.result.fromMajor);
if (report.write) printWriteOutcome(report.write, appliedCount);
else if (report.range?.kind === 'rewrite') printRangeDryRun(report.range.rewrite);
}
/**
* One site the protocol-19 form move left for the author (ADR-0159 D7 / D8,
* #37112): a form left in place, a moved form the author still owes an edit,
* or a translation key the move does not carry.
*/
export interface FormMoveSite {
/** The conversion whose site this is. */
readonly conversionId: string;
/** Where the site is, in the shape the author wrote it (`views[0].formViews.web`). */
readonly path: string;
/** What stands there (a form's name, a serialized value). */
readonly from: string;
/** What the author decides, and how. */
readonly reason: string;
}
const FORM_MOVE_ID = 'view-forms-to-form-items';
const FORM_TAILS_ID = 'translation-view-form-tails-to-forms';
const FORM_MOVE_MAJOR = 19;
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/**
* Every `objects.OBJECT._views.KEY.label` / `.description` of a translation
* bundle whose `OBJECT.KEY` names a form the move carried (D8: the two keys
* stay, because a list carries them too; the author re-authors them under
* `forms`).
*/
function viewCopyOfMovedForms(stack: Record<string, unknown>, moved: ReadonlySet<string>, prefix: string): FormMoveSite[] {
const out: FormMoveSite[] = [];
const translations = stack.translations;
if (!Array.isArray(translations) || moved.size === 0) return out;
const readData = (data: Record<string, unknown>, path: string) => {
if (!isPlainRecord(data.objects)) return;
for (const [object, objectData] of Object.entries(data.objects)) {
if (!isPlainRecord(objectData) || !isPlainRecord(objectData._views)) continue;
for (const [key, entry] of Object.entries(objectData._views)) {
if (!isPlainRecord(entry)) continue;
const name = key.startsWith(`${object}.`) ? key : `${object}.${key}`;
if (!moved.has(name)) continue;
for (const copy of ['label', 'description'] as const) {
if (entry[copy] === undefined) continue;
out.push({
conversionId: FORM_TAILS_ID,
path: `${path}.objects.${object}._views.${key}.${copy}`,
from: JSON.stringify(entry[copy]),
reason:
`'${name}' is a \`form\` item now, and \`_views.${key}.${copy}\` is a view's key, which no form reads `
+ `(ADR-0159 D8). Re-author it as \`forms['${name}'].${copy}\`, then delete it here.`,
});
}
}
}
};
translations.forEach((entry, i) => {
if (!isPlainRecord(entry)) return;
const path = `${prefix}translations[${i}]`;
readData(entry, path);
for (const [locale, data] of Object.entries(entry)) {
if (isPlainRecord(data) && isPlainRecord(data.objects)) readData(data, `${path}.${locale}`);
}
});
return out;
}
/**
* The per-site edits the protocol-19 form move leaves for the author (ADR-0159
* D7 / D8, #37112) — the lines the semantic entries
* `view-forms-move-to-form-type` and `translation-form-tails-move-to-forms`
* promise.
*
* The chain carries a conversion's applied edits, never its TODO channel, so
* this asks the two conversions directly, over the stack as it enters the
* major-19 hop (the chain replayed up to 18 first, where `--from` is below
* it), and over each `packages[].manifest` body of an assembled stack the same
* way: a form left in place (an unreadable body, a disagreeing binding, a
* non-object binding, a key a `form` item does not carry, a name `forms[]`
* holds), a moved pair on one public address, a moved `overrides` holder for
* `os validate`, a translation tail left in place, and a `_views` label or
* description of a moved form. Empty when the run does not cross into 19.
*/
export function formMoveSites(stack: Record<string, unknown>, fromMajor: number, toMajor: number): FormMoveSite[] {
if (!(fromMajor < FORM_MOVE_MAJOR && toMajor >= FORM_MOVE_MAJOR)) return [];
const move = ALL_CONVERSIONS.find((c) => c.id === FORM_MOVE_ID);
const tails = ALL_CONVERSIONS.find((c) => c.id === FORM_TAILS_ID);
if (!move || !tails) return [];
const bodies: Array<{ prefix: string; body: Record<string, unknown> }> = [{ prefix: '', body: stack }];
if (Array.isArray(stack.packages)) {
stack.packages.forEach((entry, i) => {
if (isPlainRecord(entry) && isPlainRecord(entry.manifest)) bodies.push({ prefix: `packages[${i}].manifest.`, body: entry.manifest });
});
}
const sites: FormMoveSite[] = [];
for (const { prefix, body } of bodies) {
const entering = fromMajor < FORM_MOVE_MAJOR - 1
? applyMetaMigrations(body, fromMajor, FORM_MOVE_MAJOR - 1).stack
: body;
const moved = new Set<string>();