Your Agent Can See the Repo. Git Says the Ownership Is Dubious.

You check in after a scheduled publish or an overnight run. The agent service is green. The workspace path is right where it should be. But the job log says Git refused to status, commit, fetch, or push, and the reason is one line: detected dubious ownership in repository. You SSH in as your login user, cd into the repo, run git status, and it works. Now the failure looks intermittent, or imaginary.

It is neither. Git checks whether the user running it owns the repository, and the user running your job is not the user you SSH in as. This guide covers how to confirm who owns the repo versus who runs the job, rule out the failures that look similar, fix ownership, consider a narrow safe.directory exception only when you cannot change ownership, and add a preflight so the next job does not start against a repo Git will refuse.

The errors you’ll actually see

  • fatal: detected dubious ownership in repository at '/opt/agent/repo' (or a path under /home/agent or a workspace directory).
  • Right after it, Git’s hint: To add an exception for this directory, call: followed by git config --global --add safe.directory /opt/agent/repo.
  • git status, git fetch, git commit, and git push all fail with the same line, because Git refuses to open the repo at all.
  • A cron or systemd job exits non-zero while an interactive shell as your login user runs Git in the same path without complaint.
  • sudo git status also fails, or it works once and leaves root-owned files behind under .git.
  • A publish script stops before writing the new post, with no partial commit.
  • The failure returns after a reboot, because nothing ever changed the owner.

Rule out the cousins first

  • Dirty working tree. Git opens the repo, and git status --porcelain lists leftover files. That is a different problem, covered in the dirty Git tree publish block. This post is about Git refusing to open the repo.
  • fatal: not a git repository. Wrong path, wrong WorkingDirectory=, or .git is missing.
  • Plain Permission denied. A parent directory is not traversable or files are not readable by the job user. That is a mode problem, not an ownership-check problem. A world-readable tree can still fail the dubious-ownership check.
  • Auth or deploy key failures. Permission denied (publickey) or a rejected push only appears after Git has already accepted the repo.

Why it hides

The path exists and looks fine in ls. Your login user, often pi, frequently owns the tree, so your interactive git status succeeds. The systemd User= or the cron user is different, and that is the user Git checks. sudo git runs as root, which is also a mismatch when the tree is owned by pi or agent. If you follow Git’s hint as yourself or under sudo, the exception lands in your ~/.gitconfig or /root/.gitconfig, and the service user never reads either. A systemd service’s HOME may be the service home, /, or unset, so it may not see config you just wrote. A one-off sudo git pull can leave only some files under .git owned by root, so the trouble surfaces later on a fetch or commit.

Step 1: Confirm the owner mismatch

Identify the repo path the job uses and the user it runs as.

REPO=/opt/agent/repo
systemctl show -p User,Group,WorkingDirectory,Environment agent.service
# For cron jobs, find which user's crontab holds the job:
sudo crontab -u agent -l

An empty User= means the service runs as root. Then compare owners:

JOB_USER=agent
JOB_GROUP="$(id -gn "$JOB_USER")"
id "$JOB_USER"
stat -c '%U:%G %n' "$REPO" "$REPO/.git"
sudo find "$REPO" -xdev \( ! -user "$JOB_USER" -o ! -group "$JOB_GROUP" \) \
  -printf '%u:%g %p\n' | head -n 20

Inspect .git as well as the top-level directory. Git checks both, and a stray sudo often leaves the damage inside .git.

Now run Git as the job user, not as yourself:

sudo -u "$JOB_USER" -H git -C "$REPO" status

If that prints the dubious-ownership line and stat shows an owner other than the job user, you have found the cause.

Step 2: Restore ownership to the job user

If this is the agent’s own repo, the job user should own all of it, including .git:

sudo chown -R "$JOB_USER:$JOB_GROUP" "$REPO"
stat -c '%U:%G %n' "$REPO" "$REPO/.git"
sudo -u "$JOB_USER" -H git -C "$REPO" status

This is the preferred fix. Do not run the agent as root to make the error go away, and do not chmod -R 777 the tree. Neither addresses the owner check, and both widen what can write to your repo. If you are still setting up the service account, see the dedicated Linux user and systemd sandbox guide.

Step 3: Make the fix stick for the user that runs the job

After the chown, confirm the unit’s User= and WorkingDirectory= (or the cron user and its cd path) still point at the tree you just fixed. Then adopt one standing rule: no sudo git in the agent repo. If you need elevated access to run Git there, run it as the job user:

sudo -u "$JOB_USER" -H git -C "$REPO" pull

Only if the tree must stay owned by someone else (a shared checkout you should not chown), add a narrow exception to the service user’s global config, with an absolute path:

sudo -u "$JOB_USER" -H git config --global --add safe.directory "$REPO"
sudo -u "$JOB_USER" -H git config --global --list --show-origin | grep safe.directory

The --show-origin output should name the job user’s home, such as file:/home/agent/.gitconfig, not /root/.gitconfig. Git only honors safe.directory from system, global, or command-line config, not from the repo’s own .git/config. Do not use safe.directory=*. It turns the ownership check off for every repo the user touches, and it should not be the default advice for any box.

If the unit’s HOME is / or unset, Git will not find that file. Set it in the unit:

[Service]
Environment=HOME=/home/agent

If the service user has no real home, point Git at a dedicated file instead:

sudo git config --file /etc/agent/gitconfig --add safe.directory "$REPO"
sudo chmod 644 /etc/agent/gitconfig
[Service]
Environment=GIT_CONFIG_GLOBAL=/etc/agent/gitconfig

A boot-time oneshot that re-runs the chown is optional insurance. The standing rule plus the preflight below matters more.

Step 4: A fail-closed preflight

This script refuses to let the job start against a repo Git will refuse. It logs one clear line, alerts once per outage through a Discord webhook if one is configured, and exits 1 so cron can chain it with &&.

#!/usr/bin/env bash
# /usr/local/bin/git-owner-preflight.sh
# Run as the SAME user the job runs as. Exits 1 if Git will refuse the repo.
set -u

REPO="${REPO:-/opt/agent/repo}"
STRICT="${STRICT:-0}"                      # 1 = also scan the whole tree
ALLOW_FOREIGN_OWNER="${ALLOW_FOREIGN_OWNER:-0}"  # 1 only if using safe.directory
MARKER_DIR="${MARKER_DIR:-/run/agent-preflight}"
MARKER="$MARKER_DIR/git-owner.alerted"
WEBHOOK_FILE="${WEBHOOK_FILE:-${HOME:-/nonexistent}/.config/agent/discord-webhook}"

ME="$(id -un)"
MYGROUP="$(id -gn)"

log() { echo "git-owner-preflight: $*" >&2; }

alert_once() {
  local msg="$1"
  [ -e "$MARKER" ] && return 0
  local url="${DISCORD_WEBHOOK_URL:-}"
  if [ -z "$url" ] && [ -r "$WEBHOOK_FILE" ]; then
    url="$(head -n 1 "$WEBHOOK_FILE")"
  fi
  if [ -n "$url" ]; then
    curl -fsS -m 10 -H 'Content-Type: application/json' \
      -d "{\"content\":\"$(hostname): ${msg}\"}" "$url" >/dev/null 2>&1 \
      || log "webhook post failed (URL not shown)"
  fi
  mkdir -p "$MARKER_DIR" 2>/dev/null && touch "$MARKER" 2>/dev/null
}

fail() { log "FAIL: $*"; alert_once "$*"; exit 1; }

if [ "$(id -u)" -eq 0 ] && [ "${ALLOW_ROOT:-0}" != 1 ]; then
  fail "running as root; run this as the job user"
fi

[ -d "$REPO" ]      || fail "repo path missing: $REPO"
[ -e "$REPO/.git" ] || fail "no .git in $REPO (wrong path or not a repo)"

if [ "$ALLOW_FOREIGN_OWNER" != 1 ]; then
  for p in "$REPO" "$REPO/.git"; do
    owner="$(stat -c '%U' "$p")"
    [ "$owner" = "$ME" ] || fail "owner mismatch: $p owned by $owner, job runs as $ME"
  done
  if [ "$STRICT" = 1 ]; then
    bad="$(find "$REPO" -xdev \( ! -user "$ME" -o ! -group "$MYGROUP" \) -print -quit 2>/dev/null)"
    [ -z "$bad" ] || fail "mismatched owner under repo, first: $bad"
  fi
fi

out="$(git -C "$REPO" rev-parse --is-inside-work-tree 2>&1)"
rc=$?
if printf '%s' "$out" | grep -q 'dubious ownership'; then
  fail "Git reports dubious ownership in $REPO for user $ME"
fi
[ "$rc" -eq 0 ] && [ "$out" = "true" ] || fail "git rev-parse failed in $REPO (rc=$rc)"

rm -f "$MARKER" 2>/dev/null
log "OK: $REPO owned by $ME and Git accepts it"

Install it with sudo install -m 755 git-owner-preflight.sh /usr/local/bin/. The top-level and .git checks are cheap. STRICT=1 walks the whole tree, which is slower on an SD card but catches root-owned objects deep inside .git. The webhook URL is never printed.

The marker lives in /run, so it clears on reboot. A non-root user cannot create directories there, so create it at boot for cron jobs:

echo 'd /run/agent-preflight 0755 agent agent -' | sudo tee /etc/tmpfiles.d/agent-preflight.conf
sudo systemd-tmpfiles --create /etc/tmpfiles.d/agent-preflight.conf

Cron, in the job user’s crontab (sudo crontab -u agent -e):

*/30 * * * * REPO=/opt/agent/repo /usr/local/bin/git-owner-preflight.sh && /opt/agent/bin/publish.sh >> /home/agent/logs/publish.log 2>&1

If your cron entry lives in a different user’s crontab than the service, the preflight must still run as the job user, or it checks the wrong owner.

systemd:

[Service]
User=agent
Group=agent
Environment=HOME=/home/agent
Environment=REPO=/opt/agent/repo
RuntimeDirectory=agent-preflight
RuntimeDirectoryPreserve=yes
ExecStartPre=/usr/local/bin/git-owner-preflight.sh
ExecStart=/opt/agent/bin/publish.sh

An ExecStartPre= in a unit with User=agent already runs as agent, so it checks the same user Git will. RuntimeDirectoryPreserve=yes keeps the alert marker between runs until reboot, so a timer-driven oneshot does not alert on every attempt.

Standing routine

  • Every job: run the preflight first and chain the real work behind it.
  • After moving the repo or changing the service user: rerun Step 1 and update REPO, User=, and the cron entry together.
  • After any sudo git command in that tree: run the find from Step 1 and chown back if anything shows up.
  • Monthly: run the preflight with STRICT=1 and confirm stat still shows the job user on the repo and .git.

If you run the reboot and power-loss test, add this ownership check to it. A box can come back with a repo that was restored, extracted, or repaired as root, and the first sign will be a publish that never happens.

Keep the next run boring

The fix is usually one chown and one habit: run Git as the job user. If you want the prompts and checklists we use to keep unattended agents honest, start with the free prompts, go deeper with the OpenClaw Agent Ops Toolkit, or get everything in the Ultimate Bundle.

More from the build log

Suggested

Want the full MarketMai stack?

Get the core MarketMai guides and operator playbooks in one premium bundle for $49.

View Bundle