Solution (source code)

= Solution

Vary the <scalar field> and integrate by parts, taking the <variation> to vanish at the boundary:
$$
\delta S=\int d^4x\sqrt{-g}\left\{\nabla_\mu\nabla^\mu\phi-V_{,\phi}\right\}\delta\phi.
$$
Thus the curved-spacetime <Klein-Gordon equation> is $\Box\phi-V_{,\phi}=0$. In the flat <FRW metric>, $\sqrt{-g}=a^3$ and $g^{00}=-1$. A spatially homogeneous field therefore has
$$
\Box\phi=\frac1{a^3}\partial_t(-a^3\dot\phi)=-\ddot\phi-3\frac{\dot a}{a}\dot\phi.
$$
Consequently
$$
\boxed{\ddot\phi+3H\dot\phi+V_{,\phi}=0,\qquad H=\frac{\dot a}{a}.}
$$
Dots now denote <cosmic time> derivatives. The $3H\dot\phi$ term is <Hubble friction> caused by expansion of the <comoving volume>.