Skip to content

TAKEOFF69/codex-skills-kit / skills/git-under-contention

git-under-contention

Verified

Operate Git safely when multiple humans or coding agents may share a repository, checkout, index, branches, or worktrees. Use before staging, committing, pushing, merging, rebasing, creating or removing worktrees, recovering apparently lost edits, handling staged files you did not touch, or preserving unfinished agent work under parallel-session contention.

FileKindSize
SKILL.mdskill md4.4 KB
agents/openai.yamlconfig239 B
scripts/contention_preflight.pyscript11.2 KB

scripts/contention_preflight.py

View on GitHub
#!/usr/bin/env python3
"""Detect deterministic Git-contention signals in a shared repository.

Signals:
  other-worktrees   worktrees registered besides current checkout
  head-moved-60m    HEAD reflog entries within last 60 minutes
  pre-staged        files already present in index
  dirty-not-mine    dirty paths outside pathspecs passed with --mine

Verdict is CLEAR when no signal fires and CONTENTION otherwise. CONTENTION is
not an error by itself; it means use explicit path ownership or isolated
worktree before mutating repository state.

Exit codes: 0 CLEAR, 1 CONTENTION or failed selftest, 2 usage or environment.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import tempfile
from datetime import datetime, timedelta, timezone
from pathlib import Path

HEAD_WINDOW_MIN = 60
REFLOG_SHOW = 3
REFLOG_TS = re.compile(r"@\{([^}]+)\}")


def run_git(
    args: list[str], cwd: str | Path, env: dict[str, str] | None = None
) -> tuple[int, str, str]:
    try:
        proc = subprocess.run(
            ["git", *args],
            cwd=cwd,
            env=env,
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="replace",
            check=False,
        )
    except FileNotFoundError:
        return 2, "", "git not found on PATH"
    return proc.returncode, proc.stdout or "", proc.stderr or ""


def norm(path: str | Path) -> str:
    return os.path.normcase(os.path.normpath(os.path.abspath(path)))


def repo_toplevel(cwd: str | Path, env: dict[str, str] | None = None) -> str | None:
    rc, out, _ = run_git(["rev-parse", "--show-toplevel"], cwd, env)
    return out.strip() if rc == 0 else None


def check_other_worktrees(cwd: str | Path, env: dict[str, str] | None = None) -> dict:
    top = repo_toplevel(cwd, env)
    rc, out, _ = run_git(["worktree", "list", "--porcelain"], cwd, env)
    evidence: list[str] = []
    if rc == 0 and top:
        for block in out.strip().split("\n\n"):
            path = None
            branch = None
            for line in block.splitlines():
                if line.startswith("worktree "):
                    path = line.removeprefix("worktree ").strip()
                elif line.startswith("branch "):
                    branch = line.removeprefix("branch ").strip()
                elif line.strip() == "detached":
                    branch = "(detached)"
                elif line.strip() == "bare":
                    branch = "(bare)"
            if path and norm(path) != norm(top):
                evidence.append(f"{path} [{branch or '?'}]")
    return {
        "id": "other-worktrees",
        "label": "other worktrees registered on this repository",
        "fired": bool(evidence),
        "evidence": evidence,
    }


def check_head_moved(
    cwd: str | Path,
    env: dict[str, str] | None = None,
    window_min: int = HEAD_WINDOW_MIN,
) -> dict:
    rc, out, _ = run_git(["reflog", "--date=iso"], cwd, env)
    recent: list[str] = []
    if rc == 0:
        now = datetime.now(timezone.utc)
        for line in out.splitlines():
            match = REFLOG_TS.search(line)
            if not match:
                continue
            try:
                stamp = datetime.strptime(match.group(1), "%Y-%m-%d %H:%M:%S %z")
            except ValueError:
                continue
            if now - stamp <= timedelta(minutes=window_min):
                recent.append(line.strip())
    evidence: list[str] = []
    if recent:
        evidence.append(f"{len(recent)} HEAD reflog entries in last {window_min} min")
        evidence.extend(recent[:REFLOG_SHOW])
    return {
        "id": "head-moved-60m",
        "label": f"HEAD reflog movement in last {window_min} min",
        "fired": bool(recent),
        "count": len(recent),
        "evidence": evidence,
    }


def check_pre_staged(cwd: str | Path, env: dict[str, str] | None = None) -> dict:
    rc, out, _ = run_git(["diff", "--cached", "--name-only"], cwd, env)
    files = [line.strip() for line in out.splitlines() if line.strip()] if rc == 0 else []
    return {
        "id": "pre-staged",
        "label": "files already staged in index",
        "fired": bool(files),
        "evidence": files,
    }


def status_paths(
    cwd: str | Path,
    env: dict[str, str] | None = None,
    pathspecs: list[str] | None = None,
) -> set[str]:
    args = ["status", "--porcelain", "--untracked-files=all"]
    if pathspecs:
        args += ["--", *pathspecs]
    rc, out, _ = run_git(args, cwd, env)
    paths: set[str] = set()
    if rc != 0:
        return paths
    for line in out.splitlines():
        if len(line) < 4:
            continue
        path = line[3:]
        if " -> " in path:
            path = path.split(" -> ", 1)[1]
        if len(path) >= 2 and path[0] == '"' and path[-1] == '"':
            path = path[1:-1]
        paths.add(path)
    return paths


def check_dirty_not_mine(
    cwd: str | Path,
    env: dict[str, str] | None = None,
    mine: list[str] | None = None,
) -> dict:
    if not mine:
        return {
            "id": "dirty-not-mine",
            "label": "dirty paths outside --mine pathspecs",
            "fired": False,
            "evidence": [],
            "skipped": "no --mine pathspecs given",
        }
    outside = sorted(status_paths(cwd, env) - status_paths(cwd, env, mine))
    return {
        "id": "dirty-not-mine",
        "label": f"dirty paths outside --mine ({' '.join(mine)})",
        "fired": bool(outside),
        "evidence": outside,
    }


def run_checks(
    cwd: str | Path,
    env: dict[str, str] | None = None,
    mine: list[str] | None = None,
) -> list[dict]:
    return [
        check_other_worktrees(cwd, env),
        check_head_moved(cwd, env),
        check_pre_staged(cwd, env),
        check_dirty_not_mine(cwd, env, mine),
    ]


def verdict_of(signals: list[dict]) -> str:
    return "CONTENTION" if any(signal["fired"] for signal in signals) else "CLEAR"


def wipe(path: str) -> None:
    def onerror(func, target, _exc):
        try:
            os.chmod(target, stat.S_IWRITE)
            func(target)
        except OSError:
            pass

    shutil.rmtree(path, onerror=onerror)


def selftest() -> int:
    failures: list[str] = []

    def check(name: str, condition: bool, detail: str = "") -> None:
        print(f"  {'ok  ' if condition else 'FAIL'} {name}")
        if not condition:
            if detail:
                print(f"       {detail}")
            failures.append(name)

    scratch = tempfile.mkdtemp(prefix="contention_selftest_")
    try:
        env = dict(os.environ)
        env.update(
            {
                "GIT_CONFIG_GLOBAL": os.devnull,
                "GIT_CONFIG_SYSTEM": os.devnull,
                "GIT_CONFIG_NOSYSTEM": "1",
                "GIT_AUTHOR_NAME": "selftest",
                "GIT_AUTHOR_EMAIL": "selftest@invalid",
                "GIT_COMMITTER_NAME": "selftest",
                "GIT_COMMITTER_EMAIL": "selftest@invalid",
            }
        )
        old = datetime.now(timezone.utc) - timedelta(hours=3)
        backdated = dict(env)
        backdated["GIT_AUTHOR_DATE"] = f"{int(old.timestamp())} +0000"
        backdated["GIT_COMMITTER_DATE"] = f"{int(old.timestamp())} +0000"

        repo = Path(scratch) / "repo"
        repo.mkdir()

        def git(args: list[str], selected_env: dict[str, str] = env, cwd: Path = repo) -> str:
            rc, out, err = run_git(args, cwd, selected_env)
            if rc != 0:
                raise RuntimeError(f"git {' '.join(args)} failed: {err.strip()}")
            return out

        def write(name: str, value: str) -> None:
            (repo / name).write_text(value, encoding="utf-8")

        git(["init", "-q", "-b", "main"])
        write("base.txt", "one\n")
        git(["add", "base.txt"], backdated)
        git(["commit", "-q", "-m", "initial"], backdated)

        quiet = run_checks(repo, env)
        check("quiet repository has no fired signal", not any(item["fired"] for item in quiet))
        check("quiet verdict is CLEAR", verdict_of(quiet) == "CLEAR")

        worktree = Path(scratch) / "worktree"
        git(["worktree", "add", str(worktree), "-b", "side"], backdated)
        signal = check_other_worktrees(repo, env)
        check("other-worktrees fires", signal["fired"], json.dumps(signal["evidence"]))

        write("base.txt", "one\ntwo\n")
        git(["add", "base.txt"])
        git(["commit", "-q", "-m", "recent move"])
        signal = check_head_moved(repo, env)
        check("head-moved-60m fires", signal["fired"] and signal["count"] >= 1)

        write("staged.txt", "staged\n")
        git(["add", "staged.txt"])
        signal = check_pre_staged(repo, env)
        check("pre-staged fires", signal["fired"] and "staged.txt" in signal["evidence"])

        write("mine.txt", "mine\n")
        write("stray.txt", "stray\n")
        signal = check_dirty_not_mine(repo, env, ["mine.txt"])
        check("dirty-not-mine fires", signal["fired"] and "stray.txt" in signal["evidence"])
        check("dirty-not-mine excludes mine", "mine.txt" not in signal["evidence"])

        loaded = run_checks(repo, env, ["mine.txt"])
        check("loaded verdict is CONTENTION", verdict_of(loaded) == "CONTENTION")
    except Exception as exc:
        print(f"  FAIL selftest infrastructure: {exc}")
        failures.append("infrastructure")
    finally:
        wipe(scratch)

    print(f"selftest: {'PASS' if not failures else 'FAIL'} ({len(failures)} failures)")
    return 0 if not failures else 1


def main(argv: list[str]) -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--mine", nargs="+", default=None, metavar="PATHSPEC")
    parser.add_argument("--json", action="store_true")
    parser.add_argument("--selftest", action="store_true")
    args = parser.parse_args(argv)

    if args.selftest:
        return selftest()

    top = repo_toplevel(os.getcwd())
    if top is None:
        print("contention_preflight: not inside a Git repository", file=sys.stderr)
        return 2

    signals = run_checks(os.getcwd(), mine=args.mine)
    fired = [signal for signal in signals if signal["fired"]]
    verdict = verdict_of(signals)

    if args.json:
        print(
            json.dumps(
                {
                    "repo": top,
                    "verdict": verdict,
                    "window_minutes": HEAD_WINDOW_MIN,
                    "mine": args.mine or [],
                    "signals": signals,
                },
                ensure_ascii=False,
                indent=2,
            )
        )
    else:
        print(f"contention_preflight: {top}")
        for signal in signals:
            if signal.get("skipped"):
                print(f"  [--] {signal['id']}: skipped ({signal['skipped']})")
                continue
            marker = "[SIGNAL]" if signal["fired"] else "[ok]"
            print(f"  {marker} {signal['id']}: {signal['label']}")
            for evidence in signal["evidence"]:
                print(f"      {evidence}")
        print(f"verdict: {verdict}" + (f" ({len(fired)} signals)" if fired else ""))
        if fired:
            print("Use explicit path ownership or move work to isolated worktree.")

    return 1 if fired else 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 469kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 321kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 321kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 321kUpdated Claude CodeCodexVerifiedInstall