[step:Use reversibility to force periodicity from the first reduced state]
We show that the transition from $(m_n,d_n)$ to $(m_{n+1},d_{n+1})$ is injective on the reduced states that occur above. Suppose a reduced state $(m',d')$ is the image of a reduced state $(m,d)$. Then
\begin{align*}
d=\frac{D-(m')^2}{d'}
\end{align*}
is forced by the recurrence
\begin{align*}
d'=\frac{D-(m')^2}{d}.
\end{align*}
Once $d$ is known, the equation
\begin{align*}
m'=ad-m
\end{align*}
forces
\begin{align*}
m=ad-m'
\end{align*}
for the integer $a=\lfloor(\sqrt{D}+m)/d\rfloor$.
The reduced inequalities for the predecessor require
\begin{align*}
\sqrt{D}-d < m < \sqrt{D}.
\end{align*}
Substituting $m=ad-m'$ gives
\begin{align*}
\frac{m'+\sqrt{D}-d}{d} < a < \frac{m'+\sqrt{D}}{d}.
\end{align*}
This is an open interval of length $1$. Its endpoints are irrational because $\sqrt{D}$ is irrational, so it contains at most one integer. Hence the predecessor state is unique, and the transition is injective on reduced states.
Since the sequence $((m_n,d_n))_{n\geq 1}$ lies in the finite set $\mathcal{S}$, there exist indices $1\leq r<s$ such that
\begin{align*}
(m_r,d_r)=(m_s,d_s).
\end{align*}
If $r>1$, injectivity lets us step backwards repeatedly and obtain
\begin{align*}
(m_1,d_1)=(m_{s-r+1},d_{s-r+1}).
\end{align*}
Therefore the first reduced state $(m_1,d_1)$ repeats. Let $\ell\geq 1$ be the smallest integer such that
\begin{align*}
(m_{\ell+1},d_{\ell+1})=(m_1,d_1).
\end{align*}
The deterministic recurrence then gives
\begin{align*}
(m_{n+\ell},d_{n+\ell})=(m_n,d_n)
\end{align*}
for every $n\geq 1$. Since
\begin{align*}
a_n=\left\lfloor \frac{\sqrt{D}+m_n}{d_n}\right\rfloor
\end{align*}
for $n\geq 1$, it follows that
\begin{align*}
a_{n+\ell}=a_n
\end{align*}
for every $n\geq 1$. Thus the continued fraction of $\sqrt{D}$ is periodic after the initial term:
\begin{align*}
\sqrt{D}=[a_0;\overline{a_1,a_2,\dots,a_\ell}].
\end{align*}
[/step]