  We define a congruence module $\Psi_A(M)$ associated to a surjective
$\mathcal O$-algebra morphism $\lambda\colon A \to \mathcal{O}$, with
$\mathcal{O}$ a discrete valuation ring, $A$ a complete noetherian local
$\mathcal{O}$-algebra regular at $\mathfrak{p}$, the kernel of $\lambda$, and
$M$ a finitely generated $A$-module. We establish a numerical criterion for $M$
to have a free direct summand over $A$ of positive rank. It is in terms of the
lengths of $\Psi_A(M)$ and the torsion part of $\mathfrak{p}/\mathfrak{p}^2$.
It generalizes results of Wiles, Lenstra, and Diamond, that deal with the case
when the codimension of $\mathfrak{p}$ is zero.
  Number theoretic applications include integral (non-minimal) $R=\mathbb T$
theorems in situations of positive defect conditional on certain standard
conjectures. Here $R$ is a deformation ring parametrizing certain Galois
representations and $\mathbb T$ is a Hecke algebra. An example is a modularity
lifting for 2-dimensional $\ell$-adic Galois representations over an imaginary
quadratic field. The proofs combine our commutative algebra results with a
generalization due to Calegari and Geraghty of the patching method of Wiles and
Taylor--Wiles and level raising arguments that go back to Ribet. The results
provide new evidence in favor of the intriguing, and as yet fledgling, torsion
analog of the classical Langlands correspondence.
  We also prove unconditional integral $R=\mathbb T$ results for Hecke algebras
$\mathbb T$ acting on weight one cohomology of Shimura curves over $\mathbb Q$.
This leads to a torsion Jacquet--Langlands correspondence comparing integral
Hecke algebras acting on weight one cohomology of Shimura curves and modular
curves. In this case the cohomology has abundant torsion and so our
correspondence cannot be deduced by means of the classical Jacquet--Langlands
correspondence.
