@prisma-next/cli 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +1 -1
  2. package/dist/{cli-errors-CF60g2cG.mjs → cli-errors-Djtz98Vm.mjs} +3 -3
  3. package/dist/cli-errors-Djtz98Vm.mjs.map +1 -0
  4. package/dist/cli.mjs +151 -12
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/{client-Brv4qlfB.mjs → client-oXO2WCPD.mjs} +6 -5
  7. package/dist/client-oXO2WCPD.mjs.map +1 -0
  8. package/dist/{command-helpers-D3vL5yi8.mjs → command-helpers-BSb0tRC8.mjs} +104 -10
  9. package/dist/command-helpers-BSb0tRC8.mjs.map +1 -0
  10. package/dist/commands/contract-emit.mjs +1 -1
  11. package/dist/commands/contract-infer.mjs +1 -1
  12. package/dist/commands/db-init.d.mts.map +1 -1
  13. package/dist/commands/db-init.mjs +19 -20
  14. package/dist/commands/db-init.mjs.map +1 -1
  15. package/dist/commands/db-schema.mjs +6 -10
  16. package/dist/commands/db-schema.mjs.map +1 -1
  17. package/dist/commands/db-sign.mjs +7 -11
  18. package/dist/commands/db-sign.mjs.map +1 -1
  19. package/dist/commands/db-update.d.mts.map +1 -1
  20. package/dist/commands/db-update.mjs +16 -17
  21. package/dist/commands/db-update.mjs.map +1 -1
  22. package/dist/commands/db-verify.mjs +1 -1
  23. package/dist/commands/migrate.d.mts +1 -1
  24. package/dist/commands/migrate.mjs +7 -11
  25. package/dist/commands/migrate.mjs.map +1 -1
  26. package/dist/commands/migration-check.mjs +4 -7
  27. package/dist/commands/migration-check.mjs.map +1 -1
  28. package/dist/commands/migration-graph.d.mts +1 -1
  29. package/dist/commands/migration-graph.mjs +6 -10
  30. package/dist/commands/migration-graph.mjs.map +1 -1
  31. package/dist/commands/migration-list.mjs +5 -9
  32. package/dist/commands/migration-list.mjs.map +1 -1
  33. package/dist/commands/migration-log.d.mts.map +1 -1
  34. package/dist/commands/migration-log.mjs +7 -10
  35. package/dist/commands/migration-log.mjs.map +1 -1
  36. package/dist/commands/migration-new.mjs +6 -10
  37. package/dist/commands/migration-new.mjs.map +1 -1
  38. package/dist/commands/migration-plan.d.mts +1 -1
  39. package/dist/commands/migration-plan.mjs +1 -1
  40. package/dist/commands/migration-show.d.mts +1 -1
  41. package/dist/commands/migration-show.mjs +8 -12
  42. package/dist/commands/migration-show.mjs.map +1 -1
  43. package/dist/commands/migration-status.d.mts +1 -1
  44. package/dist/commands/migration-status.d.mts.map +1 -1
  45. package/dist/commands/migration-status.mjs +36 -14
  46. package/dist/commands/migration-status.mjs.map +1 -1
  47. package/dist/commands/ref.d.mts +1 -1
  48. package/dist/commands/ref.mjs +9 -19
  49. package/dist/commands/ref.mjs.map +1 -1
  50. package/dist/{contract-emit-iynA3BCA.mjs → contract-emit-bcrpT-wD.mjs} +3 -3
  51. package/dist/{contract-emit-iynA3BCA.mjs.map → contract-emit-bcrpT-wD.mjs.map} +1 -1
  52. package/dist/{contract-emit-C3STUIBg.mjs → contract-emit-r4y8Zhf1.mjs} +7 -12
  53. package/dist/contract-emit-r4y8Zhf1.mjs.map +1 -0
  54. package/dist/{contract-infer-Cnj8G1E2.mjs → contract-infer-BmySmqVT.mjs} +8 -13
  55. package/dist/contract-infer-BmySmqVT.mjs.map +1 -0
  56. package/dist/{contract-space-aggregate-loader-pAc8CDfY.mjs → contract-space-aggregate-loader-BmNQwlws.mjs} +2 -2
  57. package/dist/{contract-space-aggregate-loader-pAc8CDfY.mjs.map → contract-space-aggregate-loader-BmNQwlws.mjs.map} +1 -1
  58. package/dist/{db-verify-D7cyH_zz.mjs → db-verify-BClPs3ph.mjs} +9 -13
  59. package/dist/db-verify-BClPs3ph.mjs.map +1 -0
  60. package/dist/exports/control-api.d.mts +1 -1
  61. package/dist/exports/control-api.mjs +2 -2
  62. package/dist/exports/index.mjs +2 -2
  63. package/dist/exports/init-output.mjs +1 -1
  64. package/dist/{framework-components-xFLFpZUO.mjs → framework-components-65gOHkHB.mjs} +2 -2
  65. package/dist/{framework-components-xFLFpZUO.mjs.map → framework-components-65gOHkHB.mjs.map} +1 -1
  66. package/dist/{global-flags-DGmw6Kqg.d.mts → global-flags-CdE7M0d9.d.mts} +4 -1
  67. package/dist/global-flags-CdE7M0d9.d.mts.map +1 -0
  68. package/dist/{graph-render-eJDcLWny.mjs → graph-render-DJVv0_uf.mjs} +1 -1
  69. package/dist/{graph-render-eJDcLWny.mjs.map → graph-render-DJVv0_uf.mjs.map} +1 -1
  70. package/dist/{init-eh2z5Tl6.mjs → init-BCJZPWE1.mjs} +547 -399
  71. package/dist/init-BCJZPWE1.mjs.map +1 -0
  72. package/dist/{inspect-live-schema-CWLK_lgs.mjs → inspect-live-schema-DSRbFoOL.mjs} +4 -4
  73. package/dist/{inspect-live-schema-CWLK_lgs.mjs.map → inspect-live-schema-DSRbFoOL.mjs.map} +1 -1
  74. package/dist/{migration-command-scaffold-CmXXC1UZ.mjs → migration-command-scaffold-Bzd9La5c.mjs} +4 -4
  75. package/dist/{migration-command-scaffold-CmXXC1UZ.mjs.map → migration-command-scaffold-Bzd9La5c.mjs.map} +1 -1
  76. package/dist/{migration-plan-CHyUlBV0.mjs → migration-plan-CFwqw3Gk.mjs} +8 -12
  77. package/dist/migration-plan-CFwqw3Gk.mjs.map +1 -0
  78. package/dist/{migration-types-D2FW63pr.d.mts → migration-types-BXWvz12q.d.mts} +1 -1
  79. package/dist/{migration-types-D2FW63pr.d.mts.map → migration-types-BXWvz12q.d.mts.map} +1 -1
  80. package/dist/{migrations-DyUf5lTt.mjs → migrations-CwZMa1Ck.mjs} +2 -2
  81. package/dist/{migrations-DyUf5lTt.mjs.map → migrations-CwZMa1Ck.mjs.map} +1 -1
  82. package/dist/{output-B60Gw5fu.mjs → output-BlsrGMEF.mjs} +1 -1
  83. package/dist/{output-B60Gw5fu.mjs.map → output-BlsrGMEF.mjs.map} +1 -1
  84. package/dist/quick-reference-mongo.md +1 -1
  85. package/dist/quick-reference-postgres.md +1 -1
  86. package/dist/readme-mongo.md +35 -0
  87. package/dist/readme-postgres.md +34 -0
  88. package/dist/{terminal-ui-XtOQsqe9.mjs → terminal-ui-BiB_8KNo.mjs} +131 -24
  89. package/dist/terminal-ui-BiB_8KNo.mjs.map +1 -0
  90. package/dist/{types-0aS865QN.d.mts → types--CqjMdk0.d.mts} +2 -2
  91. package/dist/{types-0aS865QN.d.mts.map → types--CqjMdk0.d.mts.map} +1 -1
  92. package/dist/{verify-D7ypCCe6.mjs → verify-Bom75OYI.mjs} +2 -2
  93. package/dist/{verify-D7ypCCe6.mjs.map → verify-Bom75OYI.mjs.map} +1 -1
  94. package/package.json +19 -17
  95. package/src/cli.ts +42 -0
  96. package/src/commands/contract-emit.ts +4 -4
  97. package/src/commands/contract-infer.ts +6 -6
  98. package/src/commands/db-init.ts +13 -5
  99. package/src/commands/db-schema.ts +4 -4
  100. package/src/commands/db-sign.ts +4 -4
  101. package/src/commands/db-update.ts +13 -5
  102. package/src/commands/db-verify.ts +5 -5
  103. package/src/commands/init/detect-package-manager.ts +15 -0
  104. package/src/commands/init/errors.ts +33 -2
  105. package/src/commands/init/index.ts +13 -5
  106. package/src/commands/init/init.ts +61 -32
  107. package/src/commands/init/inputs.ts +82 -5
  108. package/src/commands/init/output.ts +1 -1
  109. package/src/commands/init/{agent-skill-install.ts → skill-install.ts} +42 -31
  110. package/src/commands/init/templates/code-templates.ts +22 -22
  111. package/src/commands/init/templates/env.ts +8 -1
  112. package/src/commands/init/templates/quick-reference-mongo.md +1 -1
  113. package/src/commands/init/templates/quick-reference-postgres.md +1 -1
  114. package/src/commands/init/templates/readme-mongo.md +35 -0
  115. package/src/commands/init/templates/readme-postgres.md +34 -0
  116. package/src/commands/init/templates/readme.ts +62 -0
  117. package/src/commands/migrate.ts +4 -7
  118. package/src/commands/migration-check.ts +4 -4
  119. package/src/commands/migration-graph.ts +4 -4
  120. package/src/commands/migration-list.ts +4 -4
  121. package/src/commands/migration-log.ts +6 -5
  122. package/src/commands/migration-new.ts +4 -4
  123. package/src/commands/migration-plan.ts +4 -4
  124. package/src/commands/migration-show.ts +4 -4
  125. package/src/commands/migration-status.ts +49 -6
  126. package/src/commands/ref.ts +8 -8
  127. package/src/control-api/operations/apply-aggregate.ts +1 -0
  128. package/src/utils/cli-errors.ts +4 -0
  129. package/src/utils/command-helpers.ts +6 -2
  130. package/src/utils/global-flags.ts +105 -16
  131. package/src/utils/is-ci.ts +18 -0
  132. package/src/utils/telemetry.ts +141 -0
  133. package/src/utils/terminal-ui.ts +44 -23
  134. package/dist/cli-errors-CF60g2cG.mjs.map +0 -1
  135. package/dist/client-Brv4qlfB.mjs.map +0 -1
  136. package/dist/command-helpers-D3vL5yi8.mjs.map +0 -1
  137. package/dist/contract-emit-C3STUIBg.mjs.map +0 -1
  138. package/dist/contract-infer-Cnj8G1E2.mjs.map +0 -1
  139. package/dist/db-verify-D7cyH_zz.mjs.map +0 -1
  140. package/dist/errors-Cw6kyTyV.mjs +0 -56
  141. package/dist/errors-Cw6kyTyV.mjs.map +0 -1
  142. package/dist/global-flags-DGmw6Kqg.d.mts.map +0 -1
  143. package/dist/helpers-eqdN8tH6.mjs +0 -25
  144. package/dist/helpers-eqdN8tH6.mjs.map +0 -1
  145. package/dist/init-eh2z5Tl6.mjs.map +0 -1
  146. package/dist/migration-plan-CHyUlBV0.mjs.map +0 -1
  147. package/dist/result-handler-Bm_6dDYg.mjs +0 -25
  148. package/dist/result-handler-Bm_6dDYg.mjs.map +0 -1
  149. package/dist/terminal-ui-XtOQsqe9.mjs.map +0 -1
  150. /package/dist/{cli-errors-DdcjVLJV.d.mts → cli-errors-Czmx92Zy.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"migration-show.mjs","names":[],"sources":["../../src/commands/migration-show.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport {\n APP_SPACE_ID,\n createControlStack,\n type MigrationPlanOperation,\n type OperationPreview,\n} from '@prisma-next/framework-components/control';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { readMigrationPackage, readMigrationsDir } from '@prisma-next/migration-tools/io';\nimport {\n findLatestMigration,\n reconstructGraph,\n} from '@prisma-next/migration-tools/migration-graph';\nimport type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';\nimport { parseMigrationRef } from '@prisma-next/migration-tools/ref-resolution';\nimport { readRefs } from '@prisma-next/migration-tools/refs';\nimport { spaceMigrationDirectory } from '@prisma-next/migration-tools/spaces';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { isAbsolute, relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport {\n type CliStructuredError,\n errorContractValidationFailed,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n mapMigrationToolsError,\n mapRefResolutionError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n setCommandSeeAlso,\n} from '../utils/command-helpers';\nimport { buildContractSpaceAggregate } from '../utils/contract-space-aggregate-loader';\nimport { formatMigrationShowOutput } from '../utils/formatters/migrations';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationShowOptions extends CommonCommandOptions {\n readonly config?: string;\n}\n\n/**\n * Details of one space's latest (or targeted) migration package.\n */\nexport interface MigrationShowSpacePresent {\n readonly kind: 'present';\n readonly spaceId: string;\n readonly dirName: string;\n readonly dirPath: string;\n readonly from: string | null;\n readonly to: string;\n readonly migrationHash: string;\n readonly createdAt: string;\n readonly operations: readonly {\n readonly id: string;\n readonly label: string;\n readonly operationClass: string;\n }[];\n /**\n * Family-agnostic textual preview of the migration's operations. Always\n * defined; statements is empty for a no-op migration or a family that does\n * not implement the `OperationPreviewCapable` capability.\n */\n readonly preview: OperationPreview;\n readonly summary: string;\n}\n\n/**\n * Placeholder for a loaded contract space that has no on-disk migration\n * package — the extension descriptor declared the space but no migrations\n * directory has been materialised for it yet. Surfaces the space in the\n * response so JSON consumers see every loaded extension instead of having\n * silently-skipped entries.\n */\nexport interface MigrationShowSpaceMissing {\n readonly kind: 'missing';\n readonly spaceId: string;\n readonly summary: string;\n}\n\nexport type MigrationShowSpaceResult = MigrationShowSpacePresent | MigrationShowSpaceMissing;\n\nexport interface MigrationShowResult {\n readonly ok: true;\n /**\n * Per-space results, ordered: app first, then extensions alphabetically\n * (matching the aggregate's canonical ordering).\n */\n readonly spaces: readonly MigrationShowSpaceResult[];\n}\n\nfunction looksLikePath(target: string): boolean {\n return target.includes('/') || target.includes('\\\\');\n}\n\n/**\n * Validate that a path-like `migration show` target resolves inside the app\n * migrations directory. The returned result is always emitted under\n * `aggregate.app.spaceId`, so accepting an extension-space (or otherwise\n * external) path here would silently mislabel the result. Returns the\n * resolved absolute path on success.\n *\n * `pathe.relative` can return an absolute path when the target cannot be\n * expressed relative to the base (e.g. on Windows when `target` is on a\n * different drive than `appMigrationsDir`). That case does not start with\n * `..`, so the absolute-check below is required to reject cross-drive\n * targets rather than mislabeling them as app-space.\n */\nexport function resolveAppTargetPath(\n target: string,\n appMigrationsDir: string,\n appMigrationsRelative: string,\n): Result<string, CliStructuredError> {\n const targetPath = resolve(target);\n const relativeToApp = relative(appMigrationsDir, targetPath);\n const isOutsideAppDir =\n relativeToApp === '' ||\n relativeToApp === '.' ||\n relativeToApp.startsWith('..') ||\n isAbsolute(relativeToApp);\n if (isOutsideAppDir) {\n return notOk(\n errorRuntime('Target must point to an app-space migration', {\n why: `Expected a path under ${appMigrationsRelative}, got ${target}`,\n fix: 'Pass an app-space migration directory or use a hash prefix.',\n }),\n );\n }\n return ok(targetPath);\n}\n\nexport function resolveByHashPrefix(\n packages: readonly OnDiskMigrationPackage[],\n prefix: string,\n): Result<OnDiskMigrationPackage, CliStructuredError> {\n const normalizedPrefix = prefix.startsWith('sha256:') ? prefix : `sha256:${prefix}`;\n const matches = packages.filter((p) => p.metadata.migrationHash.startsWith(normalizedPrefix));\n\n if (matches.length === 1) {\n return ok(matches[0]!);\n }\n\n if (matches.length === 0) {\n return notOk(\n errorRuntime('No migration found matching prefix', {\n why: `No migration has a migrationHash starting with \"${normalizedPrefix}\"`,\n fix: 'Run `prisma-next migration show` (no argument) to see the latest migration, or check the migrations directory for available packages.',\n }),\n );\n }\n\n const candidates = matches.map((p) => ` ${p.dirName} ${p.metadata.migrationHash}`).join('\\n');\n return notOk(\n errorRuntime('Ambiguous hash prefix', {\n why: `Multiple migrations match prefix \"${normalizedPrefix}\":\\n${candidates}`,\n fix: 'Provide a longer prefix to uniquely identify the migration.',\n }),\n );\n}\n\n/**\n * Resolve the latest migration from a space directory.\n *\n * Returns `ok(null)` only when the directory is empty or absent (ENOENT is\n * absorbed by `readMigrationsDir`). If `readMigrationsDir` returned packages\n * but `findLatestMigration` cannot pick a leaf, the on-disk history is\n * corrupt — return a runtime error rather than collapsing it to a `missing`\n * placeholder, which would hide the corruption from the caller.\n */\nexport async function resolveLatestFromDir(\n spaceDir: string,\n): Promise<Result<OnDiskMigrationPackage | null, CliStructuredError>> {\n try {\n const allPackages = await readMigrationsDir(spaceDir);\n if (allPackages.length === 0) return ok(null);\n const graph = reconstructGraph(allPackages);\n const latestMigration = findLatestMigration(graph);\n if (!latestMigration) {\n return notOk(\n errorRuntime('Could not resolve latest migration', {\n why: `No latest migration found in ${relative(process.cwd(), spaceDir)}`,\n fix: 'The migrations directory may be corrupted. Inspect the migration.json files.',\n }),\n );\n }\n const leafPkg = allPackages.find(\n (p) => p.metadata.migrationHash === latestMigration.migrationHash,\n );\n return ok(leafPkg ?? null);\n } catch (error) {\n if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read migrations: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n}\n\nfunction pkgToSpaceResult(\n spaceId: string,\n pkg: OnDiskMigrationPackage,\n client: ReturnType<typeof createControlClient>,\n): MigrationShowSpacePresent {\n const ops = pkg.ops as readonly MigrationPlanOperation[];\n const preview: OperationPreview = client.toOperationPreview(ops) ?? { statements: [] };\n return {\n kind: 'present',\n spaceId,\n dirName: pkg.dirName,\n dirPath: relative(process.cwd(), pkg.dirPath),\n from: pkg.metadata.from,\n to: pkg.metadata.to,\n migrationHash: pkg.metadata.migrationHash,\n createdAt: pkg.metadata.createdAt,\n operations: ops.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n preview,\n summary: `${ops.length} operation(s)`,\n };\n}\n\nasync function executeMigrationShowCommand(\n target: string | undefined,\n options: MigrationShowOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<MigrationShowResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, appMigrationsDir, appMigrationsRelative, refsDir } =\n resolveMigrationPaths(options.config, config);\n\n const contractPathAbsolute = resolveContractPath(config);\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n { label: 'migrations', value: appMigrationsRelative },\n ];\n if (target) {\n details.push({ label: 'target', value: target });\n }\n const header = formatStyledHeader({\n command: 'migration show',\n description: 'Display migration package contents',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n // `migration show` is an offline command; the control client is constructed\n // purely to dispatch the family-specific `toOperationPreview` capability and\n // is not connected to a database.\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n ...ifDefined('driver', config.driver),\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Explicit-target path. Read the app-space migrations directory directly\n // and resolve `target` against the app graph. We deliberately skip\n // `buildContractSpaceAggregate` here for two reasons:\n //\n // 1. Functional: the user asked about ONE specific migration. They don't\n // need extension-space enumeration; resolving + rendering the named\n // package is enough.\n // 2. UX: the aggregate's layout-integrity check (PN-MIG-5001) fires when\n // an extension is declared but its migrations directory hasn't been\n // materialised. Gating an offline read-only inspect command on that\n // check forces users to run `migrate` against a database before they\n // can see what a migration contains — which contradicts what an\n // offline read-only verb should require.\n //\n // Same pattern as `migration list`, `migration graph`, `migration check`:\n // those verbs read `appMigrationsDir` directly without ever consulting\n // the aggregate.\n if (target) {\n try {\n let appPkg: OnDiskMigrationPackage;\n if (looksLikePath(target)) {\n const resolved = resolveAppTargetPath(target, appMigrationsDir, appMigrationsRelative);\n if (!resolved.ok) return resolved;\n appPkg = await readMigrationPackage(resolved.value);\n } else {\n const allPackages = await readMigrationsDir(appMigrationsDir);\n if (allPackages.length === 0) {\n return notOk(\n errorRuntime('No migrations found', {\n why: `No migration packages found in ${appMigrationsRelative}`,\n fix: 'Run `prisma-next migration plan` to create a migration first.',\n }),\n );\n }\n const graph = reconstructGraph(allPackages);\n const refs = await readRefs(refsDir);\n const migResult = parseMigrationRef(target, { graph, refs });\n if (!migResult.ok) {\n return notOk(mapRefResolutionError(migResult.failure));\n }\n const matchedPkg = allPackages.find(\n (p) => p.metadata.migrationHash === migResult.value.migrationHash,\n );\n if (!matchedPkg) {\n return notOk(\n errorRuntime('Migration package not found', {\n why: `Resolved migration \"${migResult.value.dirName}\" but the package was not loaded`,\n fix: 'The migrations directory may be corrupted. Inspect the migration.json files.',\n }),\n );\n }\n appPkg = matchedPkg;\n }\n return ok({\n ok: true,\n spaces: [pkgToSpaceResult(APP_SPACE_ID, appPkg, client)],\n });\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read app-space migration: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n }\n\n // No-target path. Enumerate the latest migration per space (app +\n // extensions). The aggregate-loader is needed here because we need to\n // know which extension spaces are declared; its layout-integrity check\n // is appropriate at this entry point because the user is asking the\n // system to report on every loaded space.\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: 'Failed to read contract file',\n }),\n );\n }\n\n // Construct the family instance up-front so the on-disk app contract\n // read crosses the serializer seam (`familyInstance.deserializeContract`)\n // at the read site. See TML-2536.\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n\n let appContract: Contract;\n try {\n appContract = familyInstance.deserializeContract(JSON.parse(contractJsonContent) as unknown);\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract at ${contractPathAbsolute} failed to deserialize: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n const aggregateResult = await buildContractSpaceAggregate({\n targetId: config.target.targetId,\n migrationsDir,\n appContract,\n extensionPacks: config.extensionPacks ?? [],\n deserializeContract: (json: unknown) => familyInstance.deserializeContract(json),\n });\n if (!aggregateResult.ok) {\n return notOk(aggregateResult.failure);\n }\n const aggregate = aggregateResult.value;\n\n const spaces: MigrationShowSpaceResult[] = [];\n\n // App space: latest leaf.\n try {\n const allPackages = await readMigrationsDir(appMigrationsDir);\n if (allPackages.length === 0) {\n return notOk(\n errorRuntime('No migrations found', {\n why: `No migration packages found in ${appMigrationsRelative}`,\n fix: 'Run `prisma-next migration plan` to create a migration first.',\n }),\n );\n }\n const graph = reconstructGraph(allPackages);\n const latestMigration = findLatestMigration(graph);\n if (!latestMigration) {\n return notOk(\n errorRuntime('Could not resolve latest migration', {\n why: 'No latest migration found in the migration history',\n fix: 'The migrations directory may be corrupted. Inspect the migration.json files.',\n }),\n );\n }\n const leafPkg = allPackages.find(\n (p) => p.metadata.migrationHash === latestMigration.migrationHash,\n );\n if (!leafPkg) {\n return notOk(\n errorRuntime('Could not resolve latest migration', {\n why: `Latest migration ${latestMigration.dirName} does not match any package`,\n fix: 'The migrations directory may be corrupted. Inspect the migration.json files.',\n }),\n );\n }\n spaces.push(pkgToSpaceResult(aggregate.app.spaceId, leafPkg, client));\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read app-space migration: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n // Extension spaces: always emit one entry per loaded extension so the\n // response enumerates every space the aggregate knows about. Spaces\n // with no on-disk migration package yet (e.g. an extension was declared\n // but never `migrate`d) become `kind: 'missing'` placeholders instead\n // of being silently skipped.\n for (const ext of aggregate.extensions) {\n const extSpaceDir = spaceMigrationDirectory(migrationsDir, ext.spaceId);\n const extPkgResult = await resolveLatestFromDir(extSpaceDir);\n if (!extPkgResult.ok) return extPkgResult;\n if (extPkgResult.value !== null) {\n spaces.push(pkgToSpaceResult(ext.spaceId, extPkgResult.value, client));\n } else {\n spaces.push({\n kind: 'missing',\n spaceId: ext.spaceId,\n summary: 'No on-disk migration package for this space',\n });\n }\n }\n\n return ok({ ok: true, spaces });\n}\n\nexport function createMigrationShowCommand(): Command {\n const command = new Command('show');\n setCommandDescriptions(\n command,\n 'Display migration package contents',\n 'Shows the operations, statement preview, and metadata for every loaded contract\\n' +\n 'space (app + extensions). Accepts a directory path or hash prefix to target a\\n' +\n 'specific app-space migration; defaults to the latest per space.',\n );\n setCommandExamples(command, [\n 'prisma-next migration show',\n 'prisma-next migration show sha256:a1b2c3',\n ]);\n setCommandSeeAlso(command, [\n { verb: 'migration status', oneLiner: 'Show migration path and pending status' },\n { verb: 'migration log', oneLiner: 'Show executed migration history' },\n { verb: 'migration list', oneLiner: 'List on-disk migrations' },\n { verb: 'migration graph', oneLiner: 'Show the migration graph topology' },\n ]);\n addGlobalOptions(command)\n .argument(\n '[target]',\n 'Migration reference: directory name, hash/prefix, or path (defaults to latest)',\n )\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (target: string | undefined, options: MigrationShowOptions) => {\n const flags = parseGlobalFlags(options);\n\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n const result = await executeMigrationShowCommand(target, options, flags, ui);\n\n const exitCode = handleResult(result, flags, ui, (showResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(showResult, null, 2));\n } else if (!flags.quiet) {\n ui.log(formatMigrationShowOutput(showResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuGA,SAAS,cAAc,QAAyB;CAC9C,OAAO,OAAO,SAAS,IAAI,IAAI,OAAO,SAAS,KAAK;;;;;;;;;;;;;;;AAgBtD,SAAgB,qBACd,QACA,kBACA,uBACoC;CACpC,MAAM,aAAa,QAAQ,OAAO;CAClC,MAAM,gBAAgB,SAAS,kBAAkB,WAAW;CAM5D,IAJE,kBAAkB,MAClB,kBAAkB,OAClB,cAAc,WAAW,KAAK,IAC9B,WAAW,cAAc,EAEzB,OAAO,MACL,aAAa,+CAA+C;EAC1D,KAAK,yBAAyB,sBAAsB,QAAQ;EAC5D,KAAK;EACN,CAAC,CACH;CAEH,OAAO,GAAG,WAAW;;AAGvB,SAAgB,oBACd,UACA,QACoD;CACpD,MAAM,mBAAmB,OAAO,WAAW,UAAU,GAAG,SAAS,UAAU;CAC3E,MAAM,UAAU,SAAS,QAAQ,MAAM,EAAE,SAAS,cAAc,WAAW,iBAAiB,CAAC;CAE7F,IAAI,QAAQ,WAAW,GACrB,OAAO,GAAG,QAA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AM,qBADP,wBAAwB,eAAe,IAAI,QACJ,CAAC;EAC5D,IAAI,CAAC,aAAa,IAAI,OAAO;EAC7B,IAAI,aAAa,UAAU,MACzB,OAAO,KAAK,iBAAiB,IAAI,SAAS,aAAa,OAAO,OAAO,CAAC;OAEtE,OAAO,KAAK;GACV,MAAM;GACN,SAAS,IAAI;GACb,SAAS;GACV,CAAC;;CAIN,OAAO,GAAG;EAAE,IAAI;EAAM;EAAQ,CAAC;;AAGjC,SAAgB,6BAAsC;CACpD,MAAM,UAAU,IAAI,QAAQ,OAAO;CACnC,uBACE,SACA,sCACA,kOAGD;CACD,mBAAmB,SAAS,CAC1B,8BACA,2CACD,CAAC;CACF,kBAAkB,SAAS;EACzB;GAAE,MAAM;GAAoB,UAAU;GAA0C;EAChF;GAAE,MAAM;GAAiB,UAAU;GAAmC;EACtE;GAAE,MAAM;GAAkB,UAAU;GAA2B;EAC/D;GAAE,MAAM;GAAmB,UAAU;GAAqC;EAC3E,CAAC;CACF,iBAAiB,QAAQ,CACtB,SACC,YACA,iFACD,CACA,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,OAAO,QAA4B,YAAkC;EAC3E,MAAM,QAAQ,iBAAiB,QAAQ;EAEvC,MAAM,KAAK,IAAI,WAAW;GAAE,OAAO,MAAM;GAAO,aAAa,MAAM;GAAa,CAAC;EAIjF,MAAM,WAAW,aAAa,MAFT,4BAA4B,QAAQ,SAAS,OAAO,GAAG,EAEtC,OAAO,KAAK,eAAe;GAC/D,IAAI,MAAM,MACR,GAAG,OAAO,KAAK,UAAU,YAAY,MAAM,EAAE,CAAC;QACzC,IAAI,CAAC,MAAM,OAChB,GAAG,IAAI,0BAA0B,YAAY,MAAM,CAAC;IAEtD;EAEF,QAAQ,KAAK,SAAS;GACtB;CAEJ,OAAO"}
1
+ {"version":3,"file":"migration-show.mjs","names":[],"sources":["../../src/commands/migration-show.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport {\n APP_SPACE_ID,\n createControlStack,\n type MigrationPlanOperation,\n type OperationPreview,\n} from '@prisma-next/framework-components/control';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { readMigrationPackage, readMigrationsDir } from '@prisma-next/migration-tools/io';\nimport {\n findLatestMigration,\n reconstructGraph,\n} from '@prisma-next/migration-tools/migration-graph';\nimport type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';\nimport { parseMigrationRef } from '@prisma-next/migration-tools/ref-resolution';\nimport { readRefs } from '@prisma-next/migration-tools/refs';\nimport { spaceMigrationDirectory } from '@prisma-next/migration-tools/spaces';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { isAbsolute, relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport {\n type CliStructuredError,\n errorContractValidationFailed,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n mapMigrationToolsError,\n mapRefResolutionError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n setCommandSeeAlso,\n} from '../utils/command-helpers';\nimport { buildContractSpaceAggregate } from '../utils/contract-space-aggregate-loader';\nimport { formatMigrationShowOutput } from '../utils/formatters/migrations';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationShowOptions extends CommonCommandOptions {\n readonly config?: string;\n}\n\n/**\n * Details of one space's latest (or targeted) migration package.\n */\nexport interface MigrationShowSpacePresent {\n readonly kind: 'present';\n readonly spaceId: string;\n readonly dirName: string;\n readonly dirPath: string;\n readonly from: string | null;\n readonly to: string;\n readonly migrationHash: string;\n readonly createdAt: string;\n readonly operations: readonly {\n readonly id: string;\n readonly label: string;\n readonly operationClass: string;\n }[];\n /**\n * Family-agnostic textual preview of the migration's operations. Always\n * defined; statements is empty for a no-op migration or a family that does\n * not implement the `OperationPreviewCapable` capability.\n */\n readonly preview: OperationPreview;\n readonly summary: string;\n}\n\n/**\n * Placeholder for a loaded contract space that has no on-disk migration\n * package — the extension descriptor declared the space but no migrations\n * directory has been materialised for it yet. Surfaces the space in the\n * response so JSON consumers see every loaded extension instead of having\n * silently-skipped entries.\n */\nexport interface MigrationShowSpaceMissing {\n readonly kind: 'missing';\n readonly spaceId: string;\n readonly summary: string;\n}\n\nexport type MigrationShowSpaceResult = MigrationShowSpacePresent | MigrationShowSpaceMissing;\n\nexport interface MigrationShowResult {\n readonly ok: true;\n /**\n * Per-space results, ordered: app first, then extensions alphabetically\n * (matching the aggregate's canonical ordering).\n */\n readonly spaces: readonly MigrationShowSpaceResult[];\n}\n\nfunction looksLikePath(target: string): boolean {\n return target.includes('/') || target.includes('\\\\');\n}\n\n/**\n * Validate that a path-like `migration show` target resolves inside the app\n * migrations directory. The returned result is always emitted under\n * `aggregate.app.spaceId`, so accepting an extension-space (or otherwise\n * external) path here would silently mislabel the result. Returns the\n * resolved absolute path on success.\n *\n * `pathe.relative` can return an absolute path when the target cannot be\n * expressed relative to the base (e.g. on Windows when `target` is on a\n * different drive than `appMigrationsDir`). That case does not start with\n * `..`, so the absolute-check below is required to reject cross-drive\n * targets rather than mislabeling them as app-space.\n */\nexport function resolveAppTargetPath(\n target: string,\n appMigrationsDir: string,\n appMigrationsRelative: string,\n): Result<string, CliStructuredError> {\n const targetPath = resolve(target);\n const relativeToApp = relative(appMigrationsDir, targetPath);\n const isOutsideAppDir =\n relativeToApp === '' ||\n relativeToApp === '.' ||\n relativeToApp.startsWith('..') ||\n isAbsolute(relativeToApp);\n if (isOutsideAppDir) {\n return notOk(\n errorRuntime('Target must point to an app-space migration', {\n why: `Expected a path under ${appMigrationsRelative}, got ${target}`,\n fix: 'Pass an app-space migration directory or use a hash prefix.',\n }),\n );\n }\n return ok(targetPath);\n}\n\nexport function resolveByHashPrefix(\n packages: readonly OnDiskMigrationPackage[],\n prefix: string,\n): Result<OnDiskMigrationPackage, CliStructuredError> {\n const normalizedPrefix = prefix.startsWith('sha256:') ? prefix : `sha256:${prefix}`;\n const matches = packages.filter((p) => p.metadata.migrationHash.startsWith(normalizedPrefix));\n\n if (matches.length === 1) {\n return ok(matches[0]!);\n }\n\n if (matches.length === 0) {\n return notOk(\n errorRuntime('No migration found matching prefix', {\n why: `No migration has a migrationHash starting with \"${normalizedPrefix}\"`,\n fix: 'Run `prisma-next migration show` (no argument) to see the latest migration, or check the migrations directory for available packages.',\n }),\n );\n }\n\n const candidates = matches.map((p) => ` ${p.dirName} ${p.metadata.migrationHash}`).join('\\n');\n return notOk(\n errorRuntime('Ambiguous hash prefix', {\n why: `Multiple migrations match prefix \"${normalizedPrefix}\":\\n${candidates}`,\n fix: 'Provide a longer prefix to uniquely identify the migration.',\n }),\n );\n}\n\n/**\n * Resolve the latest migration from a space directory.\n *\n * Returns `ok(null)` only when the directory is empty or absent (ENOENT is\n * absorbed by `readMigrationsDir`). If `readMigrationsDir` returned packages\n * but `findLatestMigration` cannot pick a leaf, the on-disk history is\n * corrupt — return a runtime error rather than collapsing it to a `missing`\n * placeholder, which would hide the corruption from the caller.\n */\nexport async function resolveLatestFromDir(\n spaceDir: string,\n): Promise<Result<OnDiskMigrationPackage | null, CliStructuredError>> {\n try {\n const allPackages = await readMigrationsDir(spaceDir);\n if (allPackages.length === 0) return ok(null);\n const graph = reconstructGraph(allPackages);\n const latestMigration = findLatestMigration(graph);\n if (!latestMigration) {\n return notOk(\n errorRuntime('Could not resolve latest migration', {\n why: `No latest migration found in ${relative(process.cwd(), spaceDir)}`,\n fix: 'The migrations directory may be corrupted. Inspect the migration.json files.',\n }),\n );\n }\n const leafPkg = allPackages.find(\n (p) => p.metadata.migrationHash === latestMigration.migrationHash,\n );\n return ok(leafPkg ?? null);\n } catch (error) {\n if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read migrations: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n}\n\nfunction pkgToSpaceResult(\n spaceId: string,\n pkg: OnDiskMigrationPackage,\n client: ReturnType<typeof createControlClient>,\n): MigrationShowSpacePresent {\n const ops = pkg.ops as readonly MigrationPlanOperation[];\n const preview: OperationPreview = client.toOperationPreview(ops) ?? { statements: [] };\n return {\n kind: 'present',\n spaceId,\n dirName: pkg.dirName,\n dirPath: relative(process.cwd(), pkg.dirPath),\n from: pkg.metadata.from,\n to: pkg.metadata.to,\n migrationHash: pkg.metadata.migrationHash,\n createdAt: pkg.metadata.createdAt,\n operations: ops.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n preview,\n summary: `${ops.length} operation(s)`,\n };\n}\n\nasync function executeMigrationShowCommand(\n target: string | undefined,\n options: MigrationShowOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<MigrationShowResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, appMigrationsDir, appMigrationsRelative, refsDir } =\n resolveMigrationPaths(options.config, config);\n\n const contractPathAbsolute = resolveContractPath(config);\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n { label: 'migrations', value: appMigrationsRelative },\n ];\n if (target) {\n details.push({ label: 'target', value: target });\n }\n const header = formatStyledHeader({\n command: 'migration show',\n description: 'Display migration package contents',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n // `migration show` is an offline command; the control client is constructed\n // purely to dispatch the family-specific `toOperationPreview` capability and\n // is not connected to a database.\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n ...ifDefined('driver', config.driver),\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Explicit-target path. Read the app-space migrations directory directly\n // and resolve `target` against the app graph. We deliberately skip\n // `buildContractSpaceAggregate` here for two reasons:\n //\n // 1. Functional: the user asked about ONE specific migration. They don't\n // need extension-space enumeration; resolving + rendering the named\n // package is enough.\n // 2. UX: the aggregate's layout-integrity check (PN-MIG-5001) fires when\n // an extension is declared but its migrations directory hasn't been\n // materialised. Gating an offline read-only inspect command on that\n // check forces users to run `migrate` against a database before they\n // can see what a migration contains — which contradicts what an\n // offline read-only verb should require.\n //\n // Same pattern as `migration list`, `migration graph`, `migration check`:\n // those verbs read `appMigrationsDir` directly without ever consulting\n // the aggregate.\n if (target) {\n try {\n let appPkg: OnDiskMigrationPackage;\n if (looksLikePath(target)) {\n const resolved = resolveAppTargetPath(target, appMigrationsDir, appMigrationsRelative);\n if (!resolved.ok) return resolved;\n appPkg = await readMigrationPackage(resolved.value);\n } else {\n const allPackages = await readMigrationsDir(appMigrationsDir);\n if (allPackages.length === 0) {\n return notOk(\n errorRuntime('No migrations found', {\n why: `No migration packages found in ${appMigrationsRelative}`,\n fix: 'Run `prisma-next migration plan` to create a migration first.',\n }),\n );\n }\n const graph = reconstructGraph(allPackages);\n const refs = await readRefs(refsDir);\n const migResult = parseMigrationRef(target, { graph, refs });\n if (!migResult.ok) {\n return notOk(mapRefResolutionError(migResult.failure));\n }\n const matchedPkg = allPackages.find(\n (p) => p.metadata.migrationHash === migResult.value.migrationHash,\n );\n if (!matchedPkg) {\n return notOk(\n errorRuntime('Migration package not found', {\n why: `Resolved migration \"${migResult.value.dirName}\" but the package was not loaded`,\n fix: 'The migrations directory may be corrupted. Inspect the migration.json files.',\n }),\n );\n }\n appPkg = matchedPkg;\n }\n return ok({\n ok: true,\n spaces: [pkgToSpaceResult(APP_SPACE_ID, appPkg, client)],\n });\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read app-space migration: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n }\n\n // No-target path. Enumerate the latest migration per space (app +\n // extensions). The aggregate-loader is needed here because we need to\n // know which extension spaces are declared; its layout-integrity check\n // is appropriate at this entry point because the user is asking the\n // system to report on every loaded space.\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: 'Failed to read contract file',\n }),\n );\n }\n\n // Construct the family instance up-front so the on-disk app contract\n // read crosses the serializer seam (`familyInstance.deserializeContract`)\n // at the read site. See TML-2536.\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n\n let appContract: Contract;\n try {\n appContract = familyInstance.deserializeContract(JSON.parse(contractJsonContent) as unknown);\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract at ${contractPathAbsolute} failed to deserialize: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n const aggregateResult = await buildContractSpaceAggregate({\n targetId: config.target.targetId,\n migrationsDir,\n appContract,\n extensionPacks: config.extensionPacks ?? [],\n deserializeContract: (json: unknown) => familyInstance.deserializeContract(json),\n });\n if (!aggregateResult.ok) {\n return notOk(aggregateResult.failure);\n }\n const aggregate = aggregateResult.value;\n\n const spaces: MigrationShowSpaceResult[] = [];\n\n // App space: latest leaf.\n try {\n const allPackages = await readMigrationsDir(appMigrationsDir);\n if (allPackages.length === 0) {\n return notOk(\n errorRuntime('No migrations found', {\n why: `No migration packages found in ${appMigrationsRelative}`,\n fix: 'Run `prisma-next migration plan` to create a migration first.',\n }),\n );\n }\n const graph = reconstructGraph(allPackages);\n const latestMigration = findLatestMigration(graph);\n if (!latestMigration) {\n return notOk(\n errorRuntime('Could not resolve latest migration', {\n why: 'No latest migration found in the migration history',\n fix: 'The migrations directory may be corrupted. Inspect the migration.json files.',\n }),\n );\n }\n const leafPkg = allPackages.find(\n (p) => p.metadata.migrationHash === latestMigration.migrationHash,\n );\n if (!leafPkg) {\n return notOk(\n errorRuntime('Could not resolve latest migration', {\n why: `Latest migration ${latestMigration.dirName} does not match any package`,\n fix: 'The migrations directory may be corrupted. Inspect the migration.json files.',\n }),\n );\n }\n spaces.push(pkgToSpaceResult(aggregate.app.spaceId, leafPkg, client));\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read app-space migration: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n // Extension spaces: always emit one entry per loaded extension so the\n // response enumerates every space the aggregate knows about. Spaces\n // with no on-disk migration package yet (e.g. an extension was declared\n // but never `migrate`d) become `kind: 'missing'` placeholders instead\n // of being silently skipped.\n for (const ext of aggregate.extensions) {\n const extSpaceDir = spaceMigrationDirectory(migrationsDir, ext.spaceId);\n const extPkgResult = await resolveLatestFromDir(extSpaceDir);\n if (!extPkgResult.ok) return extPkgResult;\n if (extPkgResult.value !== null) {\n spaces.push(pkgToSpaceResult(ext.spaceId, extPkgResult.value, client));\n } else {\n spaces.push({\n kind: 'missing',\n spaceId: ext.spaceId,\n summary: 'No on-disk migration package for this space',\n });\n }\n }\n\n return ok({ ok: true, spaces });\n}\n\nexport function createMigrationShowCommand(): Command {\n const command = new Command('show');\n setCommandDescriptions(\n command,\n 'Display migration package contents',\n 'Shows the operations, statement preview, and metadata for every loaded contract\\n' +\n 'space (app + extensions). Accepts a directory path or hash prefix to target a\\n' +\n 'specific app-space migration; defaults to the latest per space.',\n );\n setCommandExamples(command, [\n 'prisma-next migration show',\n 'prisma-next migration show sha256:a1b2c3',\n ]);\n setCommandSeeAlso(command, [\n { verb: 'migration status', oneLiner: 'Show migration path and pending status' },\n { verb: 'migration log', oneLiner: 'Show executed migration history' },\n { verb: 'migration list', oneLiner: 'List on-disk migrations' },\n { verb: 'migration graph', oneLiner: 'Show the migration graph topology' },\n ]);\n addGlobalOptions(command)\n .argument(\n '[target]',\n 'Migration reference: directory name, hash/prefix, or path (defaults to latest)',\n )\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (target: string | undefined, options: MigrationShowOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n\n const ui = createTerminalUI(flags);\n\n const result = await executeMigrationShowCommand(target, options, flags, ui);\n\n const exitCode = handleResult(result, flags, ui, (showResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(showResult, null, 2));\n } else if (!flags.quiet) {\n ui.log(formatMigrationShowOutput(showResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuGA,SAAS,cAAc,QAAyB;CAC9C,OAAO,OAAO,SAAS,IAAI,IAAI,OAAO,SAAS,KAAK;;;;;;;;;;;;;;;AAgBtD,SAAgB,qBACd,QACA,kBACA,uBACoC;CACpC,MAAM,aAAa,QAAQ,OAAO;CAClC,MAAM,gBAAgB,SAAS,kBAAkB,WAAW;CAM5D,IAJE,kBAAkB,MAClB,kBAAkB,OAClB,cAAc,WAAW,KAAK,IAC9B,WAAW,cAAc,EAEzB,OAAO,MACL,aAAa,+CAA+C;EAC1D,KAAK,yBAAyB,sBAAsB,QAAQ;EAC5D,KAAK;EACN,CAAC,CACH;CAEH,OAAO,GAAG,WAAW;;AAGvB,SAAgB,oBACd,UACA,QACoD;CACpD,MAAM,mBAAmB,OAAO,WAAW,UAAU,GAAG,SAAS,UAAU;CAC3E,MAAM,UAAU,SAAS,QAAQ,MAAM,EAAE,SAAS,cAAc,WAAW,iBAAiB,CAAC;CAE7F,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,OAAO,UAAU,YAAY;EAEtC,MAAM,eAAe,MAAM,qBADP,wBAAwB,eAAe,IAAI,QACJ,CAAC;EAC5D,IAAI,CAAC,aAAa,IAAI,OAAO;EAC7B,IAAI,aAAa,UAAU,MACzB,OAAO,KAAK,iBAAiB,IAAI,SAAS,aAAa,OAAO,OAAO,CAAC;OAEtE,OAAO,KAAK;GACV,MAAM;GACN,SAAS,IAAI;GACb,SAAS;GACV,CAAC;;CAIN,OAAO,GAAG;EAAE,IAAI;EAAM;EAAQ,CAAC;;AAGjC,SAAgB,6BAAsC;CACpD,MAAM,UAAU,IAAI,QAAQ,OAAO;CACnC,uBACE,SACA,sCACA,kOAGD;CACD,mBAAmB,SAAS,CAC1B,8BACA,2CACD,CAAC;CACF,kBAAkB,SAAS;EACzB;GAAE,MAAM;GAAoB,UAAU;GAA0C;EAChF;GAAE,MAAM;GAAiB,UAAU;GAAmC;EACtE;GAAE,MAAM;GAAkB,UAAU;GAA2B;EAC/D;GAAE,MAAM;GAAmB,UAAU;GAAqC;EAC3E,CAAC;CACF,iBAAiB,QAAQ,CACtB,SACC,YACA,iFACD,CACA,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,OAAO,QAA4B,YAAkC;EAC3E,MAAM,QAAQ,uBAAuB,QAAQ;EAE7C,MAAM,KAAK,iBAAiB,MAAM;EAIlC,MAAM,WAAW,aAAa,MAFT,4BAA4B,QAAQ,SAAS,OAAO,GAAG,EAEtC,OAAO,KAAK,eAAe;GAC/D,IAAI,MAAM,MACR,GAAG,OAAO,KAAK,UAAU,YAAY,MAAM,EAAE,CAAC;QACzC,IAAI,CAAC,MAAM,OAChB,GAAG,IAAI,0BAA0B,YAAY,MAAM,CAAC;IAEtD;EAEF,QAAQ,KAAK,SAAS;GACtB;CAEJ,OAAO"}
@@ -1,4 +1,4 @@
1
- import { n as StatusRef, t as StatusDiagnostic } from "../migration-types-D2FW63pr.mjs";
1
+ import { n as StatusRef, t as StatusDiagnostic } from "../migration-types-BXWvz12q.mjs";
2
2
  import { Command } from "commander";
3
3
  import { Result } from "@prisma-next/utils/result";
4
4
  import { ControlExtensionDescriptor } from "@prisma-next/framework-components/control";
@@ -1 +1 @@
1
- {"version":3,"file":"migration-status.d.mts","names":[],"sources":["../../src/utils/contract-space-aggregate-loader.ts","../../src/utils/formatters/graph-migration-mapper.ts","../../src/commands/migration-status.ts"],"mappings":";;;;;;;;;;;;;;;;;UAqHiB,oBAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,aAAA;EAAA,SACA,WAAA,EAAa,QAAA;EAAA,SACb,cAAA,EAAgB,aAAA,CAAc,0BAAA,CAA2B,SAAA,EAAW,SAAA;EAAA,SACpE,mBAAA,GAAsB,YAAA,cAA0B,QAAA;EAJhD;;;;;;;;;;;;EAAA,SAiBA,oBAAA,GAAuB,aAAA,CAAc,sBAAA;AAAA;;;KCtHpC,cAAA;;UAmBK,UAAA;EAAA,SACN,OAAA;EAAA,SACA,MAAA,EAAQ,cAAA;AAAA;;;UCyCF,oBAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAA;EAAA,SACA,EAAA;EAAA,SACA,aAAA;EAAA,SACA,cAAA;EAAA,SACA,gBAAA;EAAA,SACA,cAAA;EAAA,SACA,MAAA,EAAQ,cAAA;AAAA;;;;;;;;;;;;;;;;;;;;UAsBF,yBAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAA;EAAA,SACA,QAAA;EAAA,SACA,UAAA;EAAA,SACA,YAAA;EAAA,SACA,MAAA;AAAA;;;;;ADlGX;;;iBC4GgB,+BAAA,CACd,MAAA,WAAiB,yBAAA;AAAA,UAaF,qBAAA;EAAA,SACN,EAAA;EAAA,SACA,IAAA;EAAA,SACA,UAAA,WAAqB,oBAAA;EAAA,SACrB,UAAA;EAAA,SACA,UAAA;EAAA,SACA,YAAA;EAAA,SACA,IAAA,YAAgB,SAAA;ED5GM;EAAA,SC8GtB,kBAAA;;;AArEX;;;;;;WA8EW,iBAAA;EA1EA;EAAA,SA4EA,iBAAA;EAAA,SACA,YAAA;IAAA,SACE,QAAA;IAAA,SACA,MAAA;IAAA,SACA,gBAAA;IAAA,SACA,eAAA;IAAA,SACA,OAAA;IAAA,SACA,kBAAA;IAAA,SACA,mBAAA;IAAA,SACA,YAAA;MAAA,SACE,OAAA;MAAA,SACA,aAAA;MAAA,SACA,IAAA;MAAA,SACA,EAAA;MAAA,SACA,UAAA;IAAA;EAAA;EAAA,SAGJ,OAAA;EAAA,SACA,WAAA,WAAsB,gBAAA;EApDjB;;;;;AAchB;;;;;;;;EAdgB,SAkEL,MAAA,YAAkB,yBAAA;EAKM;EAAA,SAHxB,wBAAA;EAAA,SACA,KAAA,GAAQ,cAAA;EAAA,SACR,OAAA,YAAmB,sBAAA;EAAA,SACnB,YAAA,YAAwB,UAAA;EAAA,SACxB,aAAA;EAAA,SACA,aAAA;EAAA,SACA,QAAA;AAAA;;;;;;;;;;;;;;;;iBA+CK,kBAAA,CACd,KAAA,EAAO,cAAA,EACP,UAAA,UACA,YAAA,UACA,UAAA,sBACA,IAAA,yBACC,UAAA;;;;;;;;;;;;iBAsLmB,yBAAA,CAA0B,IAAA;EAAA,SACrC,QAAA;EAAA,SACA,aAAA;EAAA,SACA,cAAA;EAAA,SACA,cAAA,EAAgB,oBAAA;EAAA,SAChB,mBAAA,EAAqB,oBAAA;EAAA,SACrB,cAAA,EAAgB,WAAA,SAAoB,wBAAA;AAAA,IAC3C,OAAA,UAAiB,yBAAA;AAAA,iBAknBL,4BAAA,CAAA,GAAgC,OAAA;AAAA,iBAoGhC,mBAAA,CAAoB,MAAA,EAAQ,qBAAA,EAAuB,QAAA"}
1
+ {"version":3,"file":"migration-status.d.mts","names":[],"sources":["../../src/utils/contract-space-aggregate-loader.ts","../../src/utils/formatters/graph-migration-mapper.ts","../../src/commands/migration-status.ts"],"mappings":";;;;;;;;;;;;;;;;;UAqHiB,oBAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,aAAA;EAAA,SACA,WAAA,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;;;;EAdgB,SAkEL,MAAA,YAAkB,yBAAA;EAKM;EAAA,SAHxB,wBAAA;EAAA,SACA,KAAA,GAAQ,cAAA;EAAA,SACR,OAAA,YAAmB,sBAAA;EAAA,SACnB,YAAA,YAAwB,UAAA;EAAA,SACxB,aAAA;EAAA,SACA,aAAA;EAAA,SACA,QAAA;AAAA;;;;;;;;;;;;;;;;iBA+CK,kBAAA,CACd,KAAA,EAAO,cAAA,EACP,UAAA,UACA,YAAA,UACA,UAAA,sBACA,IAAA,yBACC,UAAA;;;;;;;;;;;;iBAsLmB,yBAAA,CAA0B,IAAA;EAAA,SACrC,QAAA;EAAA,SACA,aAAA;EAAA,SACA,cAAA;EAAA,SACA,cAAA,EAAgB,oBAAA;EAAA,SAChB,mBAAA,EAAqB,oBAAA;EAAA,SACrB,cAAA,EAAgB,WAAA,SAAoB,wBAAA;AAAA,IAC3C,OAAA,UAAiB,yBAAA;AAAA,iBA6pBL,4BAAA,CAAA,GAAgC,OAAA;AAAA,iBAoGhC,mBAAA,CAAoB,MAAA,EAAQ,qBAAA,EAAuB,QAAA"}
@@ -1,11 +1,10 @@
1
1
  import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
2
- import { _ as errorUnexpected, m as errorRuntime, v as mapMigrationToolsError, y as mapRefResolutionError } from "../cli-errors-CF60g2cG.mjs";
3
- import { _ as parseGlobalFlags, a as loadMigrationPackages, b as formatStyledHeader, d as setCommandDescriptions, f as setCommandExamples, g as toStructuralEdge, h as toPathDecisionResult, l as resolveMigrationPaths, n as collectDeclaredInvariants, o as maskConnectionUrl, p as setCommandSeeAlso, s as readContractEnvelope, t as addGlobalOptions } from "../command-helpers-D3vL5yi8.mjs";
4
- import { t as handleResult } from "../result-handler-Bm_6dDYg.mjs";
5
- import { t as TerminalUI } from "../terminal-ui-XtOQsqe9.mjs";
6
- import { t as createControlClient } from "../client-Brv4qlfB.mjs";
7
- import { t as buildContractSpaceAggregate } from "../contract-space-aggregate-loader-pAc8CDfY.mjs";
8
- import { i as migrationGraphToRenderInput, n as graphRenderer, r as isLinearGraph, t as extractRelevantSubgraph } from "../graph-render-eJDcLWny.mjs";
2
+ import { b as mapMigrationToolsError, g as errorRuntime, t as CliStructuredError, x as mapRefResolutionError, y as errorUnexpected } from "../cli-errors-Djtz98Vm.mjs";
3
+ import { t as createTerminalUI } from "../terminal-ui-BiB_8KNo.mjs";
4
+ import { S as formatStyledHeader, a as loadMigrationPackages, d as setCommandDescriptions, f as setCommandExamples, g as toStructuralEdge, h as toPathDecisionResult, l as resolveMigrationPaths, n as collectDeclaredInvariants, o as maskConnectionUrl, p as setCommandSeeAlso, s as readContractEnvelope, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "../command-helpers-BSb0tRC8.mjs";
5
+ import { t as createControlClient } from "../client-oXO2WCPD.mjs";
6
+ import { t as buildContractSpaceAggregate } from "../contract-space-aggregate-loader-BmNQwlws.mjs";
7
+ import { i as migrationGraphToRenderInput, n as graphRenderer, r as isLinearGraph, t as extractRelevantSubgraph } from "../graph-render-DJVv0_uf.mjs";
9
8
  import { Command } from "commander";
10
9
  import { ifDefined } from "@prisma-next/utils/defined";
11
10
  import { notOk, ok } from "@prisma-next/utils/result";
@@ -254,13 +253,34 @@ async function loadAggregateStatusSpaces(args) {
254
253
  */
255
254
  async function loadContractRawSafely(config) {
256
255
  try {
257
- const path = (await import("../command-helpers-D3vL5yi8.mjs").then((n) => n.r)).resolveContractPath(config);
256
+ const path = (await import("../command-helpers-BSb0tRC8.mjs").then((n) => n.r)).resolveContractPath(config);
258
257
  const raw = await (await import("node:fs/promises")).readFile(path, "utf-8");
259
258
  return JSON.parse(raw);
260
259
  } catch {
261
260
  return null;
262
261
  }
263
262
  }
263
+ async function validateOnlineMarkerRead(config, dbConnection) {
264
+ const driver = config.driver;
265
+ if (!driver) return ok(void 0);
266
+ const client = createControlClient({
267
+ family: config.family,
268
+ target: config.target,
269
+ adapter: config.adapter,
270
+ driver,
271
+ extensionPacks: config.extensionPacks ?? []
272
+ });
273
+ try {
274
+ await client.connect(dbConnection);
275
+ await client.readMarker();
276
+ return ok(void 0);
277
+ } catch (error) {
278
+ if (CliStructuredError.is(error)) return notOk(error);
279
+ return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Failed to read database marker: ${error instanceof Error ? error.message : String(error)}` }));
280
+ } finally {
281
+ await client.close();
282
+ }
283
+ }
264
284
  async function executeMigrationStatusCommand(options, flags, ui) {
265
285
  const config = await loadConfig(options.config);
266
286
  const { configPath, appMigrationsDir, appMigrationsRelative, migrationsDir, refsDir } = resolveMigrationPaths(options.config, config);
@@ -363,6 +383,10 @@ async function executeMigrationStatusCommand(options, flags, ui) {
363
383
  return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Failed to read migrations directory: ${error instanceof Error ? error.message : String(error)}` }));
364
384
  }
365
385
  if (bundles.length === 0) {
386
+ if (dbConnection && hasDriver) {
387
+ const markerProbe = await validateOnlineMarkerRead(config, dbConnection);
388
+ if (!markerProbe.ok) return markerProbe;
389
+ }
366
390
  if (contractHash !== EMPTY_CONTRACT_HASH) diagnostics.push({
367
391
  code: "CONTRACT.AHEAD",
368
392
  severity: "warn",
@@ -413,7 +437,8 @@ async function executeMigrationStatusCommand(options, flags, ui) {
413
437
  mode = "online";
414
438
  if (typeof client.readAllMarkers === "function") allMarkers = await client.readAllMarkers();
415
439
  else allMarkers = null;
416
- } catch {
440
+ } catch (error) {
441
+ if (CliStructuredError.is(error)) return notOk(error);
417
442
  if (!flags.json && !flags.quiet) ui.warn("Could not connect to database — showing offline status");
418
443
  } finally {
419
444
  await client.close();
@@ -622,11 +647,8 @@ function createMigrationStatusCommand() {
622
647
  }
623
648
  ]);
624
649
  addGlobalOptions(command).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--to <contract>", "Target contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)").option("--from <contract>", "Origin contract reference; same grammar as --to. Supplying --from switches to offline path computation.").action(async (options) => {
625
- const flags = parseGlobalFlags(options);
626
- const ui = new TerminalUI({
627
- color: flags.color,
628
- interactive: flags.interactive
629
- });
650
+ const flags = parseGlobalFlagsOrExit(options);
651
+ const ui = createTerminalUI(flags);
630
652
  const exitCode = handleResult(await executeMigrationStatusCommand(options, flags, ui), flags, ui, (statusResult) => {
631
653
  if (flags.json) {
632
654
  const { graph: _graph, bundles: _bundles, edgeStatuses: _edgeStatuses, activeRefHash: _activeRefHash, activeRefName: _activeRefName, diverged: _diverged, ...jsonResult } = statusResult;
@@ -1 +1 @@
1
- {"version":3,"file":"migration-status.mjs","names":[],"sources":["../../src/commands/migration-status.ts"],"sourcesContent":["import {\n createControlStack,\n type MigrationPlanOperation,\n} from '@prisma-next/framework-components/control';\nimport {\n type ContractMarkerRecordLike,\n graphWalkStrategy,\n} from '@prisma-next/migration-tools/aggregate';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport {\n errorNoInvariantPath,\n errorUnknownInvariant,\n MigrationToolsError,\n} from '@prisma-next/migration-tools/errors';\nimport type { MigrationEdge, MigrationGraph } from '@prisma-next/migration-tools/graph';\nimport {\n findPath,\n findPathWithDecision,\n findReachableLeaves,\n} from '@prisma-next/migration-tools/migration-graph';\nimport type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';\nimport { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';\nimport type { RefEntry, Refs } from '@prisma-next/migration-tools/refs';\nimport { readRefs } from '@prisma-next/migration-tools/refs';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { cyan, dim, magenta, yellow } from 'colorette';\nimport { Command } from 'commander';\n\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport {\n type CliStructuredError,\n errorRuntime,\n errorUnexpected,\n mapMigrationToolsError,\n mapRefResolutionError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n collectDeclaredInvariants,\n loadMigrationPackages,\n maskConnectionUrl,\n readContractEnvelope,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n setCommandSeeAlso,\n toPathDecisionResult,\n toStructuralEdge,\n} from '../utils/command-helpers';\nimport {\n type BuildAggregateInputs,\n buildContractSpaceAggregate,\n} from '../utils/contract-space-aggregate-loader';\nimport {\n type EdgeStatus,\n type EdgeStatusKind,\n migrationGraphToRenderInput,\n} from '../utils/formatters/graph-migration-mapper';\nimport {\n extractRelevantSubgraph,\n graphRenderer,\n isLinearGraph,\n} from '../utils/formatters/graph-render';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport type { StatusDiagnostic, StatusRef } from '../utils/migration-types';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationStatusOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly to?: string;\n readonly from?: string;\n}\n\nexport interface MigrationStatusEntry {\n readonly dirName: string;\n readonly from: string;\n readonly to: string;\n readonly migrationHash: string;\n readonly operationCount: number;\n readonly operationSummary: string;\n readonly hasDestructive: boolean;\n readonly status: EdgeStatusKind | 'unknown';\n}\n\n/**\n * Per-space status row in the aggregate-shaped status output.\n *\n * Surfaces, for each contract space:\n *\n * - `headHash`: the on-disk head ref's hash (where the space is going).\n * - `markerHash`: the live marker hash for the space, or null if no\n * marker has been written yet (greenfield, or pre-`migrate`).\n * - `pendingCount`: number of migration edges between marker and head.\n * Computed via {@link graphWalkStrategy}; 0 means the space is\n * already at head.\n * - `status`: convenience tag the formatter uses to pick a glyph.\n * `'never-planned'` is reserved for spaces with non-empty head but\n * no on-disk migrations — which shouldn't happen if the loader's\n * integrity check passes.\n *\n * Online-only fields (`markerHash`, `status`) are absent when the\n * command runs without a database connection.\n */\nexport interface MigrationStatusSpaceEntry {\n readonly spaceId: string;\n readonly kind: 'app' | 'extension';\n readonly headHash: string;\n readonly markerHash?: string | null;\n readonly pendingCount?: number;\n readonly status?: 'up-to-date' | 'pending' | 'no-marker' | 'never-planned' | 'unreachable';\n}\n\n/**\n * Sum per-space `pendingCount` into a cross-space total, but only when\n * every loaded space reports a defined `pendingCount`. Returns\n * `undefined` if any space is on the marker-unknown / offline path\n * (where `pendingCount` is intentionally absent), so JSON consumers can\n * distinguish \"no pending\" from \"unknown\".\n */\nexport function computeTotalPendingAcrossSpaces(\n spaces: readonly MigrationStatusSpaceEntry[],\n): number | undefined {\n if (spaces.length === 0) return undefined;\n let total = 0;\n for (const s of spaces) {\n if (s.pendingCount === undefined) return undefined;\n total += s.pendingCount;\n }\n return total;\n}\n\nexport type { StatusDiagnostic, StatusRef } from '../utils/migration-types';\n\nexport interface MigrationStatusResult {\n readonly ok: true;\n readonly mode: 'online' | 'offline';\n readonly migrations: readonly MigrationStatusEntry[];\n readonly markerHash?: string;\n readonly targetHash: string;\n readonly contractHash: string;\n readonly refs?: readonly StatusRef[];\n /** Required invariants from the active ref, sorted ascending. Always present (`[]` when no `--ref` or the ref declares none) — knowable offline. */\n readonly requiredInvariants: readonly string[];\n /**\n * Invariants the marker has applied at least once, intersected with\n * `requiredInvariants` for display relevance. JSON consumers see only the\n * subset overlapping the active ref's required set — the full unfiltered\n * marker invariant list lives on `marker.invariants` (control plane) and\n * is not surfaced here. Present only in `mode === 'online'`; absent when\n * offline (the marker is unknown, not empty).\n */\n readonly appliedInvariants?: readonly string[];\n /** required − applied. Present only in `mode === 'online'`; absent when offline. */\n readonly missingInvariants?: readonly string[];\n readonly pathDecision?: {\n readonly fromHash: string;\n readonly toHash: string;\n readonly alternativeCount: number;\n readonly tieBreakReasons: readonly string[];\n readonly refName?: string;\n readonly requiredInvariants: readonly string[];\n readonly satisfiedInvariants: readonly string[];\n readonly selectedPath: readonly {\n readonly dirName: string;\n readonly migrationHash: string;\n readonly from: string;\n readonly to: string;\n readonly invariants: readonly string[];\n }[];\n };\n readonly summary: string;\n readonly diagnostics: readonly StatusDiagnostic[];\n /**\n * Aggregate enumeration of every on-disk contract space (app +\n * extensions), in canonical schedule order (extensions\n * alphabetically, then app). Present whenever the aggregate loader\n * succeeded; absent in early-error returns (e.g. unreadable\n * migrations directory) where the existing diagnostics already\n * surface the failure.\n *\n * The legacy top-level fields (`migrations`, `markerHash`,\n * `targetHash`, `pathDecision`, …) describe the **app member**\n * specifically — back-compat with single-space callers. Per-space\n * detail for extension members lives only on this list.\n */\n readonly spaces?: readonly MigrationStatusSpaceEntry[];\n /** Cross-space pending-migration total (sum of `spaces[].pendingCount`). Present when `spaces` is. */\n readonly totalPendingAcrossSpaces?: number;\n readonly graph?: MigrationGraph;\n readonly bundles?: readonly OnDiskMigrationPackage[];\n readonly edgeStatuses?: readonly EdgeStatus[];\n readonly activeRefHash?: string;\n readonly activeRefName?: string;\n readonly diverged?: boolean;\n}\n\nfunction summarizeOps(ops: readonly MigrationPlanOperation[]): {\n summary: string;\n hasDestructive: boolean;\n} {\n if (ops.length === 0) return { summary: '0 ops', hasDestructive: false };\n\n const classes = new Map<string, number>();\n for (const op of ops) {\n classes.set(op.operationClass, (classes.get(op.operationClass) ?? 0) + 1);\n }\n\n const hasDestructive = classes.has('destructive');\n const count = ops.length;\n const noun = count === 1 ? 'op' : 'ops';\n\n if (classes.size === 1) {\n const cls = [...classes.keys()][0]!;\n return { summary: `${count} ${noun} (all ${cls})`, hasDestructive };\n }\n\n const destructiveCount = classes.get('destructive');\n if (destructiveCount) {\n return { summary: `${count} ${noun} (${destructiveCount} destructive)`, hasDestructive };\n }\n\n const parts = [...classes.entries()].map(([cls, n]) => `${n} ${cls}`);\n return { summary: `${count} ${noun} (${parts.join(', ')})`, hasDestructive };\n}\n\n/**\n * Derive per-edge status across the full graph using path analysis.\n *\n * - **applied**: edge is on the path from root to the DB marker\n * - **pending**: edge is on the path from the DB marker to the target\n * (and the marker is reachable from root, i.e. it's on the same branch)\n * - **unreachable**: edge is on the path from root to the target but the DB\n * marker is on a different branch — `apply` can't reach these edges\n * without the DB first moving to this branch\n *\n * Returns statuses only for edges that have a known status (skips offline\n * and edges not on any relevant path).\n *\n * @internal Exported for testing only.\n */\nexport function deriveEdgeStatuses(\n graph: MigrationGraph,\n targetHash: string,\n contractHash: string,\n markerHash: string | undefined,\n mode: 'online' | 'offline',\n): EdgeStatus[] {\n if (mode === 'offline') return [];\n\n const edgeKey = (e: MigrationEdge) => `${e.from}\\0${e.to}`;\n\n // No marker = empty DB — treat root as the marker (nothing applied, everything pending)\n const effectiveMarker = markerHash ?? EMPTY_CONTRACT_HASH;\n\n const appliedPath =\n markerHash !== undefined ? findPath(graph, EMPTY_CONTRACT_HASH, markerHash) : null;\n\n const pendingPath = findPath(graph, effectiveMarker, targetHash);\n const targetPath = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n\n const statuses: EdgeStatus[] = [];\n const assignedKeys = new Set<string>();\n\n // Applied edges (root → marker)\n if (appliedPath) {\n for (const e of appliedPath) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'applied' });\n }\n }\n\n // Pending edges (marker → target)\n if (pendingPath) {\n for (const e of pendingPath) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'pending' });\n }\n }\n\n // Pending edges beyond the target: target → contract (when target is a ref\n // and the contract is reachable from it)\n if (\n contractHash !== EMPTY_CONTRACT_HASH &&\n contractHash !== targetHash &&\n graph.nodes.has(contractHash)\n ) {\n const beyondTarget = findPath(graph, targetHash, contractHash);\n if (beyondTarget) {\n for (const e of beyondTarget) {\n if (!assignedKeys.has(edgeKey(e))) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'pending' });\n }\n }\n }\n }\n\n // Unreachable edges: on the path from root to the target but neither applied\n // nor pending. This covers two cases:\n // 1. Marker can't reach target at all (different branch entirely)\n // 2. Marker reaches target via a different route, leaving some root→target\n // edges orphaned (e.g. a fork where one branch was applied and apply\n // will continue through the other)\n if (targetPath) {\n for (const e of targetPath) {\n if (!assignedKeys.has(edgeKey(e))) {\n statuses.push({ dirName: e.dirName, status: 'unreachable' });\n }\n }\n }\n\n return statuses;\n}\n\n/**\n * @param mode — 'online' if we connected to the database, 'offline' otherwise\n * @param markerHash — the marker hash from the database, or undefined if no marker row / offline\n */\nfunction buildMigrationEntries(\n chain: readonly MigrationEdge[],\n packages: readonly OnDiskMigrationPackage[],\n mode: 'online' | 'offline',\n markerHash: string | undefined,\n edgeStatuses?: readonly EdgeStatus[],\n): MigrationStatusEntry[] {\n const pkgByDirName = new Map(packages.map((p) => [p.dirName, p]));\n const statusByDirName = edgeStatuses\n ? new Map(edgeStatuses.map((e) => [e.dirName, e.status]))\n : undefined;\n\n const markerInChain = markerHash === undefined || chain.some((e) => e.to === markerHash);\n\n const entries: MigrationStatusEntry[] = [];\n let reachedMarker = mode === 'online' && markerHash === undefined;\n\n for (const migration of chain) {\n const pkg = pkgByDirName.get(migration.dirName);\n const ops = (pkg?.ops ?? []) as readonly MigrationPlanOperation[];\n const { summary, hasDestructive } = summarizeOps(ops);\n\n let status: EdgeStatusKind | 'unknown';\n const edgeStatus = statusByDirName?.get(migration.dirName);\n if (edgeStatus) {\n status = edgeStatus;\n } else if (mode === 'offline' || !markerInChain) {\n status = 'unknown';\n } else if (reachedMarker) {\n status = 'pending';\n } else {\n status = 'applied';\n }\n\n entries.push({\n dirName: migration.dirName,\n from: migration.from,\n to: migration.to,\n migrationHash: migration.migrationHash,\n operationCount: ops.length,\n operationSummary: summary,\n hasDestructive,\n status,\n });\n\n if (!reachedMarker && migration.to === markerHash) {\n reachedMarker = true;\n }\n }\n\n return entries;\n}\n\n/**\n * Resolve the migration chain to display in status output.\n *\n * When offline or the marker is at EMPTY, the chain is simply the shortest\n * path from EMPTY to the target — all structural paths are equivalent per\n * the spec, so the deterministic shortest path is the canonical display.\n *\n * When online with a non-empty marker, the chain routes *through* the marker:\n * EMPTY→marker (applied history) + marker→target (pending edges). This ensures\n * the displayed chain includes the marker node so applied/pending status is\n * correct. Without this, BFS from EMPTY to target could pick a shortest path\n * that bypasses the marker entirely (e.g. in a diamond graph), causing the\n * marker to appear \"diverged\" when it isn't.\n */\nfunction resolveDisplayChain(\n graph: MigrationGraph,\n targetHash: string,\n markerHash: string | undefined,\n): readonly MigrationEdge[] | null {\n if (markerHash === undefined) {\n return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n }\n\n const toMarker = findPath(graph, EMPTY_CONTRACT_HASH, markerHash);\n // Marker unreachable from EMPTY — show the target chain anyway.\n // The caller detects this via markerInChain and emits a divergence diagnostic.\n if (!toMarker) return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n\n if (markerHash === targetHash) return toMarker;\n\n const fromMarker = findPath(graph, markerHash, targetHash);\n if (fromMarker) return [...toMarker, ...fromMarker];\n\n // Marker is ahead of target (or on a disconnected branch).\n // Try the inverse: target→marker. If it succeeds, the marker is ahead —\n // show the full chain from EMPTY through the target and on to the marker.\n const toTarget = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n if (!toTarget) return null;\n\n const targetToMarker = findPath(graph, targetHash, markerHash);\n if (targetToMarker) return [...toTarget, ...targetToMarker];\n\n // Genuinely disconnected — show EMPTY→target; caller handles divergence diagnostic.\n return toTarget;\n}\n\n/**\n * Build the aggregate enumeration of contract spaces for the status\n * output. Loads the aggregate from disk (lossy on failure — extension\n * spaces are simply omitted, the existing single-space app behaviour\n * keeps working), reads per-space marker rows when online, and uses\n * {@link graphWalkStrategy} to compute each space's pending count.\n *\n * Sub-spec § `migration status` semantics — the aggregate-walking\n * version reports per-space marker + pending state alongside the\n * cross-space totals.\n */\nexport async function loadAggregateStatusSpaces(args: {\n readonly targetId: string;\n readonly migrationsDir: string;\n readonly appContractRaw: unknown;\n readonly extensionPacks: BuildAggregateInputs<string, string>['extensionPacks'];\n readonly deserializeContract: BuildAggregateInputs<string, string>['deserializeContract'];\n readonly markersBySpace: ReadonlyMap<string, ContractMarkerRecordLike> | null;\n}): Promise<readonly MigrationStatusSpaceEntry[]> {\n const loadInputs: BuildAggregateInputs<string, string> = {\n targetId: args.targetId,\n migrationsDir: args.migrationsDir,\n appContract: args.deserializeContract(args.appContractRaw),\n extensionPacks: args.extensionPacks,\n deserializeContract: args.deserializeContract,\n };\n\n const loaded = await buildContractSpaceAggregate(loadInputs);\n if (!loaded.ok) {\n // Loader failure (drift, layout violation, etc.) — surfacing it\n // as a status diagnostic would duplicate `migration plan`'s job.\n // The single-space app pipeline still runs; extensions are simply\n // not enumerated.\n return [];\n }\n const aggregate = loaded.value;\n\n const orderedMembers = [...aggregate.extensions, aggregate.app];\n const rows: MigrationStatusSpaceEntry[] = [];\n for (const member of orderedMembers) {\n const liveMarker = args.markersBySpace?.get(member.spaceId) ?? null;\n const isApp = member.spaceId === aggregate.app.spaceId;\n\n if (member.migrations.graph.nodes.size === 0) {\n rows.push({\n spaceId: member.spaceId,\n kind: isApp ? 'app' : 'extension',\n headHash: member.headRef.hash,\n ...(args.markersBySpace !== null\n ? {\n markerHash: liveMarker?.storageHash ?? null,\n status: member.headRef.hash === EMPTY_CONTRACT_HASH ? 'up-to-date' : 'never-planned',\n pendingCount: 0,\n }\n : {}),\n });\n continue;\n }\n\n if (args.markersBySpace === null) {\n rows.push({\n spaceId: member.spaceId,\n kind: isApp ? 'app' : 'extension',\n headHash: member.headRef.hash,\n });\n continue;\n }\n\n const walked = graphWalkStrategy({\n aggregateTargetId: aggregate.targetId,\n member,\n currentMarker: liveMarker,\n });\n let pendingCount = 0;\n let status: MigrationStatusSpaceEntry['status'];\n if (walked.kind === 'ok') {\n // Count pending *migrations* (graph edges), not operations: a\n // single authored migration that lowers to N ops or zero ops\n // both count as exactly one pending unit of work for the user.\n pendingCount = walked.result.migrationEdges?.length ?? 0;\n if (liveMarker === null) {\n status = pendingCount === 0 ? 'no-marker' : 'pending';\n } else {\n status = pendingCount === 0 ? 'up-to-date' : 'pending';\n }\n } else {\n status = 'unreachable';\n }\n\n rows.push({\n spaceId: member.spaceId,\n kind: isApp ? 'app' : 'extension',\n headHash: member.headRef.hash,\n markerHash: liveMarker?.storageHash ?? null,\n pendingCount,\n ...(status ? { status } : {}),\n });\n }\n return rows;\n}\n\n/**\n * Read the raw contract.json bytes from disk for the aggregate\n * loader. Returns `null` if the file is missing or unparseable —\n * the existing `readContractEnvelope` path will report the same\n * problem via a status diagnostic, no need to double-surface.\n */\nasync function loadContractRawSafely(config: {\n contract?: { output?: string };\n}): Promise<unknown | null> {\n try {\n const path = (await import('../utils/command-helpers')).resolveContractPath(config);\n const raw = await (await import('node:fs/promises')).readFile(path, 'utf-8');\n return JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n}\n\nasync function executeMigrationStatusCommand(\n options: MigrationStatusOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<MigrationStatusResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { configPath, appMigrationsDir, appMigrationsRelative, migrationsDir, refsDir } =\n resolveMigrationPaths(options.config, config);\n\n const dbConnection = options.db ?? config.db?.connection;\n const hasDriver = !!config.driver;\n\n let activeRefName: string | undefined;\n let activeRefHash: string | undefined;\n let activeRefEntry: RefEntry | undefined;\n let allRefs: Refs = {};\n try {\n allRefs = await readRefs(refsDir);\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n\n let fromOverrideHash: string | undefined;\n\n if (options.to || options.from) {\n try {\n const { graph: earlyGraph } = await loadMigrationPackages(appMigrationsDir);\n\n if (options.to) {\n const refResult = parseContractRef(options.to, { graph: earlyGraph, refs: allRefs });\n if (!refResult.ok) {\n return notOk(mapRefResolutionError(refResult.failure));\n }\n activeRefHash = refResult.value.hash;\n if (refResult.value.provenance.kind === 'ref') {\n const resolvedRefName = refResult.value.provenance.refName;\n activeRefName = resolvedRefName;\n activeRefEntry = allRefs[resolvedRefName];\n }\n }\n\n if (options.from) {\n const fromResult = parseContractRef(options.from, { graph: earlyGraph, refs: allRefs });\n if (!fromResult.ok) {\n return notOk(mapRefResolutionError(fromResult.failure));\n }\n fromOverrideHash = fromResult.value.hash;\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n }\n\n const requiredInvariants: readonly string[] = [...(activeRefEntry?.invariants ?? [])].sort();\n\n const statusRefs: StatusRef[] = Object.entries(allRefs).map(([name, entry]) => ({\n name,\n hash: entry.hash,\n active: name === activeRefName,\n }));\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'migrations', value: appMigrationsRelative },\n ];\n if (dbConnection && hasDriver) {\n details.push({ label: 'database', value: maskConnectionUrl(String(dbConnection)) });\n }\n if (activeRefName) {\n details.push({ label: 'ref', value: activeRefName });\n }\n if (options.from) {\n details.push({ label: 'from', value: options.from });\n }\n if (activeRefEntry && activeRefEntry.invariants.length > 0) {\n details.push({\n label: 'required',\n value: formatInvariantList(activeRefEntry.invariants),\n });\n }\n const header = formatStyledHeader({\n command: 'migration status',\n description: 'Show migration history and applied status',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n const diagnostics: StatusDiagnostic[] = [];\n let contractHash: string = EMPTY_CONTRACT_HASH;\n try {\n const envelope = await readContractEnvelope(config);\n contractHash = envelope.storageHash;\n } catch (error) {\n diagnostics.push({\n code: 'CONTRACT.UNREADABLE',\n severity: 'warn',\n message: `Could not read contract: ${error instanceof Error ? error.message : 'unknown error'}`,\n hints: [\"Run 'prisma-next contract emit' to generate a valid contract\"],\n });\n }\n\n let bundles: readonly OnDiskMigrationPackage[];\n let graph: MigrationGraph;\n try {\n ({ bundles, graph } = await loadMigrationPackages(appMigrationsDir));\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read migrations directory: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n if (bundles.length === 0) {\n if (contractHash !== EMPTY_CONTRACT_HASH) {\n diagnostics.push({\n code: 'CONTRACT.AHEAD',\n severity: 'warn',\n message: 'No migration exists for the current contract',\n hints: [\n \"Run 'prisma-next migration plan' to generate a migration for the current contract\",\n ],\n });\n }\n return ok({\n ok: true,\n mode: dbConnection && hasDriver ? 'online' : 'offline',\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: 'No migrations found',\n diagnostics,\n requiredInvariants,\n });\n }\n\n let targetHash: string | undefined;\n\n if (activeRefHash) {\n targetHash = activeRefHash;\n } else if (graph.nodes.has(contractHash)) {\n targetHash = contractHash;\n } else {\n const leaves = findReachableLeaves(graph, EMPTY_CONTRACT_HASH);\n if (leaves.length === 1) {\n targetHash = leaves[0];\n } else {\n diagnostics.push({\n code: 'MIGRATION.DIVERGED',\n severity: 'warn',\n message: 'There are multiple valid migration paths — you must select a target',\n hints: [\n \"Use '--to <contract>' to select a target\",\n \"Or 'prisma-next ref set <name> <hash>' to create one\",\n ],\n });\n }\n }\n\n let markerHash: string | undefined;\n let markerInvariants: readonly string[] = [];\n let mode: 'online' | 'offline' = 'offline';\n let allMarkers: ReadonlyMap<string, ContractMarkerRecordLike> | null = null;\n\n if (dbConnection && hasDriver) {\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n try {\n await client.connect(dbConnection);\n const marker = await client.readMarker();\n markerHash = marker?.storageHash;\n markerInvariants = marker?.invariants ?? [];\n mode = 'online';\n // Read every space's marker so the aggregate enumeration can\n // surface per-space marker state. `readAllMarkers` mirrors what\n // `db init` / `db update` already use to drive the multi-space\n // planner; here it powers the aggregate status output.\n //\n // Probe for the method first so we only swallow the\n // unsupported-method case: older family instances may not\n // implement `readAllMarkers` (per-space enumeration then falls\n // back to \"marker unknown\"). Real query / runtime errors from\n // an instance that *does* expose the method must propagate up\n // — otherwise transient DB failures would silently degrade\n // status to \"markers unknown\".\n if (typeof client.readAllMarkers === 'function') {\n allMarkers = await client.readAllMarkers();\n } else {\n // Leaving `allMarkers` as `null` signals \"unknown\" to the\n // aggregate loader (an empty `Map` would instead mean \"every\n // space has no marker\", which is a different condition).\n allMarkers = null;\n }\n } catch {\n if (!flags.json && !flags.quiet) {\n ui.warn('Could not connect to database — showing offline status');\n }\n } finally {\n await client.close();\n }\n }\n\n if (fromOverrideHash !== undefined) {\n markerHash = fromOverrideHash;\n mode = 'offline';\n allMarkers = null;\n }\n\n // Build the aggregate enumeration of contract spaces. Lossy on\n // failure (extensions are simply omitted) so the existing\n // single-space app pipeline below still runs even if extensions\n // can't be loaded — a strict failure here would degrade the\n // load-bearing app-space output for unrelated reasons.\n const contractRawForAggregate = await loadContractRawSafely(config);\n let aggregateSpaces: readonly MigrationStatusSpaceEntry[] = [];\n if (contractRawForAggregate !== null) {\n // The aggregate loader needs a typed-Contract producer. Build a\n // real control stack so `deserializeContract` runs against a fully\n // composed family instance — descriptors that read stack members\n // during construction (e.g. codec lookups) get a consistent view.\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n try {\n aggregateSpaces = await loadAggregateStatusSpaces({\n targetId: config.target.targetId,\n migrationsDir,\n appContractRaw: contractRawForAggregate,\n extensionPacks: config.extensionPacks ?? [],\n deserializeContract: (json: unknown) => familyInstance.deserializeContract(json),\n markersBySpace: allMarkers,\n });\n } catch {\n // Loader failure short-circuits silently — the existing\n // single-space app pipeline below still runs.\n aggregateSpaces = [];\n }\n }\n const totalPendingAcrossSpaces = computeTotalPendingAcrossSpaces(aggregateSpaces);\n\n // Pre-check unknown invariants. Online: union the graph's declared\n // invariants with the marker's recorded set so a retired-but-applied\n // invariant doesn't surface as MIGRATION.UNKNOWN_INVARIANT — apply would\n // route fine because marker subtraction empties `effectiveRequired`.\n // Offline: keep the check graph-strict (the marker is unknown, and a\n // missing declarer is the dominant signal we can offer).\n if (activeRefEntry && activeRefEntry.invariants.length > 0) {\n const declared = collectDeclaredInvariants(graph);\n const known = new Set<string>(declared);\n if (mode === 'online') {\n for (const id of markerInvariants) known.add(id);\n }\n const unknown = activeRefEntry.invariants.filter((id) => !known.has(id));\n if (unknown.length > 0) {\n return notOk(\n mapMigrationToolsError(\n errorUnknownInvariant({\n ...ifDefined('refName', activeRefName),\n unknown,\n declared: [...declared].sort(),\n }),\n ),\n );\n }\n }\n\n // Marker exists but is not in the migration graph and doesn't match the\n // contract hash. The DB is at an unknown state relative to the graph.\n // Bail out early with a clear diagnostic instead of rendering a confusing\n // graph with no statuses.\n //\n // When marker === contract (both off-graph), the DB matches the current\n // contract — proceed normally; the detached contract node will carry both\n // the db and contract markers.\n if (\n mode === 'online' &&\n markerHash !== undefined &&\n !graph.nodes.has(markerHash) &&\n markerHash !== contractHash\n ) {\n const hints: string[] = [];\n if (graph.nodes.has(contractHash)) {\n hints.push(\n \"Run 'prisma-next db sign' to overwrite the marker if the database already matches the contract\",\n \"Run 'prisma-next db update' to push the current contract to the database\",\n \"Run 'prisma-next contract infer' to make your contract match the database\",\n \"Run 'prisma-next db verify' to inspect the database state\",\n );\n } else {\n hints.push(\n \"Run 'prisma-next db update' to push the current contract to the database\",\n \"Run 'prisma-next contract infer' to make your contract match the database\",\n \"Run 'prisma-next db verify' to inspect the database state\",\n );\n }\n diagnostics.push({\n code: 'MIGRATION.MARKER_NOT_IN_HISTORY',\n severity: 'warn',\n message:\n 'Database was updated outside the migration system (marker does not match any migration)',\n hints,\n });\n return ok({\n ok: true,\n mode,\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: `${bundles.length} migration(s) on disk`,\n diagnostics,\n markerHash,\n requiredInvariants,\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n });\n }\n\n if (mode === 'online' && markerHash === undefined) {\n diagnostics.push({\n code: 'MIGRATION.NO_MARKER',\n severity: 'warn',\n message: 'Database has not been initialized — no migration marker found',\n hints: [\"Run 'prisma-next migrate' to apply pending migrations\"],\n });\n }\n\n // Contract diagnostic — fires when no migration produces the current contract hash.\n // Suppressed when: (a) graph is diverged (MIGRATION.DIVERGED already guides the user),\n // (b) marker === contract and both off-graph (marker-not-in-graph diagnostic covers it).\n if (\n targetHash &&\n contractHash !== EMPTY_CONTRACT_HASH &&\n !graph.nodes.has(contractHash) &&\n markerHash !== contractHash\n ) {\n diagnostics.push({\n code: 'CONTRACT.AHEAD',\n severity: 'warn',\n message: 'Contract has changed since the last migration was planned',\n hints: [\"Run 'prisma-next migration plan' to generate a migration for the current contract\"],\n });\n }\n\n if (!targetHash) {\n return ok({\n ok: true,\n mode,\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: `${bundles.length} migration(s) on disk`,\n diagnostics,\n ...ifDefined('markerHash', markerHash),\n requiredInvariants,\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n graph,\n bundles,\n diverged: true,\n });\n }\n\n const chain = resolveDisplayChain(graph, targetHash, markerHash);\n\n if (!chain) {\n return notOk(\n errorRuntime('Cannot reconstruct migration history', {\n why: `No path from ${EMPTY_CONTRACT_HASH} to target ${targetHash}`,\n fix: 'The migration history may have gaps. Check the migrations directory for missing or corrupted packages.',\n }),\n );\n }\n\n const edgeStatuses = deriveEdgeStatuses(graph, targetHash, contractHash, markerHash, mode);\n const entries = buildMigrationEntries(chain, bundles, mode, markerHash, edgeStatuses);\n\n const pendingCount = edgeStatuses.filter((e) => e.status === 'pending').length;\n const appliedCount = edgeStatuses.filter((e) => e.status === 'applied').length;\n\n let appliedInvariants: readonly string[] | undefined;\n let missingInvariants: readonly string[] | undefined;\n let effectiveRequired = new Set<string>();\n if (mode === 'online') {\n // Mirrors `migrate.ts`: compute `effectiveRequired = required −\n // marker.invariants` directly, then derive the display fields from it.\n // `appliedInvariants` is the intersection (`required ∩ marker`), which\n // is what JSON consumers see for the active ref; the unfiltered set\n // lives on `marker.invariants`.\n const markerSet = new Set(markerInvariants);\n effectiveRequired = new Set(requiredInvariants.filter((id) => !markerSet.has(id)));\n appliedInvariants = requiredInvariants.filter((id) => markerSet.has(id));\n missingInvariants = [...effectiveRequired].sort();\n }\n\n // The marker can match the structural target while still missing required\n // invariants — for example, a self-edge that provides X, applied via a ref\n // declaring X. `pendingCount` (structural) says zero in that case but\n // `effectiveRequired` is non-empty, so up-to-date messaging would mislead.\n const hasInvariantWork = effectiveRequired.size > 0;\n const missingList = [...effectiveRequired].sort().join(', ');\n\n let summary: string;\n if (mode === 'online') {\n if (markerHash !== undefined && !graph.nodes.has(markerHash) && markerHash === contractHash) {\n summary = `${bundles.length} migration(s) on disk`;\n } else if (activeRefHash && activeRefName && markerHash !== undefined) {\n const distance = summarizeRefDistance(graph, markerHash, activeRefHash, activeRefName);\n summary = hasInvariantWork ? `${distance} — missing invariant(s): ${missingList}` : distance;\n } else if (pendingCount === 0 && !hasInvariantWork) {\n summary = `Database is up to date (${appliedCount} migration${appliedCount !== 1 ? 's' : ''} applied)`;\n } else if (pendingCount === 0 && hasInvariantWork) {\n summary = `Missing invariant(s): ${missingList} — run 'prisma-next migrate --to ${activeRefName ?? '<ref>'}' to apply`;\n } else if (markerHash === undefined) {\n summary = `${pendingCount} pending migration(s) — database has no marker`;\n } else {\n summary = `${pendingCount} pending migration(s) — run 'prisma-next migrate' to apply`;\n }\n } else {\n summary = `${entries.length} migration(s) on disk`;\n }\n\n let pathDecision: MigrationStatusResult['pathDecision'];\n let routingUnreachable = false;\n if (mode === 'online') {\n const originHash = markerHash ?? EMPTY_CONTRACT_HASH;\n const outcome = findPathWithDecision(graph, originHash, targetHash, {\n ...ifDefined('refName', activeRefName),\n required: effectiveRequired,\n });\n if (outcome.kind === 'ok') {\n pathDecision = toPathDecisionResult(outcome.decision);\n } else if (outcome.kind === 'unsatisfiable') {\n return notOk(\n mapMigrationToolsError(\n errorNoInvariantPath({\n ...ifDefined('refName', activeRefName),\n required: [...effectiveRequired].sort(),\n missing: outcome.missing,\n structuralPath: outcome.structuralPath.map(toStructuralEdge),\n }),\n ),\n );\n } else {\n // outcome.kind === 'unreachable' — origin (marker) has no structural\n // path to the active target. `pendingCount` and `hasInvariantWork`\n // both report zero in this case, but emitting MIGRATION.UP_TO_DATE\n // would be wrong: the database simply cannot reach the requested\n // ref/contract from its current state. Suppress UP_TO_DATE below.\n routingUnreachable = true;\n }\n }\n\n if (mode === 'online') {\n if (markerHash !== undefined && !graph.nodes.has(markerHash) && markerHash === contractHash) {\n diagnostics.push({\n code: 'MIGRATION.MARKER_NOT_IN_HISTORY',\n severity: 'warn',\n message: 'Database matches the current contract but was updated directly (not via migrate)',\n hints: [\"Run 'prisma-next migration plan' to plan a migration to your current contract\"],\n });\n } else if (pendingCount > 0) {\n diagnostics.push({\n code: 'MIGRATION.DATABASE_BEHIND',\n severity: 'info',\n message: `${pendingCount} migration(s) pending`,\n hints: [\"Run 'prisma-next migrate' to apply pending migrations\"],\n });\n } else if (hasInvariantWork) {\n diagnostics.push({\n code: 'MIGRATION.INVARIANTS_PENDING',\n severity: 'info',\n message: `Missing required invariant(s): ${missingList}`,\n hints: [\n `Run 'prisma-next migrate --to ${activeRefName ?? '<ref>'}' to apply a path that covers the required invariants`,\n ],\n });\n } else if (!routingUnreachable) {\n diagnostics.push({\n code: 'MIGRATION.UP_TO_DATE',\n severity: 'info',\n message: 'Database is up to date',\n hints: [],\n });\n }\n }\n\n const result: MigrationStatusResult = {\n ok: true,\n mode,\n migrations: entries,\n targetHash,\n contractHash,\n summary,\n diagnostics,\n ...ifDefined('markerHash', markerHash),\n requiredInvariants,\n ...ifDefined('appliedInvariants', appliedInvariants),\n ...ifDefined('missingInvariants', missingInvariants),\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n ...ifDefined('pathDecision', pathDecision),\n graph,\n bundles,\n edgeStatuses,\n ...ifDefined('activeRefHash', activeRefHash),\n ...ifDefined('activeRefName', activeRefName),\n spaces: aggregateSpaces,\n ...ifDefined('totalPendingAcrossSpaces', totalPendingAcrossSpaces),\n };\n return ok(result);\n}\n\nexport function createMigrationStatusCommand(): Command {\n const command = new Command('status');\n setCommandDescriptions(\n command,\n 'Show migration path and pending status',\n 'Shows which migrations are pending between the database marker and\\n' +\n 'the target contract. Requires a database connection for live status.\\n' +\n 'Use `migration graph` for topology, `migration log` for history,\\n' +\n 'and `migration list` for on-disk enumeration.',\n );\n setCommandExamples(command, [\n 'prisma-next migration status --db $DATABASE_URL',\n 'prisma-next migration status --to production --db $DATABASE_URL',\n ]);\n setCommandSeeAlso(command, [\n { verb: 'migration log', oneLiner: 'Show executed migration history' },\n { verb: 'migration list', oneLiner: 'List on-disk migrations' },\n { verb: 'migration graph', oneLiner: 'Show the migration graph topology' },\n { verb: 'migration show', oneLiner: 'Display migration package contents' },\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option(\n '--to <contract>',\n 'Target contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)',\n )\n .option(\n '--from <contract>',\n 'Origin contract reference; same grammar as --to. Supplying --from switches to offline path computation.',\n )\n .action(async (options: MigrationStatusOptions) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n const result = await executeMigrationStatusCommand(options, flags, ui);\n\n const exitCode = handleResult(result, flags, ui, (statusResult) => {\n if (flags.json) {\n const {\n graph: _graph,\n bundles: _bundles,\n edgeStatuses: _edgeStatuses,\n activeRefHash: _activeRefHash,\n activeRefName: _activeRefName,\n diverged: _diverged,\n ...jsonResult\n } = statusResult;\n ui.output(JSON.stringify(jsonResult, null, 2));\n } else if (!flags.quiet) {\n const colorize = flags.color !== false;\n\n if (statusResult.graph) {\n const renderInput = migrationGraphToRenderInput({\n graph: statusResult.graph,\n mode: statusResult.mode,\n markerHash: statusResult.markerHash,\n contractHash: statusResult.contractHash,\n refs: statusResult.refs,\n activeRefHash: statusResult.activeRefHash,\n activeRefName: statusResult.activeRefName,\n edgeStatuses: statusResult.edgeStatuses,\n });\n\n const graphToRender = statusResult.diverged\n ? renderInput.graph\n : extractRelevantSubgraph(renderInput.graph, renderInput.relevantPaths);\n const dagreOptions = isLinearGraph(graphToRender) ? { ranksep: 1 } : undefined;\n const renderOptions = {\n ...renderInput.options,\n colorize,\n ...ifDefined('dagreOptions', dagreOptions),\n };\n const graphOutput = graphRenderer.render(graphToRender, renderOptions);\n ui.log(graphOutput);\n if (statusResult.mode === 'online') {\n ui.log(formatLegend(colorize));\n }\n }\n ui.log('');\n ui.log(formatStatusSummary(statusResult, colorize));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n\nfunction formatLegend(colorize: boolean): string {\n const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);\n const parts = [\n `${c(cyan, '✓')} applied`,\n `${c(yellow, '⧗')} pending`,\n `${c(magenta, '✗')} unreachable`,\n ];\n return c(dim, parts.join(' '));\n}\n\nexport function formatStatusSummary(result: MigrationStatusResult, colorize: boolean): string {\n const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);\n const lines: string[] = [];\n\n const hasUnknown = result.migrations.some((e) => e.status === 'unknown');\n const pendingCount = result.migrations.filter((e) => e.status === 'pending').length;\n\n const hasWarnings = result.diagnostics?.some((d) => d.severity === 'warn') ?? false;\n // INVARIANTS_PENDING is filed at severity 'info' (per ADR 208) so the\n // warn-severity check above doesn't see it. It still represents pending\n // work, so it must promote the summary off the success icon.\n const hasInvariantPending =\n result.diagnostics?.some((d) => d.code === 'MIGRATION.INVARIANTS_PENDING') ?? false;\n\n if (result.mode === 'online') {\n if (hasUnknown || hasWarnings) {\n lines.push(`${c(yellow, '⚠')} ${result.summary}`);\n } else if (pendingCount === 0 && !hasInvariantPending) {\n lines.push(`${c(cyan, '✔')} ${result.summary}`);\n } else {\n lines.push(`${c(yellow, '⧗')} ${result.summary}`);\n }\n } else {\n lines.push(result.summary);\n }\n\n if (result.requiredInvariants.length > 0) {\n if (result.appliedInvariants !== undefined && result.missingInvariants !== undefined) {\n lines.push(`${c(dim, 'applied ')}${formatInvariantList(result.appliedInvariants)}`);\n lines.push(`${c(dim, 'missing ')}${formatInvariantList(result.missingInvariants)}`);\n } else {\n lines.push(`${c(dim, 'applied ')}(unknown — connect a database to evaluate)`);\n }\n }\n\n const warnings = result.diagnostics?.filter((d) => d.severity === 'warn') ?? [];\n for (const diag of warnings) {\n lines.push(`${c(yellow, '⚠')} ${diag.message}`);\n for (const hint of diag.hints) {\n lines.push(` ${c(dim, hint)}`);\n }\n }\n\n // Per-space section. Suppressed when there's no extension space —\n // the legacy single-space output already covers the app member.\n // When extensions exist, render every space (including the app)\n // for consistency, plus a cross-space pending total + apply hint.\n if (result.spaces?.some((s) => s.kind === 'extension')) {\n const total = result.totalPendingAcrossSpaces ?? 0;\n lines.push('');\n lines.push(c(dim, 'spaces'));\n for (const space of result.spaces) {\n lines.push(formatSpaceLine(space, c));\n }\n if (total > 0) {\n lines.push('');\n lines.push(\n `${c(yellow, '⧗')} ${total} pending migration(s) across ${result.spaces.length} space(s) — run 'prisma-next migrate' to apply`,\n );\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction formatSpaceLine(\n space: MigrationStatusSpaceEntry,\n c: (fn: (s: string) => string, s: string) => string,\n): string {\n const glyph = (() => {\n if (space.status === 'up-to-date' || space.status === 'no-marker') return c(cyan, '✓');\n if (space.status === 'pending') return c(yellow, '⧗');\n if (space.status === 'unreachable' || space.status === 'never-planned') return c(magenta, '✗');\n return ' ';\n })();\n const tag = space.kind === 'app' ? '[app]' : '[ext]';\n const head = space.headHash.slice(0, 8);\n const marker =\n space.markerHash === undefined\n ? '(unknown)'\n : space.markerHash === null\n ? '(no marker)'\n : space.markerHash.slice(0, 8);\n const pending =\n space.pendingCount === undefined\n ? ''\n : space.pendingCount === 0\n ? c(dim, ' (up to date)')\n : c(yellow, ` (${space.pendingCount} pending)`);\n return ` ${glyph} ${c(dim, tag)} ${space.spaceId} → head ${c(dim, head)}, marker ${c(dim, marker)}${pending}`;\n}\n\nfunction formatInvariantList(ids: readonly string[]): string {\n return ids.length === 0 ? '(none)' : ids.join(', ');\n}\n\nfunction summarizeRefDistance(\n graph: MigrationGraph,\n markerHash: string,\n refHash: string,\n refName: string,\n): string {\n if (markerHash === refHash) return `At ref \"${refName}\" target`;\n\n const pathToRef = findPath(graph, markerHash, refHash);\n if (pathToRef) return `${pathToRef.length} migration(s) behind ref \"${refName}\"`;\n\n const pathFromRef = findPath(graph, refHash, markerHash);\n if (pathFromRef) return `${pathFromRef.length} migration(s) ahead of ref \"${refName}\"`;\n\n return `No path between database marker and ref \"${refName}\" target`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6HA,SAAgB,gCACd,QACoB;CACpB,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,IAAI,QAAQ;CACZ,KAAK,MAAM,KAAK,QAAQ;EACtB,IAAI,EAAE,iBAAiB,KAAA,GAAW,OAAO,KAAA;EACzC,SAAS,EAAE;;CAEb,OAAO;;AAoET,SAAS,aAAa,KAGpB;CACA,IAAI,IAAI,WAAW,GAAG,OAAO;EAAE,SAAS;EAAS,gBAAgB;EAAO;CAExE,MAAM,0BAAU,IAAI,KAAqB;CACzC,KAAK,MAAM,MAAM,KACf,QAAQ,IAAI,GAAG,iBAAiB,QAAQ,IAAI,GAAG,eAAe,IAAI,KAAK,EAAE;CAG3E,MAAM,iBAAiB,QAAQ,IAAI,cAAc;CACjD,MAAM,QAAQ,IAAI;CAClB,MAAM,OAAO,UAAU,IAAI,OAAO;CAElC,IAAI,QAAQ,SAAS,GAEnB,OAAO;EAAE,SAAS,GAAG,MAAM,GAAG,KAAK,QADvB,CAAC,GAAG,QAAQ,MAAM,CAAC,CAAC,GACe;EAAI;EAAgB;CAGrE,MAAM,mBAAmB,QAAQ,IAAI,cAAc;CACnD,IAAI,kBACF,OAAO;EAAE,SAAS,GAAG,MAAM,GAAG,KAAK,IAAI,iBAAiB;EAAgB;EAAgB;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E,MAAM,cAAc,SAAS,OAAO,SAAS,WAAW;CACxD,IAAI,aAAa,OAAO,GAAG,YAAY,OAAO,8BAA8B,QAAQ;CAEpF,OAAO,4CAA4C,QAAQ"}
1
+ {"version":3,"file":"migration-status.mjs","names":[],"sources":["../../src/commands/migration-status.ts"],"sourcesContent":["import {\n createControlStack,\n type MigrationPlanOperation,\n} from '@prisma-next/framework-components/control';\nimport {\n type ContractMarkerRecordLike,\n graphWalkStrategy,\n} from '@prisma-next/migration-tools/aggregate';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport {\n errorNoInvariantPath,\n errorUnknownInvariant,\n MigrationToolsError,\n} from '@prisma-next/migration-tools/errors';\nimport type { MigrationEdge, MigrationGraph } from '@prisma-next/migration-tools/graph';\nimport {\n findPath,\n findPathWithDecision,\n findReachableLeaves,\n} from '@prisma-next/migration-tools/migration-graph';\nimport type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';\nimport { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';\nimport type { RefEntry, Refs } from '@prisma-next/migration-tools/refs';\nimport { readRefs } from '@prisma-next/migration-tools/refs';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { cyan, dim, magenta, yellow } from 'colorette';\nimport { Command } from 'commander';\n\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport {\n CliStructuredError,\n errorRuntime,\n errorUnexpected,\n mapMigrationToolsError,\n mapRefResolutionError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n collectDeclaredInvariants,\n loadMigrationPackages,\n maskConnectionUrl,\n readContractEnvelope,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n setCommandSeeAlso,\n toPathDecisionResult,\n toStructuralEdge,\n} from '../utils/command-helpers';\nimport {\n type BuildAggregateInputs,\n buildContractSpaceAggregate,\n} from '../utils/contract-space-aggregate-loader';\nimport {\n type EdgeStatus,\n type EdgeStatusKind,\n migrationGraphToRenderInput,\n} from '../utils/formatters/graph-migration-mapper';\nimport {\n extractRelevantSubgraph,\n graphRenderer,\n isLinearGraph,\n} from '../utils/formatters/graph-render';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport type { StatusDiagnostic, StatusRef } from '../utils/migration-types';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationStatusOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n readonly to?: string;\n readonly from?: string;\n}\n\nexport interface MigrationStatusEntry {\n readonly dirName: string;\n readonly from: string;\n readonly to: string;\n readonly migrationHash: string;\n readonly operationCount: number;\n readonly operationSummary: string;\n readonly hasDestructive: boolean;\n readonly status: EdgeStatusKind | 'unknown';\n}\n\n/**\n * Per-space status row in the aggregate-shaped status output.\n *\n * Surfaces, for each contract space:\n *\n * - `headHash`: the on-disk head ref's hash (where the space is going).\n * - `markerHash`: the live marker hash for the space, or null if no\n * marker has been written yet (greenfield, or pre-`migrate`).\n * - `pendingCount`: number of migration edges between marker and head.\n * Computed via {@link graphWalkStrategy}; 0 means the space is\n * already at head.\n * - `status`: convenience tag the formatter uses to pick a glyph.\n * `'never-planned'` is reserved for spaces with non-empty head but\n * no on-disk migrations — which shouldn't happen if the loader's\n * integrity check passes.\n *\n * Online-only fields (`markerHash`, `status`) are absent when the\n * command runs without a database connection.\n */\nexport interface MigrationStatusSpaceEntry {\n readonly spaceId: string;\n readonly kind: 'app' | 'extension';\n readonly headHash: string;\n readonly markerHash?: string | null;\n readonly pendingCount?: number;\n readonly status?: 'up-to-date' | 'pending' | 'no-marker' | 'never-planned' | 'unreachable';\n}\n\n/**\n * Sum per-space `pendingCount` into a cross-space total, but only when\n * every loaded space reports a defined `pendingCount`. Returns\n * `undefined` if any space is on the marker-unknown / offline path\n * (where `pendingCount` is intentionally absent), so JSON consumers can\n * distinguish \"no pending\" from \"unknown\".\n */\nexport function computeTotalPendingAcrossSpaces(\n spaces: readonly MigrationStatusSpaceEntry[],\n): number | undefined {\n if (spaces.length === 0) return undefined;\n let total = 0;\n for (const s of spaces) {\n if (s.pendingCount === undefined) return undefined;\n total += s.pendingCount;\n }\n return total;\n}\n\nexport type { StatusDiagnostic, StatusRef } from '../utils/migration-types';\n\nexport interface MigrationStatusResult {\n readonly ok: true;\n readonly mode: 'online' | 'offline';\n readonly migrations: readonly MigrationStatusEntry[];\n readonly markerHash?: string;\n readonly targetHash: string;\n readonly contractHash: string;\n readonly refs?: readonly StatusRef[];\n /** Required invariants from the active ref, sorted ascending. Always present (`[]` when no `--ref` or the ref declares none) — knowable offline. */\n readonly requiredInvariants: readonly string[];\n /**\n * Invariants the marker has applied at least once, intersected with\n * `requiredInvariants` for display relevance. JSON consumers see only the\n * subset overlapping the active ref's required set — the full unfiltered\n * marker invariant list lives on `marker.invariants` (control plane) and\n * is not surfaced here. Present only in `mode === 'online'`; absent when\n * offline (the marker is unknown, not empty).\n */\n readonly appliedInvariants?: readonly string[];\n /** required − applied. Present only in `mode === 'online'`; absent when offline. */\n readonly missingInvariants?: readonly string[];\n readonly pathDecision?: {\n readonly fromHash: string;\n readonly toHash: string;\n readonly alternativeCount: number;\n readonly tieBreakReasons: readonly string[];\n readonly refName?: string;\n readonly requiredInvariants: readonly string[];\n readonly satisfiedInvariants: readonly string[];\n readonly selectedPath: readonly {\n readonly dirName: string;\n readonly migrationHash: string;\n readonly from: string;\n readonly to: string;\n readonly invariants: readonly string[];\n }[];\n };\n readonly summary: string;\n readonly diagnostics: readonly StatusDiagnostic[];\n /**\n * Aggregate enumeration of every on-disk contract space (app +\n * extensions), in canonical schedule order (extensions\n * alphabetically, then app). Present whenever the aggregate loader\n * succeeded; absent in early-error returns (e.g. unreadable\n * migrations directory) where the existing diagnostics already\n * surface the failure.\n *\n * The legacy top-level fields (`migrations`, `markerHash`,\n * `targetHash`, `pathDecision`, …) describe the **app member**\n * specifically — back-compat with single-space callers. Per-space\n * detail for extension members lives only on this list.\n */\n readonly spaces?: readonly MigrationStatusSpaceEntry[];\n /** Cross-space pending-migration total (sum of `spaces[].pendingCount`). Present when `spaces` is. */\n readonly totalPendingAcrossSpaces?: number;\n readonly graph?: MigrationGraph;\n readonly bundles?: readonly OnDiskMigrationPackage[];\n readonly edgeStatuses?: readonly EdgeStatus[];\n readonly activeRefHash?: string;\n readonly activeRefName?: string;\n readonly diverged?: boolean;\n}\n\nfunction summarizeOps(ops: readonly MigrationPlanOperation[]): {\n summary: string;\n hasDestructive: boolean;\n} {\n if (ops.length === 0) return { summary: '0 ops', hasDestructive: false };\n\n const classes = new Map<string, number>();\n for (const op of ops) {\n classes.set(op.operationClass, (classes.get(op.operationClass) ?? 0) + 1);\n }\n\n const hasDestructive = classes.has('destructive');\n const count = ops.length;\n const noun = count === 1 ? 'op' : 'ops';\n\n if (classes.size === 1) {\n const cls = [...classes.keys()][0]!;\n return { summary: `${count} ${noun} (all ${cls})`, hasDestructive };\n }\n\n const destructiveCount = classes.get('destructive');\n if (destructiveCount) {\n return { summary: `${count} ${noun} (${destructiveCount} destructive)`, hasDestructive };\n }\n\n const parts = [...classes.entries()].map(([cls, n]) => `${n} ${cls}`);\n return { summary: `${count} ${noun} (${parts.join(', ')})`, hasDestructive };\n}\n\n/**\n * Derive per-edge status across the full graph using path analysis.\n *\n * - **applied**: edge is on the path from root to the DB marker\n * - **pending**: edge is on the path from the DB marker to the target\n * (and the marker is reachable from root, i.e. it's on the same branch)\n * - **unreachable**: edge is on the path from root to the target but the DB\n * marker is on a different branch — `apply` can't reach these edges\n * without the DB first moving to this branch\n *\n * Returns statuses only for edges that have a known status (skips offline\n * and edges not on any relevant path).\n *\n * @internal Exported for testing only.\n */\nexport function deriveEdgeStatuses(\n graph: MigrationGraph,\n targetHash: string,\n contractHash: string,\n markerHash: string | undefined,\n mode: 'online' | 'offline',\n): EdgeStatus[] {\n if (mode === 'offline') return [];\n\n const edgeKey = (e: MigrationEdge) => `${e.from}\\0${e.to}`;\n\n // No marker = empty DB — treat root as the marker (nothing applied, everything pending)\n const effectiveMarker = markerHash ?? EMPTY_CONTRACT_HASH;\n\n const appliedPath =\n markerHash !== undefined ? findPath(graph, EMPTY_CONTRACT_HASH, markerHash) : null;\n\n const pendingPath = findPath(graph, effectiveMarker, targetHash);\n const targetPath = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n\n const statuses: EdgeStatus[] = [];\n const assignedKeys = new Set<string>();\n\n // Applied edges (root → marker)\n if (appliedPath) {\n for (const e of appliedPath) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'applied' });\n }\n }\n\n // Pending edges (marker → target)\n if (pendingPath) {\n for (const e of pendingPath) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'pending' });\n }\n }\n\n // Pending edges beyond the target: target → contract (when target is a ref\n // and the contract is reachable from it)\n if (\n contractHash !== EMPTY_CONTRACT_HASH &&\n contractHash !== targetHash &&\n graph.nodes.has(contractHash)\n ) {\n const beyondTarget = findPath(graph, targetHash, contractHash);\n if (beyondTarget) {\n for (const e of beyondTarget) {\n if (!assignedKeys.has(edgeKey(e))) {\n assignedKeys.add(edgeKey(e));\n statuses.push({ dirName: e.dirName, status: 'pending' });\n }\n }\n }\n }\n\n // Unreachable edges: on the path from root to the target but neither applied\n // nor pending. This covers two cases:\n // 1. Marker can't reach target at all (different branch entirely)\n // 2. Marker reaches target via a different route, leaving some root→target\n // edges orphaned (e.g. a fork where one branch was applied and apply\n // will continue through the other)\n if (targetPath) {\n for (const e of targetPath) {\n if (!assignedKeys.has(edgeKey(e))) {\n statuses.push({ dirName: e.dirName, status: 'unreachable' });\n }\n }\n }\n\n return statuses;\n}\n\n/**\n * @param mode — 'online' if we connected to the database, 'offline' otherwise\n * @param markerHash — the marker hash from the database, or undefined if no marker row / offline\n */\nfunction buildMigrationEntries(\n chain: readonly MigrationEdge[],\n packages: readonly OnDiskMigrationPackage[],\n mode: 'online' | 'offline',\n markerHash: string | undefined,\n edgeStatuses?: readonly EdgeStatus[],\n): MigrationStatusEntry[] {\n const pkgByDirName = new Map(packages.map((p) => [p.dirName, p]));\n const statusByDirName = edgeStatuses\n ? new Map(edgeStatuses.map((e) => [e.dirName, e.status]))\n : undefined;\n\n const markerInChain = markerHash === undefined || chain.some((e) => e.to === markerHash);\n\n const entries: MigrationStatusEntry[] = [];\n let reachedMarker = mode === 'online' && markerHash === undefined;\n\n for (const migration of chain) {\n const pkg = pkgByDirName.get(migration.dirName);\n const ops = (pkg?.ops ?? []) as readonly MigrationPlanOperation[];\n const { summary, hasDestructive } = summarizeOps(ops);\n\n let status: EdgeStatusKind | 'unknown';\n const edgeStatus = statusByDirName?.get(migration.dirName);\n if (edgeStatus) {\n status = edgeStatus;\n } else if (mode === 'offline' || !markerInChain) {\n status = 'unknown';\n } else if (reachedMarker) {\n status = 'pending';\n } else {\n status = 'applied';\n }\n\n entries.push({\n dirName: migration.dirName,\n from: migration.from,\n to: migration.to,\n migrationHash: migration.migrationHash,\n operationCount: ops.length,\n operationSummary: summary,\n hasDestructive,\n status,\n });\n\n if (!reachedMarker && migration.to === markerHash) {\n reachedMarker = true;\n }\n }\n\n return entries;\n}\n\n/**\n * Resolve the migration chain to display in status output.\n *\n * When offline or the marker is at EMPTY, the chain is simply the shortest\n * path from EMPTY to the target — all structural paths are equivalent per\n * the spec, so the deterministic shortest path is the canonical display.\n *\n * When online with a non-empty marker, the chain routes *through* the marker:\n * EMPTY→marker (applied history) + marker→target (pending edges). This ensures\n * the displayed chain includes the marker node so applied/pending status is\n * correct. Without this, BFS from EMPTY to target could pick a shortest path\n * that bypasses the marker entirely (e.g. in a diamond graph), causing the\n * marker to appear \"diverged\" when it isn't.\n */\nfunction resolveDisplayChain(\n graph: MigrationGraph,\n targetHash: string,\n markerHash: string | undefined,\n): readonly MigrationEdge[] | null {\n if (markerHash === undefined) {\n return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n }\n\n const toMarker = findPath(graph, EMPTY_CONTRACT_HASH, markerHash);\n // Marker unreachable from EMPTY — show the target chain anyway.\n // The caller detects this via markerInChain and emits a divergence diagnostic.\n if (!toMarker) return findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n\n if (markerHash === targetHash) return toMarker;\n\n const fromMarker = findPath(graph, markerHash, targetHash);\n if (fromMarker) return [...toMarker, ...fromMarker];\n\n // Marker is ahead of target (or on a disconnected branch).\n // Try the inverse: target→marker. If it succeeds, the marker is ahead —\n // show the full chain from EMPTY through the target and on to the marker.\n const toTarget = findPath(graph, EMPTY_CONTRACT_HASH, targetHash);\n if (!toTarget) return null;\n\n const targetToMarker = findPath(graph, targetHash, markerHash);\n if (targetToMarker) return [...toTarget, ...targetToMarker];\n\n // Genuinely disconnected — show EMPTY→target; caller handles divergence diagnostic.\n return toTarget;\n}\n\n/**\n * Build the aggregate enumeration of contract spaces for the status\n * output. Loads the aggregate from disk (lossy on failure — extension\n * spaces are simply omitted, the existing single-space app behaviour\n * keeps working), reads per-space marker rows when online, and uses\n * {@link graphWalkStrategy} to compute each space's pending count.\n *\n * Sub-spec § `migration status` semantics — the aggregate-walking\n * version reports per-space marker + pending state alongside the\n * cross-space totals.\n */\nexport async function loadAggregateStatusSpaces(args: {\n readonly targetId: string;\n readonly migrationsDir: string;\n readonly appContractRaw: unknown;\n readonly extensionPacks: BuildAggregateInputs<string, string>['extensionPacks'];\n readonly deserializeContract: BuildAggregateInputs<string, string>['deserializeContract'];\n readonly markersBySpace: ReadonlyMap<string, ContractMarkerRecordLike> | null;\n}): Promise<readonly MigrationStatusSpaceEntry[]> {\n const loadInputs: BuildAggregateInputs<string, string> = {\n targetId: args.targetId,\n migrationsDir: args.migrationsDir,\n appContract: args.deserializeContract(args.appContractRaw),\n extensionPacks: args.extensionPacks,\n deserializeContract: args.deserializeContract,\n };\n\n const loaded = await buildContractSpaceAggregate(loadInputs);\n if (!loaded.ok) {\n // Loader failure (drift, layout violation, etc.) — surfacing it\n // as a status diagnostic would duplicate `migration plan`'s job.\n // The single-space app pipeline still runs; extensions are simply\n // not enumerated.\n return [];\n }\n const aggregate = loaded.value;\n\n const orderedMembers = [...aggregate.extensions, aggregate.app];\n const rows: MigrationStatusSpaceEntry[] = [];\n for (const member of orderedMembers) {\n const liveMarker = args.markersBySpace?.get(member.spaceId) ?? null;\n const isApp = member.spaceId === aggregate.app.spaceId;\n\n if (member.migrations.graph.nodes.size === 0) {\n rows.push({\n spaceId: member.spaceId,\n kind: isApp ? 'app' : 'extension',\n headHash: member.headRef.hash,\n ...(args.markersBySpace !== null\n ? {\n markerHash: liveMarker?.storageHash ?? null,\n status: member.headRef.hash === EMPTY_CONTRACT_HASH ? 'up-to-date' : 'never-planned',\n pendingCount: 0,\n }\n : {}),\n });\n continue;\n }\n\n if (args.markersBySpace === null) {\n rows.push({\n spaceId: member.spaceId,\n kind: isApp ? 'app' : 'extension',\n headHash: member.headRef.hash,\n });\n continue;\n }\n\n const walked = graphWalkStrategy({\n aggregateTargetId: aggregate.targetId,\n member,\n currentMarker: liveMarker,\n });\n let pendingCount = 0;\n let status: MigrationStatusSpaceEntry['status'];\n if (walked.kind === 'ok') {\n // Count pending *migrations* (graph edges), not operations: a\n // single authored migration that lowers to N ops or zero ops\n // both count as exactly one pending unit of work for the user.\n pendingCount = walked.result.migrationEdges?.length ?? 0;\n if (liveMarker === null) {\n status = pendingCount === 0 ? 'no-marker' : 'pending';\n } else {\n status = pendingCount === 0 ? 'up-to-date' : 'pending';\n }\n } else {\n status = 'unreachable';\n }\n\n rows.push({\n spaceId: member.spaceId,\n kind: isApp ? 'app' : 'extension',\n headHash: member.headRef.hash,\n markerHash: liveMarker?.storageHash ?? null,\n pendingCount,\n ...(status ? { status } : {}),\n });\n }\n return rows;\n}\n\n/**\n * Read the raw contract.json bytes from disk for the aggregate\n * loader. Returns `null` if the file is missing or unparseable —\n * the existing `readContractEnvelope` path will report the same\n * problem via a status diagnostic, no need to double-surface.\n */\nasync function loadContractRawSafely(config: {\n contract?: { output?: string };\n}): Promise<unknown | null> {\n try {\n const path = (await import('../utils/command-helpers')).resolveContractPath(config);\n const raw = await (await import('node:fs/promises')).readFile(path, 'utf-8');\n return JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n}\n\nasync function validateOnlineMarkerRead(\n config: Awaited<ReturnType<typeof loadConfig>>,\n dbConnection: unknown,\n): Promise<Result<void, CliStructuredError>> {\n const driver = config.driver;\n if (!driver) {\n return ok(undefined);\n }\n\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n try {\n await client.connect(dbConnection);\n await client.readMarker();\n return ok(undefined);\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read database marker: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nasync function executeMigrationStatusCommand(\n options: MigrationStatusOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<MigrationStatusResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { configPath, appMigrationsDir, appMigrationsRelative, migrationsDir, refsDir } =\n resolveMigrationPaths(options.config, config);\n\n const dbConnection = options.db ?? config.db?.connection;\n const hasDriver = !!config.driver;\n\n let activeRefName: string | undefined;\n let activeRefHash: string | undefined;\n let activeRefEntry: RefEntry | undefined;\n let allRefs: Refs = {};\n try {\n allRefs = await readRefs(refsDir);\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n\n let fromOverrideHash: string | undefined;\n\n if (options.to || options.from) {\n try {\n const { graph: earlyGraph } = await loadMigrationPackages(appMigrationsDir);\n\n if (options.to) {\n const refResult = parseContractRef(options.to, { graph: earlyGraph, refs: allRefs });\n if (!refResult.ok) {\n return notOk(mapRefResolutionError(refResult.failure));\n }\n activeRefHash = refResult.value.hash;\n if (refResult.value.provenance.kind === 'ref') {\n const resolvedRefName = refResult.value.provenance.refName;\n activeRefName = resolvedRefName;\n activeRefEntry = allRefs[resolvedRefName];\n }\n }\n\n if (options.from) {\n const fromResult = parseContractRef(options.from, { graph: earlyGraph, refs: allRefs });\n if (!fromResult.ok) {\n return notOk(mapRefResolutionError(fromResult.failure));\n }\n fromOverrideHash = fromResult.value.hash;\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n }\n\n const requiredInvariants: readonly string[] = [...(activeRefEntry?.invariants ?? [])].sort();\n\n const statusRefs: StatusRef[] = Object.entries(allRefs).map(([name, entry]) => ({\n name,\n hash: entry.hash,\n active: name === activeRefName,\n }));\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'migrations', value: appMigrationsRelative },\n ];\n if (dbConnection && hasDriver) {\n details.push({ label: 'database', value: maskConnectionUrl(String(dbConnection)) });\n }\n if (activeRefName) {\n details.push({ label: 'ref', value: activeRefName });\n }\n if (options.from) {\n details.push({ label: 'from', value: options.from });\n }\n if (activeRefEntry && activeRefEntry.invariants.length > 0) {\n details.push({\n label: 'required',\n value: formatInvariantList(activeRefEntry.invariants),\n });\n }\n const header = formatStyledHeader({\n command: 'migration status',\n description: 'Show migration history and applied status',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n const diagnostics: StatusDiagnostic[] = [];\n let contractHash: string = EMPTY_CONTRACT_HASH;\n try {\n const envelope = await readContractEnvelope(config);\n contractHash = envelope.storageHash;\n } catch (error) {\n diagnostics.push({\n code: 'CONTRACT.UNREADABLE',\n severity: 'warn',\n message: `Could not read contract: ${error instanceof Error ? error.message : 'unknown error'}`,\n hints: [\"Run 'prisma-next contract emit' to generate a valid contract\"],\n });\n }\n\n let bundles: readonly OnDiskMigrationPackage[];\n let graph: MigrationGraph;\n try {\n ({ bundles, graph } = await loadMigrationPackages(appMigrationsDir));\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read migrations directory: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n if (bundles.length === 0) {\n if (dbConnection && hasDriver) {\n const markerProbe = await validateOnlineMarkerRead(config, dbConnection);\n if (!markerProbe.ok) {\n return markerProbe;\n }\n }\n if (contractHash !== EMPTY_CONTRACT_HASH) {\n diagnostics.push({\n code: 'CONTRACT.AHEAD',\n severity: 'warn',\n message: 'No migration exists for the current contract',\n hints: [\n \"Run 'prisma-next migration plan' to generate a migration for the current contract\",\n ],\n });\n }\n return ok({\n ok: true,\n mode: dbConnection && hasDriver ? 'online' : 'offline',\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: 'No migrations found',\n diagnostics,\n requiredInvariants,\n });\n }\n\n let targetHash: string | undefined;\n\n if (activeRefHash) {\n targetHash = activeRefHash;\n } else if (graph.nodes.has(contractHash)) {\n targetHash = contractHash;\n } else {\n const leaves = findReachableLeaves(graph, EMPTY_CONTRACT_HASH);\n if (leaves.length === 1) {\n targetHash = leaves[0];\n } else {\n diagnostics.push({\n code: 'MIGRATION.DIVERGED',\n severity: 'warn',\n message: 'There are multiple valid migration paths — you must select a target',\n hints: [\n \"Use '--to <contract>' to select a target\",\n \"Or 'prisma-next ref set <name> <hash>' to create one\",\n ],\n });\n }\n }\n\n let markerHash: string | undefined;\n let markerInvariants: readonly string[] = [];\n let mode: 'online' | 'offline' = 'offline';\n let allMarkers: ReadonlyMap<string, ContractMarkerRecordLike> | null = null;\n\n if (dbConnection && hasDriver) {\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n try {\n await client.connect(dbConnection);\n const marker = await client.readMarker();\n markerHash = marker?.storageHash;\n markerInvariants = marker?.invariants ?? [];\n mode = 'online';\n // Read every space's marker so the aggregate enumeration can\n // surface per-space marker state. `readAllMarkers` mirrors what\n // `db init` / `db update` already use to drive the multi-space\n // planner; here it powers the aggregate status output.\n //\n // Probe for the method first so we only swallow the\n // unsupported-method case: older family instances may not\n // implement `readAllMarkers` (per-space enumeration then falls\n // back to \"marker unknown\"). Real query / runtime errors from\n // an instance that *does* expose the method must propagate up\n // — otherwise transient DB failures would silently degrade\n // status to \"markers unknown\".\n if (typeof client.readAllMarkers === 'function') {\n allMarkers = await client.readAllMarkers();\n } else {\n // Leaving `allMarkers` as `null` signals \"unknown\" to the\n // aggregate loader (an empty `Map` would instead mean \"every\n // space has no marker\", which is a different condition).\n allMarkers = null;\n }\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n if (!flags.json && !flags.quiet) {\n ui.warn('Could not connect to database — showing offline status');\n }\n } finally {\n await client.close();\n }\n }\n\n if (fromOverrideHash !== undefined) {\n markerHash = fromOverrideHash;\n mode = 'offline';\n allMarkers = null;\n }\n\n // Build the aggregate enumeration of contract spaces. Lossy on\n // failure (extensions are simply omitted) so the existing\n // single-space app pipeline below still runs even if extensions\n // can't be loaded — a strict failure here would degrade the\n // load-bearing app-space output for unrelated reasons.\n const contractRawForAggregate = await loadContractRawSafely(config);\n let aggregateSpaces: readonly MigrationStatusSpaceEntry[] = [];\n if (contractRawForAggregate !== null) {\n // The aggregate loader needs a typed-Contract producer. Build a\n // real control stack so `deserializeContract` runs against a fully\n // composed family instance — descriptors that read stack members\n // during construction (e.g. codec lookups) get a consistent view.\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n try {\n aggregateSpaces = await loadAggregateStatusSpaces({\n targetId: config.target.targetId,\n migrationsDir,\n appContractRaw: contractRawForAggregate,\n extensionPacks: config.extensionPacks ?? [],\n deserializeContract: (json: unknown) => familyInstance.deserializeContract(json),\n markersBySpace: allMarkers,\n });\n } catch {\n // Loader failure short-circuits silently — the existing\n // single-space app pipeline below still runs.\n aggregateSpaces = [];\n }\n }\n const totalPendingAcrossSpaces = computeTotalPendingAcrossSpaces(aggregateSpaces);\n\n // Pre-check unknown invariants. Online: union the graph's declared\n // invariants with the marker's recorded set so a retired-but-applied\n // invariant doesn't surface as MIGRATION.UNKNOWN_INVARIANT — apply would\n // route fine because marker subtraction empties `effectiveRequired`.\n // Offline: keep the check graph-strict (the marker is unknown, and a\n // missing declarer is the dominant signal we can offer).\n if (activeRefEntry && activeRefEntry.invariants.length > 0) {\n const declared = collectDeclaredInvariants(graph);\n const known = new Set<string>(declared);\n if (mode === 'online') {\n for (const id of markerInvariants) known.add(id);\n }\n const unknown = activeRefEntry.invariants.filter((id) => !known.has(id));\n if (unknown.length > 0) {\n return notOk(\n mapMigrationToolsError(\n errorUnknownInvariant({\n ...ifDefined('refName', activeRefName),\n unknown,\n declared: [...declared].sort(),\n }),\n ),\n );\n }\n }\n\n // Marker exists but is not in the migration graph and doesn't match the\n // contract hash. The DB is at an unknown state relative to the graph.\n // Bail out early with a clear diagnostic instead of rendering a confusing\n // graph with no statuses.\n //\n // When marker === contract (both off-graph), the DB matches the current\n // contract — proceed normally; the detached contract node will carry both\n // the db and contract markers.\n if (\n mode === 'online' &&\n markerHash !== undefined &&\n !graph.nodes.has(markerHash) &&\n markerHash !== contractHash\n ) {\n const hints: string[] = [];\n if (graph.nodes.has(contractHash)) {\n hints.push(\n \"Run 'prisma-next db sign' to overwrite the marker if the database already matches the contract\",\n \"Run 'prisma-next db update' to push the current contract to the database\",\n \"Run 'prisma-next contract infer' to make your contract match the database\",\n \"Run 'prisma-next db verify' to inspect the database state\",\n );\n } else {\n hints.push(\n \"Run 'prisma-next db update' to push the current contract to the database\",\n \"Run 'prisma-next contract infer' to make your contract match the database\",\n \"Run 'prisma-next db verify' to inspect the database state\",\n );\n }\n diagnostics.push({\n code: 'MIGRATION.MARKER_NOT_IN_HISTORY',\n severity: 'warn',\n message:\n 'Database was updated outside the migration system (marker does not match any migration)',\n hints,\n });\n return ok({\n ok: true,\n mode,\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: `${bundles.length} migration(s) on disk`,\n diagnostics,\n markerHash,\n requiredInvariants,\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n });\n }\n\n if (mode === 'online' && markerHash === undefined) {\n diagnostics.push({\n code: 'MIGRATION.NO_MARKER',\n severity: 'warn',\n message: 'Database has not been initialized — no migration marker found',\n hints: [\"Run 'prisma-next migrate' to apply pending migrations\"],\n });\n }\n\n // Contract diagnostic — fires when no migration produces the current contract hash.\n // Suppressed when: (a) graph is diverged (MIGRATION.DIVERGED already guides the user),\n // (b) marker === contract and both off-graph (marker-not-in-graph diagnostic covers it).\n if (\n targetHash &&\n contractHash !== EMPTY_CONTRACT_HASH &&\n !graph.nodes.has(contractHash) &&\n markerHash !== contractHash\n ) {\n diagnostics.push({\n code: 'CONTRACT.AHEAD',\n severity: 'warn',\n message: 'Contract has changed since the last migration was planned',\n hints: [\"Run 'prisma-next migration plan' to generate a migration for the current contract\"],\n });\n }\n\n if (!targetHash) {\n return ok({\n ok: true,\n mode,\n migrations: [],\n targetHash: EMPTY_CONTRACT_HASH,\n contractHash,\n summary: `${bundles.length} migration(s) on disk`,\n diagnostics,\n ...ifDefined('markerHash', markerHash),\n requiredInvariants,\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n graph,\n bundles,\n diverged: true,\n });\n }\n\n const chain = resolveDisplayChain(graph, targetHash, markerHash);\n\n if (!chain) {\n return notOk(\n errorRuntime('Cannot reconstruct migration history', {\n why: `No path from ${EMPTY_CONTRACT_HASH} to target ${targetHash}`,\n fix: 'The migration history may have gaps. Check the migrations directory for missing or corrupted packages.',\n }),\n );\n }\n\n const edgeStatuses = deriveEdgeStatuses(graph, targetHash, contractHash, markerHash, mode);\n const entries = buildMigrationEntries(chain, bundles, mode, markerHash, edgeStatuses);\n\n const pendingCount = edgeStatuses.filter((e) => e.status === 'pending').length;\n const appliedCount = edgeStatuses.filter((e) => e.status === 'applied').length;\n\n let appliedInvariants: readonly string[] | undefined;\n let missingInvariants: readonly string[] | undefined;\n let effectiveRequired = new Set<string>();\n if (mode === 'online') {\n // Mirrors `migrate.ts`: compute `effectiveRequired = required −\n // marker.invariants` directly, then derive the display fields from it.\n // `appliedInvariants` is the intersection (`required ∩ marker`), which\n // is what JSON consumers see for the active ref; the unfiltered set\n // lives on `marker.invariants`.\n const markerSet = new Set(markerInvariants);\n effectiveRequired = new Set(requiredInvariants.filter((id) => !markerSet.has(id)));\n appliedInvariants = requiredInvariants.filter((id) => markerSet.has(id));\n missingInvariants = [...effectiveRequired].sort();\n }\n\n // The marker can match the structural target while still missing required\n // invariants — for example, a self-edge that provides X, applied via a ref\n // declaring X. `pendingCount` (structural) says zero in that case but\n // `effectiveRequired` is non-empty, so up-to-date messaging would mislead.\n const hasInvariantWork = effectiveRequired.size > 0;\n const missingList = [...effectiveRequired].sort().join(', ');\n\n let summary: string;\n if (mode === 'online') {\n if (markerHash !== undefined && !graph.nodes.has(markerHash) && markerHash === contractHash) {\n summary = `${bundles.length} migration(s) on disk`;\n } else if (activeRefHash && activeRefName && markerHash !== undefined) {\n const distance = summarizeRefDistance(graph, markerHash, activeRefHash, activeRefName);\n summary = hasInvariantWork ? `${distance} — missing invariant(s): ${missingList}` : distance;\n } else if (pendingCount === 0 && !hasInvariantWork) {\n summary = `Database is up to date (${appliedCount} migration${appliedCount !== 1 ? 's' : ''} applied)`;\n } else if (pendingCount === 0 && hasInvariantWork) {\n summary = `Missing invariant(s): ${missingList} — run 'prisma-next migrate --to ${activeRefName ?? '<ref>'}' to apply`;\n } else if (markerHash === undefined) {\n summary = `${pendingCount} pending migration(s) — database has no marker`;\n } else {\n summary = `${pendingCount} pending migration(s) — run 'prisma-next migrate' to apply`;\n }\n } else {\n summary = `${entries.length} migration(s) on disk`;\n }\n\n let pathDecision: MigrationStatusResult['pathDecision'];\n let routingUnreachable = false;\n if (mode === 'online') {\n const originHash = markerHash ?? EMPTY_CONTRACT_HASH;\n const outcome = findPathWithDecision(graph, originHash, targetHash, {\n ...ifDefined('refName', activeRefName),\n required: effectiveRequired,\n });\n if (outcome.kind === 'ok') {\n pathDecision = toPathDecisionResult(outcome.decision);\n } else if (outcome.kind === 'unsatisfiable') {\n return notOk(\n mapMigrationToolsError(\n errorNoInvariantPath({\n ...ifDefined('refName', activeRefName),\n required: [...effectiveRequired].sort(),\n missing: outcome.missing,\n structuralPath: outcome.structuralPath.map(toStructuralEdge),\n }),\n ),\n );\n } else {\n // outcome.kind === 'unreachable' — origin (marker) has no structural\n // path to the active target. `pendingCount` and `hasInvariantWork`\n // both report zero in this case, but emitting MIGRATION.UP_TO_DATE\n // would be wrong: the database simply cannot reach the requested\n // ref/contract from its current state. Suppress UP_TO_DATE below.\n routingUnreachable = true;\n }\n }\n\n if (mode === 'online') {\n if (markerHash !== undefined && !graph.nodes.has(markerHash) && markerHash === contractHash) {\n diagnostics.push({\n code: 'MIGRATION.MARKER_NOT_IN_HISTORY',\n severity: 'warn',\n message: 'Database matches the current contract but was updated directly (not via migrate)',\n hints: [\"Run 'prisma-next migration plan' to plan a migration to your current contract\"],\n });\n } else if (pendingCount > 0) {\n diagnostics.push({\n code: 'MIGRATION.DATABASE_BEHIND',\n severity: 'info',\n message: `${pendingCount} migration(s) pending`,\n hints: [\"Run 'prisma-next migrate' to apply pending migrations\"],\n });\n } else if (hasInvariantWork) {\n diagnostics.push({\n code: 'MIGRATION.INVARIANTS_PENDING',\n severity: 'info',\n message: `Missing required invariant(s): ${missingList}`,\n hints: [\n `Run 'prisma-next migrate --to ${activeRefName ?? '<ref>'}' to apply a path that covers the required invariants`,\n ],\n });\n } else if (!routingUnreachable) {\n diagnostics.push({\n code: 'MIGRATION.UP_TO_DATE',\n severity: 'info',\n message: 'Database is up to date',\n hints: [],\n });\n }\n }\n\n const result: MigrationStatusResult = {\n ok: true,\n mode,\n migrations: entries,\n targetHash,\n contractHash,\n summary,\n diagnostics,\n ...ifDefined('markerHash', markerHash),\n requiredInvariants,\n ...ifDefined('appliedInvariants', appliedInvariants),\n ...ifDefined('missingInvariants', missingInvariants),\n ...(statusRefs.length > 0 ? { refs: statusRefs } : {}),\n ...ifDefined('pathDecision', pathDecision),\n graph,\n bundles,\n edgeStatuses,\n ...ifDefined('activeRefHash', activeRefHash),\n ...ifDefined('activeRefName', activeRefName),\n spaces: aggregateSpaces,\n ...ifDefined('totalPendingAcrossSpaces', totalPendingAcrossSpaces),\n };\n return ok(result);\n}\n\nexport function createMigrationStatusCommand(): Command {\n const command = new Command('status');\n setCommandDescriptions(\n command,\n 'Show migration path and pending status',\n 'Shows which migrations are pending between the database marker and\\n' +\n 'the target contract. Requires a database connection for live status.\\n' +\n 'Use `migration graph` for topology, `migration log` for history,\\n' +\n 'and `migration list` for on-disk enumeration.',\n );\n setCommandExamples(command, [\n 'prisma-next migration status --db $DATABASE_URL',\n 'prisma-next migration status --to production --db $DATABASE_URL',\n ]);\n setCommandSeeAlso(command, [\n { verb: 'migration log', oneLiner: 'Show executed migration history' },\n { verb: 'migration list', oneLiner: 'List on-disk migrations' },\n { verb: 'migration graph', oneLiner: 'Show the migration graph topology' },\n { verb: 'migration show', oneLiner: 'Display migration package contents' },\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option(\n '--to <contract>',\n 'Target contract reference (hash, prefix, ref name, migration dir name, <dir>^, or ./path)',\n )\n .option(\n '--from <contract>',\n 'Origin contract reference; same grammar as --to. Supplying --from switches to offline path computation.',\n )\n .action(async (options: MigrationStatusOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n\n const result = await executeMigrationStatusCommand(options, flags, ui);\n\n const exitCode = handleResult(result, flags, ui, (statusResult) => {\n if (flags.json) {\n const {\n graph: _graph,\n bundles: _bundles,\n edgeStatuses: _edgeStatuses,\n activeRefHash: _activeRefHash,\n activeRefName: _activeRefName,\n diverged: _diverged,\n ...jsonResult\n } = statusResult;\n ui.output(JSON.stringify(jsonResult, null, 2));\n } else if (!flags.quiet) {\n const colorize = flags.color !== false;\n\n if (statusResult.graph) {\n const renderInput = migrationGraphToRenderInput({\n graph: statusResult.graph,\n mode: statusResult.mode,\n markerHash: statusResult.markerHash,\n contractHash: statusResult.contractHash,\n refs: statusResult.refs,\n activeRefHash: statusResult.activeRefHash,\n activeRefName: statusResult.activeRefName,\n edgeStatuses: statusResult.edgeStatuses,\n });\n\n const graphToRender = statusResult.diverged\n ? renderInput.graph\n : extractRelevantSubgraph(renderInput.graph, renderInput.relevantPaths);\n const dagreOptions = isLinearGraph(graphToRender) ? { ranksep: 1 } : undefined;\n const renderOptions = {\n ...renderInput.options,\n colorize,\n ...ifDefined('dagreOptions', dagreOptions),\n };\n const graphOutput = graphRenderer.render(graphToRender, renderOptions);\n ui.log(graphOutput);\n if (statusResult.mode === 'online') {\n ui.log(formatLegend(colorize));\n }\n }\n ui.log('');\n ui.log(formatStatusSummary(statusResult, colorize));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n\nfunction formatLegend(colorize: boolean): string {\n const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);\n const parts = [\n `${c(cyan, '✓')} applied`,\n `${c(yellow, '⧗')} pending`,\n `${c(magenta, '✗')} unreachable`,\n ];\n return c(dim, parts.join(' '));\n}\n\nexport function formatStatusSummary(result: MigrationStatusResult, colorize: boolean): string {\n const c = (fn: (s: string) => string, s: string) => (colorize ? fn(s) : s);\n const lines: string[] = [];\n\n const hasUnknown = result.migrations.some((e) => e.status === 'unknown');\n const pendingCount = result.migrations.filter((e) => e.status === 'pending').length;\n\n const hasWarnings = result.diagnostics?.some((d) => d.severity === 'warn') ?? false;\n // INVARIANTS_PENDING is filed at severity 'info' (per ADR 208) so the\n // warn-severity check above doesn't see it. It still represents pending\n // work, so it must promote the summary off the success icon.\n const hasInvariantPending =\n result.diagnostics?.some((d) => d.code === 'MIGRATION.INVARIANTS_PENDING') ?? false;\n\n if (result.mode === 'online') {\n if (hasUnknown || hasWarnings) {\n lines.push(`${c(yellow, '⚠')} ${result.summary}`);\n } else if (pendingCount === 0 && !hasInvariantPending) {\n lines.push(`${c(cyan, '✔')} ${result.summary}`);\n } else {\n lines.push(`${c(yellow, '⧗')} ${result.summary}`);\n }\n } else {\n lines.push(result.summary);\n }\n\n if (result.requiredInvariants.length > 0) {\n if (result.appliedInvariants !== undefined && result.missingInvariants !== undefined) {\n lines.push(`${c(dim, 'applied ')}${formatInvariantList(result.appliedInvariants)}`);\n lines.push(`${c(dim, 'missing ')}${formatInvariantList(result.missingInvariants)}`);\n } else {\n lines.push(`${c(dim, 'applied ')}(unknown — connect a database to evaluate)`);\n }\n }\n\n const warnings = result.diagnostics?.filter((d) => d.severity === 'warn') ?? [];\n for (const diag of warnings) {\n lines.push(`${c(yellow, '⚠')} ${diag.message}`);\n for (const hint of diag.hints) {\n lines.push(` ${c(dim, hint)}`);\n }\n }\n\n // Per-space section. Suppressed when there's no extension space —\n // the legacy single-space output already covers the app member.\n // When extensions exist, render every space (including the app)\n // for consistency, plus a cross-space pending total + apply hint.\n if (result.spaces?.some((s) => s.kind === 'extension')) {\n const total = result.totalPendingAcrossSpaces ?? 0;\n lines.push('');\n lines.push(c(dim, 'spaces'));\n for (const space of result.spaces) {\n lines.push(formatSpaceLine(space, c));\n }\n if (total > 0) {\n lines.push('');\n lines.push(\n `${c(yellow, '⧗')} ${total} pending migration(s) across ${result.spaces.length} space(s) — run 'prisma-next migrate' to apply`,\n );\n }\n }\n\n return lines.join('\\n');\n}\n\nfunction formatSpaceLine(\n space: MigrationStatusSpaceEntry,\n c: (fn: (s: string) => string, s: string) => string,\n): string {\n const glyph = (() => {\n if (space.status === 'up-to-date' || space.status === 'no-marker') return c(cyan, '✓');\n if (space.status === 'pending') return c(yellow, '⧗');\n if (space.status === 'unreachable' || space.status === 'never-planned') return c(magenta, '✗');\n return ' ';\n })();\n const tag = space.kind === 'app' ? '[app]' : '[ext]';\n const head = space.headHash.slice(0, 8);\n const marker =\n space.markerHash === undefined\n ? '(unknown)'\n : space.markerHash === null\n ? '(no marker)'\n : space.markerHash.slice(0, 8);\n const pending =\n space.pendingCount === undefined\n ? ''\n : space.pendingCount === 0\n ? c(dim, ' (up to date)')\n : c(yellow, ` (${space.pendingCount} pending)`);\n return ` ${glyph} ${c(dim, tag)} ${space.spaceId} → head ${c(dim, head)}, marker ${c(dim, marker)}${pending}`;\n}\n\nfunction formatInvariantList(ids: readonly string[]): string {\n return ids.length === 0 ? '(none)' : ids.join(', ');\n}\n\nfunction summarizeRefDistance(\n graph: MigrationGraph,\n markerHash: string,\n refHash: string,\n refName: string,\n): string {\n if (markerHash === refHash) return `At ref \"${refName}\" target`;\n\n const pathToRef = findPath(graph, markerHash, refHash);\n if (pathToRef) return `${pathToRef.length} migration(s) behind ref \"${refName}\"`;\n\n const pathFromRef = findPath(graph, refHash, markerHash);\n if (pathFromRef) return `${pathFromRef.length} migration(s) ahead of ref \"${refName}\"`;\n\n return `No path between database marker and ref \"${refName}\" target`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6HA,SAAgB,gCACd,QACoB;CACpB,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,IAAI,QAAQ;CACZ,KAAK,MAAM,KAAK,QAAQ;EACtB,IAAI,EAAE,iBAAiB,KAAA,GAAW,OAAO,KAAA;EACzC,SAAS,EAAE;;CAEb,OAAO;;AAoET,SAAS,aAAa,KAGpB;CACA,IAAI,IAAI,WAAW,GAAG,OAAO;EAAE,SAAS;EAAS,gBAAgB;EAAO;CAExE,MAAM,0BAAU,IAAI,KAAqB;CACzC,KAAK,MAAM,MAAM,KACf,QAAQ,IAAI,GAAG,iBAAiB,QAAQ,IAAI,GAAG,eAAe,IAAI,KAAK,EAAE;CAG3E,MAAM,iBAAiB,QA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jVLJV.mjs";
1
+ import { t as CliStructuredError } from "../cli-errors-Czmx92Zy.mjs";
2
2
  import { Command } from "commander";
3
3
  import { Result } from "@prisma-next/utils/result";
4
4
  import { RefEntry } from "@prisma-next/migration-tools/refs";