Here are a few references to merit from the CCC:
**
We can have merit in God’s sight only because of God’s free plan to associate man with the work of his grace. Merit is to be ascribed in the first place to the grace of God, and secondly to man’s collaboration. Man’s merit is due to God.
2026 The grace of the Holy Spirit can confer true merit on us, by virtue of our adoptive filiation, and in accordance with God’s gratuitous justice. Charity is the principal source of merit in us before God.
2027 No one can merit the initial grace which is at the origin of conversion. Moved by the Holy Spirit, we can merit for ourselves and for others all the graces needed to attain eternal life, as well as necessary temporal goods.
I learned quite some years ago from the Baltimore Catechism that one cannot “merit” while in the state of mortal sin, for the works do not flow from being in the state of sanctifying grace. So if this condition remains, one could lose everything if they die unrepentant.
Note below, that good works can also be wrought through God’s inspiration flowing from His “actual” graces. I’m not sure these are meritorious, per se.
**
** Sanctifying grace makes us “pleasing to God.” Charisms, special graces of the Holy Spirit, are oriented to sanctifying grace and are intended for the common good of the Church. God also acts through many actual graces, to be distinguished from habitual grace which is permanent in us.
After one returns to the state of sanctifying grace through a worthy confession, it is my understanding that their former good works are retained and are still “meritorious.” Rev. 14:13, says
"And I heard a voice from heaven, saying to me: Write: Blessed are the dead, who die in the Lord. From henceforth now, saith the Spirit, that they may rest from their labours; for their works follow them."
**