{"version":3,"file":"upgrade-migration.mjs","names":[],"sources":["../../../src/services/scaffold/upgrade-migration.ts"],"sourcesContent":["import { existsSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { MISSING_CONFIG_MESSAGE, readAuthoredConfigInput } from \"../../config\";\nimport type { PhaseTiming, UpgradeOptions, UpgradeResult } from \"../../contract\";\nimport { formatUnknownError } from \"../../utils/errors\";\nimport { saveBosConfig } from \"../../utils/save-config\";\nimport { timePhase } from \"../../utils/timing\";\nimport { readNodeModulesVersion } from \"../framework-version\";\nimport { openResolution } from \"../resolution/session\";\nimport { syncResolvedSharedDeps } from \"../workspace/shared-deps\";\nimport { runTypesGen } from \"./init\";\nimport { syncTemplate } from \"./sync\";\nimport {\n  FRAMEWORK_PACKAGES,\n  installDriftError,\n  migrateChildRootPackageJson,\n} from \"./upgrade-packages\";\nimport {\n  detectOwnedDivergentKeys,\n  type OwnedRealignment,\n  realignOwnedRemotes,\n} from \"./upgrade-realign\";\nimport { buildChangelogUrl, type ExtendedRootSource } from \"./upgrade-source\";\n\n/** Migration-phase scope (ADR 0032): template reconciliation rides the\n * framework version delta — with no delta nothing touches the tree. */\nexport interface MigrationScope {\n  /** true when the upgrade moves framework versions (or `--from` says so) */\n  versionDelta: boolean;\n}\n\n/**\n * Surgical authored-release edit on the authored config's source: rewrites\n * only the `release:` line (or a legacy `platform:` line — the codemod form),\n * or inserts one after `extends`, leaving every other byte — formatting,\n * comments, attachments — untouched. Throws with the version to set by hand\n * when no safe anchor exists; the authored file is never re-serialized.\n */\nexport function stampRelease(source: string, version: string): string {\n  const releaseLineRe =\n    /^([ \\t]*)(release|platform|\"release\"|\"platform\")[ \\t]*:[ \\t]*\"([^\"]*)\"(,?)[ \\t]*$/;\n  const extendsLineRe = /^([ \\t]*)(extends|\"extends\")[ \\t]*:[ \\t]*(\"[^\"]*\")(,?)[ \\t]*$/;\n  const lines = source.split(\"\\n\");\n\n  for (let i = 0; i < lines.length; i++) {\n    const match = lines[i].match(releaseLineRe);\n    if (match) {\n      lines[i] = `${match[1]}release: \"${version}\"${match[4]}`;\n      return lines.join(\"\\n\");\n    }\n  }\n\n  for (let i = 0; i < lines.length; i++) {\n    const match = lines[i].match(extendsLineRe);\n    if (match) {\n      lines[i] = `${match[1]}${match[2]}: ${match[3]},`;\n      lines.splice(i + 1, 0, `${match[1]}release: \"${version}\",`);\n      return lines.join(\"\\n\");\n    }\n  }\n\n  throw new Error(\n    `could not stamp the authored release surgically — no release or extends ` +\n      `property found in the authored config; set release: \"${version}\" ` +\n      `in bos.app.ts manually and re-run`,\n  );\n}\n\n/**\n * Stamp the resolved framework version into the authored config's `release`\n * field (ADR 0034). Runs at the top of the migration phase on both the inline\n * and re-exec'd paths, so everyday resolution (sync, init, runtime) always\n * freezes to the release this upgrade just landed from — whether or not the\n * package versions actually moved. A legacy `platform:` line is the codemod\n * form: the same stamp rewrites it to `release:`. The authored `bos.app.ts`\n * is edited surgically (the field line only) — never re-serialized.\n */\nexport async function applyRelease(\n  projectDir: string,\n  parentSource: ExtendedRootSource,\n): Promise<string | undefined> {\n  const version = parentSource.platform.manifest.frameworkVersion;\n  const config = (await readAuthoredConfigInput(projectDir)) as Record<string, unknown> | null;\n  if (!config) return undefined;\n  if (config.release === version && config.platform === undefined) return undefined;\n\n  const appConfigPath = join(projectDir, \"bos.app.ts\");\n  if (existsSync(appConfigPath)) {\n    const source = readFileSync(appConfigPath, \"utf-8\");\n    writeFileSync(appConfigPath, stampRelease(source, version));\n    return \"bos.app.ts\";\n  }\n\n  delete config.platform;\n  config.release = version;\n  await saveBosConfig(projectDir, config);\n  return \"bos.config.json\";\n}\n\n/**\n * The re-exec'd migration child runs `--json`, so its stdout is the structured\n * result — a failed run carries the real failure in its `error` field, which\n * raw stderr/stdout concatenation hides behind `[CLI] [object Object]`.\n */\nexport function describeMigrationFailure(\n  stdout: string | undefined,\n  stderr: string | undefined,\n): string {\n  if (stdout) {\n    try {\n      const parsed = JSON.parse(stdout) as { error?: unknown };\n      if (parsed && typeof parsed === \"object\" && parsed.error != null) {\n        return formatUnknownError(parsed.error);\n      }\n    } catch {\n      // not JSON — fall through to the raw streams\n    }\n  }\n  const raw = (stderr || stdout || \"\").trim();\n  return raw.length > 0 ? raw : \"Unknown error\";\n}\n\nexport async function runMigrationPhase(\n  projectDir: string,\n  options: UpgradeOptions,\n  parentSource: ExtendedRootSource,\n  scope: MigrationScope,\n): Promise<UpgradeResult> {\n  const timings: PhaseTiming[] = [];\n\n  // The pre-rename manifest cache location is not read by this code — a\n  // stale file beside the live one only invites confusion (ticket 08).\n  const legacyCache = join(projectDir, \".bos\", \"platform-manifest.json\");\n  if (existsSync(legacyCache)) rmSync(legacyCache, { force: true });\n\n  // The catalog-preferring resolution would read the specifier back as the\n  // installed version — exactly the blind spot this gate exists for. Read the\n  // real node_modules install.\n  const drift = installDriftError(\n    Object.fromEntries(\n      FRAMEWORK_PACKAGES.map((name) => [name, readNodeModulesVersion(projectDir, name)]),\n    ),\n    Object.fromEntries(FRAMEWORK_PACKAGES.map((name) => [name, parentSource.catalog[name]])),\n  );\n  if (drift) throw new Error(drift);\n\n  const releaseStamped = await timePhase(timings, \"stamp release\", () =>\n    applyRelease(projectDir, parentSource),\n  );\n\n  const migratedRootPackageJson = await timePhase(timings, \"migrate root package\", () =>\n    migrateChildRootPackageJson(projectDir),\n  );\n\n  let syncResult: UpgradeResult[\"sync\"];\n  // Same-version upgrades never touch framework-owned files (ADR 0032).\n  // `--no-sync` opts out of a version-change sync.\n  if (scope.versionDelta && !options.noSync) {\n    syncResult = await timePhase(timings, \"sync template\", () =>\n      syncTemplate(projectDir, {\n        dryRun: false,\n        noInstall: true,\n        force: options.force,\n        // the upgrade already resolved the release — one resolution for the\n        // whole train; sync never re-derives (and never reads the authored\n        // release it exists to move)\n        resolvedRelease: parentSource.platform,\n      }),\n    );\n    if (syncResult?.status === \"conflicted\") {\n      throw new Error(syncResult.error ?? \"Template sync hit unresolvable local conflicts\");\n    }\n  }\n\n  await timePhase(timings, \"sync shared deps\", async () => {\n    const configSession = await openResolution({ cwd: projectDir });\n    if (!configSession?.config) {\n      throw new Error(`${MISSING_CONFIG_MESSAGE} in current directory`);\n    }\n\n    return syncResolvedSharedDeps({\n      configDir: projectDir,\n      hostMode: \"local\",\n      bosConfig: configSession.config,\n    });\n  });\n\n  if (!options.noInstall) {\n    await timePhase(timings, \"generate types\", () => runTypesGen(projectDir));\n  }\n\n  // Owned-slot realignment: with a framework version delta, owned slots built\n  // against the old chain keep stale shared-singleton pins — republish them\n  // from the new package so the tree the upgrade leaves behind composes\n  // coherently (the plane audit on the next dev boot confirms it).\n  let realignment: OwnedRealignment | undefined;\n  if (scope.versionDelta && !options.noRealign) {\n    realignment = await timePhase(timings, \"realign owned slots\", async () => {\n      const session = await openResolution({ cwd: projectDir });\n      if (!session?.config) return undefined;\n      const { keys, lines } = await detectOwnedDivergentKeys(session);\n      if (keys.length === 0) return { keys: [], realigned: [], failures: [] };\n      for (const line of lines) {\n        if (line.kind === \"owned\") console.error(`  [realign] ${line.message}`);\n      }\n      return await realignOwnedRemotes(projectDir, keys, console.error);\n    });\n  }\n\n  const migratedFiles = [\n    ...(releaseStamped ? [releaseStamped] : []),\n    ...(migratedRootPackageJson ? [\"package.json\"] : []),\n  ];\n\n  const mainPkg = parentSource.catalog[\"everything-dev\"];\n  const changelogUrl = mainPkg\n    ? buildChangelogUrl(undefined, mainPkg, parentSource.repository)\n    : undefined;\n\n  return {\n    status: \"upgraded\",\n    packages: [],\n    sync: syncResult,\n    migrated: migratedFiles.length > 0 ? migratedFiles : undefined,\n    ...(realignment ? { realignment } : {}),\n    timings,\n    changelogUrl,\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,aAAa,QAAgB,SAAyB;CACpE,MAAM,gBACJ;CACF,MAAM,gBAAgB;CACtB,MAAM,QAAQ,OAAO,MAAM,IAAI;CAE/B,KAAK,IAAI,IAAI,GAAG,IAAI,MA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