My Apex code that does a Metadata.Operations.enqueueDeployment
of some custom metadata records including in a 2GP managed package worked in a scratch org that had the namespace set, but fails when run as unpackaged code or when run from a second 2GP beta package that is using the same namespace with this error message:
Cannot create a new component with the namespace: xxx. Only components in the same namespace as the organization can be created through the API
I do have "Deploy Metadata from Non-Certified Package Versions via Apex" checked. And both packages are installed. Also the unit tests in the beta package pass. Note I am launching the failing code from the developer console i.e. running:
xxx.Migrator.migate();
Any suggestions for how to solve or what else to try?