Cause 1 of 5
You checked out a commit hash, a tag, or a remote-tracking ref.
Nothing is broken — this is a normal, non-destructive state for looking at history. git switch - returns you to where you were, and git switch main goes to a named branch.
Cause 2 of 5
You already committed while detached and want to keep the work.
Name it before you leave: git switch -c keep-this-work. That converts the detached commits into an ordinary branch, and there is nothing else to do.
Cause 3 of 5
You left the state and only now realise commits are missing.
git reflog lists every commit HEAD has pointed at, orphans included. Find the hash in that list, then git branch recovered <hash> to make it reachable again. Reflog entries persist for 90 days by default, so do this before running git gc --prune.
Cause 4 of 5
A CI job checks out a specific SHA, which is detached by design.
That is expected and usually fine. If a build step needs a branch name — for a version stamp, or to push a tag — create one explicitly with git checkout -B "$CI_BRANCH" or read the branch from the CI environment variable.
Cause 5 of 5
A submodule is showing as detached.
Submodules are pinned to an exact commit, so detached is their normal state. To change one, cd into it, git switch main, commit there, then commit the updated pointer in the parent repository.