|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { Args, Command, Flags } from '@oclif/core'; |
| 4 | +import { writeFileSync } from 'node:fs'; |
| 5 | +import { resolve } from 'node:path'; |
| 6 | +import chalk from 'chalk'; |
| 7 | +import { |
| 8 | + ObjectStackDefinitionSchema, |
| 9 | + applyMetaMigrations, |
| 10 | + composeSpecChanges, |
| 11 | + normalizeStackInput, |
| 12 | + MigrationFloorError, |
| 13 | +} from '@objectstack/spec'; |
| 14 | +import { PROTOCOL_MAJOR, PROTOCOL_VERSION } from '@objectstack/spec/kernel'; |
| 15 | +import { loadConfig } from '../../utils/config.js'; |
| 16 | +import { |
| 17 | + printHeader, |
| 18 | + printSuccess, |
| 19 | + printWarning, |
| 20 | + printError, |
| 21 | + printInfo, |
| 22 | + printStep, |
| 23 | + createTimer, |
| 24 | +} from '../../utils/format.js'; |
| 25 | + |
| 26 | +/** |
| 27 | + * `os migrate meta --from N` — replay the ADR-0087 D3 migration chain. |
| 28 | + * |
| 29 | + * Composes the per-major steps N+1 → … → current and applies each major's |
| 30 | + * mechanical transforms (the graduated D2 conversions) to the loaded stack in |
| 31 | + * one run — cross-major is the designed-for case, not an edge. It reports a |
| 32 | + * generated, schema-validated diff (the mechanical rewrites) plus the structured |
| 33 | + * TODOs for the semantic changes the chain cannot apply, so the consumer agent |
| 34 | + * reviews a provably-valid change instead of hand-porting from prose. |
| 35 | + * |
| 36 | + * The command does not silently rewrite TS config source (that AST rewrite is |
| 37 | + * unsafe and lossy); `--out` writes the canonicalized stack as a JSON snapshot |
| 38 | + * the agent can diff and adopt. `--step` prints a per-hop checkpoint so a failure |
| 39 | + * can be bisected to the exact major. |
| 40 | + */ |
| 41 | +export default class MigrateMeta extends Command { |
| 42 | + static override description = |
| 43 | + 'Replay the metadata protocol migration chain from a past major to current (ADR-0087 D3).'; |
| 44 | + |
| 45 | + static override examples = [ |
| 46 | + '$ os migrate meta --from 10', |
| 47 | + '$ os migrate meta --from 10 --step', |
| 48 | + '$ os migrate meta --from 11 --to 12 --json', |
| 49 | + '$ os migrate meta --from 10 --out migrated.stack.json', |
| 50 | + ]; |
| 51 | + |
| 52 | + static override args = { |
| 53 | + config: Args.string({ description: 'Path to the stack config (defaults to auto-detected).' }), |
| 54 | + }; |
| 55 | + |
| 56 | + static override flags = { |
| 57 | + from: Flags.integer({ |
| 58 | + description: 'The protocol major the metadata was authored against.', |
| 59 | + required: true, |
| 60 | + }), |
| 61 | + to: Flags.integer({ |
| 62 | + description: `Target protocol major (defaults to this runtime's, ${PROTOCOL_MAJOR}).`, |
| 63 | + }), |
| 64 | + step: Flags.boolean({ |
| 65 | + description: 'Print a per-hop checkpoint (for per-major verify / bisection).', |
| 66 | + default: false, |
| 67 | + }), |
| 68 | + out: Flags.string({ description: 'Write the migrated stack as a JSON snapshot to this path.' }), |
| 69 | + json: Flags.boolean({ description: 'Output the machine-readable migration result as JSON.' }), |
| 70 | + }; |
| 71 | + |
| 72 | + async run(): Promise<void> { |
| 73 | + const { args, flags } = await this.parse(MigrateMeta); |
| 74 | + const timer = createTimer(); |
| 75 | + const toMajor = flags.to ?? PROTOCOL_MAJOR; |
| 76 | + |
| 77 | + if (!flags.json) printHeader('Migrate · meta'); |
| 78 | + |
| 79 | + try { |
| 80 | + if (!flags.json) printStep('Loading configuration…'); |
| 81 | + const { config, absolutePath } = await loadConfig(args.config); |
| 82 | + |
| 83 | + // Map→array normalization ONLY (convert:false): the chain must replay the |
| 84 | + // conversions itself against the raw authored source so each rewrite is |
| 85 | + // attributed to a chain hop, not silently pre-applied by the load-time |
| 86 | + // D2 pass. Running the D2 pass here would leave the chain's diff empty. |
| 87 | + const normalized = normalizeStackInput(config as Record<string, unknown>, { convert: false }); |
| 88 | + |
| 89 | + if (!flags.json) printStep(`Replaying chain: protocol ${flags.from} → ${toMajor}…`); |
| 90 | + const result = applyMetaMigrations(normalized, flags.from, toMajor); |
| 91 | + |
| 92 | + // Prove the migrated stack is schema-valid — the "generated, provably valid |
| 93 | + // diff" the consumer agent reviews (ADR-0087 D3/D5). |
| 94 | + const parsed = ObjectStackDefinitionSchema.safeParse(result.stack); |
| 95 | + const specChanges = composeSpecChanges(flags.from, toMajor); |
| 96 | + |
| 97 | + if (flags.json) { |
| 98 | + console.log( |
| 99 | + JSON.stringify( |
| 100 | + { |
| 101 | + from: result.fromMajor, |
| 102 | + to: result.toMajor, |
| 103 | + runtime: PROTOCOL_VERSION, |
| 104 | + applied: result.applied, |
| 105 | + todos: result.todos, |
| 106 | + hops: flags.step |
| 107 | + ? result.hops.map((h) => ({ |
| 108 | + toMajor: h.toMajor, |
| 109 | + rationale: h.rationale, |
| 110 | + applied: h.applied, |
| 111 | + todos: h.todos, |
| 112 | + })) |
| 113 | + : undefined, |
| 114 | + specChanges, |
| 115 | + schemaValid: parsed.success, |
| 116 | + duration: timer.elapsed(), |
| 117 | + }, |
| 118 | + null, |
| 119 | + 2, |
| 120 | + ), |
| 121 | + ); |
| 122 | + if (flags.out) writeFileSync(resolve(flags.out), JSON.stringify(result.stack, null, 2)); |
| 123 | + return; |
| 124 | + } |
| 125 | + |
| 126 | + printInfo(`Config: ${chalk.white(absolutePath)}`); |
| 127 | + printInfo(`Chain: protocol ${flags.from} → ${toMajor} (runtime ${PROTOCOL_VERSION})`); |
| 128 | + console.log(''); |
| 129 | + |
| 130 | + if (result.applied.length === 0 && result.todos.length === 0) { |
| 131 | + printSuccess('Nothing to migrate — the metadata is already canonical for this range.'); |
| 132 | + return; |
| 133 | + } |
| 134 | + |
| 135 | + // Mechanical rewrites (auto-applied). |
| 136 | + if (result.applied.length > 0) { |
| 137 | + console.log(chalk.bold(` Applied ${result.applied.length} mechanical change(s):`)); |
| 138 | + for (const a of result.applied) { |
| 139 | + console.log(` • ${a.path}: ${chalk.red(a.from)} → ${chalk.green(a.to)} ${chalk.dim(`(${a.conversionId})`)}`); |
| 140 | + } |
| 141 | + console.log(''); |
| 142 | + } |
| 143 | + |
| 144 | + // Per-hop checkpoints. |
| 145 | + if (flags.step) { |
| 146 | + for (const hop of result.hops) { |
| 147 | + console.log(chalk.bold(` ── protocol ${hop.toMajor} ──`)); |
| 148 | + console.log(chalk.dim(` ${hop.rationale}`)); |
| 149 | + console.log(chalk.dim(` ${hop.applied.length} mechanical, ${hop.todos.length} manual`)); |
| 150 | + } |
| 151 | + console.log(''); |
| 152 | + } |
| 153 | + |
| 154 | + // Semantic TODOs (delegated to the agent — never auto-applied). |
| 155 | + if (result.todos.length > 0) { |
| 156 | + console.log(chalk.bold(chalk.yellow(` ${result.todos.length} manual change(s) require your judgment:`))); |
| 157 | + for (const t of result.todos) { |
| 158 | + console.log(` ${chalk.yellow('⚠')} [protocol ${t.toMajor}] ${t.surface} → ${t.replacement}`); |
| 159 | + console.log(chalk.dim(` why: ${t.reason}`)); |
| 160 | + console.log(chalk.dim(` verify: ${t.acceptanceCriteria}`)); |
| 161 | + } |
| 162 | + console.log(''); |
| 163 | + } |
| 164 | + |
| 165 | + if (flags.out) { |
| 166 | + writeFileSync(resolve(flags.out), JSON.stringify(result.stack, null, 2)); |
| 167 | + printInfo(`Wrote migrated stack snapshot → ${chalk.white(resolve(flags.out))}`); |
| 168 | + } |
| 169 | + |
| 170 | + if (parsed.success) { |
| 171 | + printSuccess(`Migrated stack is schema-valid ${chalk.dim(`(${timer.display()})`)}`); |
| 172 | + } else { |
| 173 | + printWarning( |
| 174 | + 'Migrated stack does not yet pass schema validation — resolve the manual changes above, ' + |
| 175 | + 'then run `os validate`.', |
| 176 | + ); |
| 177 | + } |
| 178 | + console.log(''); |
| 179 | + } catch (error: any) { |
| 180 | + if (error instanceof MigrationFloorError) { |
| 181 | + if (flags.json) { |
| 182 | + console.log(JSON.stringify({ error: 'unsupported_from_major', message: error.message })); |
| 183 | + this.exit(1); |
| 184 | + } |
| 185 | + printError(error.message); |
| 186 | + this.exit(1); |
| 187 | + return; |
| 188 | + } |
| 189 | + if (flags.json) { |
| 190 | + console.log(JSON.stringify({ error: error.message })); |
| 191 | + this.exit(1); |
| 192 | + } |
| 193 | + printError(error.message || String(error)); |
| 194 | + this.exit(1); |
| 195 | + } |
| 196 | + } |
| 197 | +} |
0 commit comments