Denote the group of solutions $X$ modulo $n$ to
$$ X^{m} = X \pmod n $$
by $H(m,n)$. Then $H(m,n)$ is a subgroup of $G_n = \Bbb{Z}_{n}^{\times}$ the group of units modulo $n$. Note that $H(n-1,n) = G_n$ and $H(n+1, n+2) = G_{n+2}$ if and only if $n$ and $n+2$ is either a Carmichael or a prime number. But because of the low density of Carmichael numbers this is probably also a twin prime detector. We also know that $|H(m,n)|$ divides $|G_n|$ for all $n$.
Now look at prime powers $p^k$ dividing $n$. If $x \in H(m,b)$ and $a \mid b$ then $x \in H(m,a)$, clearly by seeing that modulo $b$ means $b \mid X^{m} - X$, which means so does $a$ divide it.
Thus for each prime power $p^k \mid n$ we have $H(m, p^k) \subset H(m, p^{k-1}) \subset \dots \subset H(m, p)$. We know that $|H(m, p)|= \gcd(m, p-1)$.
I'm wondering, can we calculate $|H(m,n)|$ at a prime power $n = p^k$? Since $|H(m,n)| = \prod_{ p \text{ prime} \\p^k \mid n \\ p^{k+1} \nmid n} |H(m, p^k)|$ would then in general be true, because $h(n) = |H(m,n)|$ is a multiplicative function.
Attempt. I'm closely following an answer post by Jyrki Lahtonen.
Let $p$ be an odd prime, then according to Wikipedia, $\Bbb{Z}^{*}_{p^k}$ is a cyclic group of order $\varphi(p^k) = p^k - p^{k-1} = p^{k-1} (p-1)$.
So that there is a primitive root $g \in G = \Bbb{Z}^*_{p^k}$ such that:
$$ G = \{ 1, g^2, g^3, \dots, g^{\varphi(n) - 1}\} $$
So each solution $X$ can be written $X = g^j$ for some $j = 0..\varphi(n) -1$.
But $g^{jm} = 1$ if and only if $\varphi(n) \mid jm$. Take $d = \gcd(\varphi(n), m)$. Then we have $g^{jm} = 1$ if and only if $\varphi(n)/d \mid j$.
From this, and from the list enumerating $g^j$ that has $j = 1..\varphi(n)$ we can conclude that $|H(m, p^k)| = \gcd(\varphi(p^k), m)$ whenever $p$ is an odd prime. But a similar formula holds whenever $n = 1, 2,4, 2p^k$ as well, namely $|H(m, n)| = \gcd(\varphi(n), m)$.
Whenever $n$ is an odd number, it consists of a product of powers of odd primes, thus:
$$ |H(m, n)| = \prod_{p \mid n} \gcd(p^{k-1}(p -1), m) $$
where each $k$ in the product is $k = v_p(n)$.
All together we have that an odd number $n$ is a twin prime first if and only if:
$$ n \prod_{p \mid n} \dfrac{(p-1)}{p \gcd(p^{v_p(n)}(p-1), n-1)} = 1 \\ \text{ and } \\ (n+2) \prod_{p \mid (n+2)} \dfrac{(p-1)}{p \gcd(p^{v_p(n+2)}(p-1), n+1)} = 1 $$
But something is not right with the formula, so my attempt is not a correct solution. Hence, how can we solve this?