How can I improve my mediation analysis to account for repeated measures (2 time points)

We are currently trying to test a mediation model with repeated measures (two time points) for a 1-1-1 level analysis.

My independent (TreatmentF), mediator (Ambivalence), and dependent variable (Intention) are all measured on the individual level. All variables were measured two times: before and after the experiment. I am trying to write code for a mediation.

Below, I have written two simple mediations separately for the two time-points To and T1 (fitmed1 for Period==1 and fitmed2 for Period==2). In addition, I wrote a third mediator analysis, where I use the mediator ambivalence at T0 as a moderator for the mediator analysis at T1. It all works. However, I should think it would be possible to write a more concise code for a mediator analyses with repeated measures, i.e., a multilevel mediation analysis approach that allows for the nested structure of the data (i.e., repeated measures within individuals). Chat GTP suggests SEM.

So far, I failed to see whether this is possible and how I should adjust the code. Any help appreciated!

model <- '# direct effect
Intention ~ c*TreatmentF
# mediator
Ambivalence ~ a*TreatmentF
Intention ~ b*Ambivalence
# indirect effect (a*b)
ab := a*b
# total effect
total := c + (a*b)'
fitmed1<-cfa(model, data=dflong[dflong$$Period==1,],se = "bootstrap") summary(fitmed1, fit.measures=F) fitmed2<-cfa(model, data=dflong[dflong$$Period==2,],se = "bootstrap")
summary(fitmed2, fit.measures=F)

medmod <- "
df1["Moderator"] <- df1["Ambi1"] * df1['TreatmentF']
# label the coefficients:
Ambi2 ~ a_m1*Moderator + a_m2*Treatment
Int2 ~ b1*Treatment + b2*Ambi2 + bM*Moderator

#Mediated Moderation effect
MedMod_ab := a_m1*bM
TotalMod := MedMod_ab + b2
"
fitmed3 <- lavaan::sem(model = medmod,
data = df1,
fixed.x = FALSE,
meanstructure = TRUE)
summary(fitmed3, ci = T)
$$$$
`

It's my understanding that lavaan does not currently support multilevel mediation (though it's perhaps possibly to create your own code to overcome this limitation).

People wanting to run a multilevel mediation in a SEM framework are usually adviced to turn to MPlus, which can handle such analysis very well - but it's a fairly expensive program and not accessible to everyone. MPlus syntax for such analysis is available for instance here (pdf)

There is a way to run such a model in R in a multilevel regression framework, see here But this doesn't allow latent variable modeling.