dots: public mirror (history reset after licence cleanup)

This commit is contained in:
Coja committed 2026-11-09 18:19:14 +01:00
commit 693822ad5f
226 files changed
+22502

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
# SessionStart hook: refuse to let a severed dotfiles link go unnoticed.
#
# Claude Code writes settings with an atomic temp+rename. Through the stow layer that can
# replace ~/.config/claude/<file> (a symlink into the repo) with a plain FILE holding whatever
# snapshot the writing process had in memory -- silently freezing every later repo edit out
# of the live config. It happened on 2026-09-15 23:31: a stale copy dropped four hook events
# (git-guard among them) and nobody noticed for an hour. link.sh heals the identical case but
# only when run; this makes every session start say so instead.
#
# Read-only: it never relinks. Exit 2 on SessionStart shows stderr to the user and the session
# continues. Exit 0 when everything resolves into the repo.
set -u
src="$HOME/.config/claude"
bad=""
for f in settings.json statusline.py keybindings.json CLAUDE.md link.sh; do
p="$src/$f"
[ -e "$p" ] || continue
if [ ! -L "$p" ]; then bad="$bad $p is a plain file (should be a symlink into the dots repo)"$'\n'; fi
done
# the ~/.claude side too: link.sh's own guard covers it, but only when link.sh runs
for f in settings.json keybindings.json CLAUDE.md statusline.py; do
p="$HOME/.claude/$f"
[ -e "$p" ] || continue
case "$(readlink -f "$p")" in
*"/.dots/"*) ;;
*) bad="$bad $p resolves to $(readlink -f "$p"), not into the dots repo"$'\n' ;;
esac
done
[ -z "$bad" ] && exit 0
printf 'DRIFT: Claude config has broken out of the dots repo; the live config is a stale copy.\n%s fix: review with `diff`, then `bash ~/.config/claude/link.sh` (heals identical copies, warns otherwise)\n' "$bad" >&2
exit 2
+254
View File
@@ -0,0 +1,254 @@
#!/usr/bin/env python3
"""PostToolUse hook: format an edited file with the right formatter.
Reads the hook JSON from stdin, works out which file(s) were just edited, and runs a
language-appropriate formatter -- but, to avoid imposing a style on a project
that never asked for it, every formatter here only runs when the project opts in
via a config file discoverable by walking up from the edited file: stylua, ruff,
prettier and taplo on their own configs, gofmt and rustfmt on go.mod / Cargo.toml,
shfmt and fish_indent on .editorconfig. No marker, no formatting -- a repo that
hand-formats its shell keeps its own layout.
Two entry points, both wired in settings.json > hooks > PostToolUse:
* Edit|Write -- the edited path is `tool_input.file_path`.
* Bash -- under `defaultMode: auto` Claude is steered to edit through the shell
(sed -i, heredocs, python), which the Edit|Write matcher never sees.
There is no per-file event for that (`FileChanged` only watches literal
filenames), so this scans `tool_input.command` for path-like tokens with a
handled extension and formats the ones modified in the last few seconds --
the mtime gate keeps a parallel session's dirty files out of it.
Best-effort: always exits 0 so a format hiccup never blocks an edit. jq is not
guaranteed on the host, hence python for the stdin JSON parse.
"""
import fnmatch
import json
import os
import re
import shutil
import subprocess
import sys
import time
def find_up(start, names):
"""Nearest ancestor dir (incl. the file's own) containing any of `names`."""
d = os.path.dirname(os.path.abspath(start))
while True:
if any(os.path.exists(os.path.join(d, n)) for n in names):
return d
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _expand_braces(pat):
"""`a{b,c}` -> [`ab`, `ac`] (editorconfig sections use {,} alternation)."""
m = re.search(r"\{([^{}]*)\}", pat)
if not m:
return [pat]
out = []
for alt in m.group(1).split(","):
out.extend(_expand_braces(pat[: m.start()] + alt + pat[m.end():]))
return out
def editorconfig_covers(path):
"""True if the nearest ancestor .editorconfig has a section matching `path`.
Mere existence is NOT opt-in: this repo's .editorconfig is deliberately scoped
to `[{*.sh,dotsync,dotpub}]` with no [*] block precisely so fish files stay
untouched, and a generic upstream .editorconfig must not switch a formatter on
for filetypes it never mentions. Patterns without a `/` match the basename
(the editorconfig convention); ones with a `/` match the path relative to the
.editorconfig's directory.
"""
d = find_up(path, [".editorconfig"])
if not d:
return False
name = os.path.basename(path)
rel = os.path.relpath(os.path.abspath(path), d)
try:
with open(os.path.join(d, ".editorconfig"), errors="ignore") as fh:
for line in fh:
line = line.strip()
if not (line.startswith("[") and line.endswith("]")):
continue
for pat in _expand_braces(line[1:-1]):
target = rel if "/" in pat else name
if fnmatch.fnmatch(target, pat.lstrip("/")):
return True
except Exception:
pass
return False
def has_toml_section(start, filename, section):
"""True if the nearest ancestor `filename` contains `section`."""
d = find_up(start, [filename])
if not d:
return False
try:
with open(os.path.join(d, filename), errors="ignore") as fh:
return section in fh.read()
except Exception:
return False
def stylua_cmd(path):
exe = os.path.expanduser("~/.local/share/nvim/mason/bin/stylua")
if not os.access(exe, os.X_OK):
exe = shutil.which("stylua")
if exe and find_up(path, [".stylua.toml", "stylua.toml"]):
return [exe, path]
return None
def ruff_cmd(path):
exe = shutil.which("ruff")
if exe and (find_up(path, ["ruff.toml", ".ruff.toml"])
or has_toml_section(path, "pyproject.toml", "[tool.ruff")):
return [exe, "format", path]
return None
_PRETTIER_CFGS = [
".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml",
".prettierrc.json5", ".prettierrc.js", ".prettierrc.cjs", ".prettierrc.mjs",
".prettierrc.toml", "prettier.config.js", "prettier.config.cjs",
"prettier.config.mjs",
]
def prettier_cmd(path):
exe = shutil.which("prettier")
if exe and find_up(path, _PRETTIER_CFGS):
return [exe, "--write", path]
return None
def gofmt_cmd(path):
exe = shutil.which("gofmt")
if exe and find_up(path, ["go.mod"]): # one canonical style
return [exe, "-w", path]
return None
def rustfmt_cmd(path):
exe = shutil.which("rustfmt")
if exe and find_up(path, ["Cargo.toml", "rustfmt.toml", ".rustfmt.toml"]):
return [exe, path]
return None
# Shell and fish are opt-in too, gated on an .editorconfig SECTION that matches the file
# (shfmt reads .editorconfig natively for its settings, so the marker and the tool agree).
# "One canonical style" turned out not to mean "the style the project uses": 3 of ~/.dots's
# 25 fish files are not fish_indent-clean, so running these on sight rewrote whole files and
# buried a 40-line change in a 200-line diff. ~/.dots opts its shell in via
# `[{*.sh,dotsync,dotpub}]` while its fish files stay hand-formatted — existence of the
# .editorconfig alone must not turn either formatter on.
# Neovim agrees: conform.nvim there lists lua/css/html/ts/js only — never sh or fish.
def fish_cmd(path):
exe = shutil.which("fish_indent")
if exe and editorconfig_covers(path):
return [exe, "-w", path]
return None
def shfmt_cmd(path):
exe = shutil.which("shfmt")
if exe and editorconfig_covers(path):
return [exe, "-w", path]
return None
def taplo_cmd(path):
exe = shutil.which("taplo")
# opt-in: TOML reflow/align is intrusive, so only where the project asked.
if exe and find_up(path, ["taplo.toml", ".taplo.toml"]):
return [exe, "format", path]
return None
HANDLERS = {
".lua": stylua_cmd,
".py": ruff_cmd,
".js": prettier_cmd, ".jsx": prettier_cmd, ".mjs": prettier_cmd,
".cjs": prettier_cmd, ".ts": prettier_cmd, ".tsx": prettier_cmd,
".css": prettier_cmd, ".scss": prettier_cmd, ".less": prettier_cmd,
".html": prettier_cmd, ".vue": prettier_cmd, ".json": prettier_cmd,
".md": prettier_cmd, ".yaml": prettier_cmd, ".yml": prettier_cmd,
".go": gofmt_cmd,
".rs": rustfmt_cmd,
".fish": fish_cmd,
".sh": shfmt_cmd, ".bash": shfmt_cmd,
".toml": taplo_cmd,
}
RECENT_SECS = 30 # a Bash edit is "ours" if the file changed this recently
_EXT_ALT = "|".join(re.escape(e[1:]) for e in HANDLERS)
_PATHISH = re.compile(r"[\w.~/@+-]+\.(?:" + _EXT_ALT + r")\b")
def format_one(path):
if not path or not os.path.isfile(path):
return
# Resolve symlinks before walking for markers: deployed dotfiles get edited via
# their ~/.config/... links, but the opt-in configs live beside the real file in
# the repo — a lexical walk from the link's path would never find them.
path = os.path.realpath(path)
handler = HANDLERS.get(os.path.splitext(path)[1].lower())
if not handler:
return
cmd = handler(path)
if not cmd:
return
try:
subprocess.run(cmd, timeout=15, capture_output=True)
except Exception:
pass
def recent_paths_in_command(command, cwd):
"""Files a shell command plausibly just wrote: path-like tokens with a handled
extension, resolved against the tool's cwd, that exist and changed within RECENT_SECS.
Unchanged mentions (the source of a `cp`, a file merely grepped) fail the mtime gate."""
now = time.time()
seen, out = set(), []
for tok in _PATHISH.findall(command or ""):
p = os.path.expanduser(tok)
if not os.path.isabs(p):
p = os.path.join(cwd, p)
p = os.path.normpath(p)
if p in seen:
continue
seen.add(p)
try:
if os.path.isfile(p) and now - os.path.getmtime(p) <= RECENT_SECS:
out.append(p)
except OSError:
pass
return out
def main():
try:
data = json.load(sys.stdin)
except Exception:
return
ti = data.get("tool_input") or {}
tr = data.get("tool_response") or {}
if data.get("tool_name") == "Bash":
cwd = data.get("cwd") or os.getcwd()
for p in recent_paths_in_command(ti.get("command"), cwd):
format_one(p)
return
format_one(ti.get("file_path") or tr.get("filePath") or "")
if __name__ == "__main__":
main()
+223
View File
@@ -0,0 +1,223 @@
#!/usr/bin/env bash
# Regression matrix for git-guard.py: `bash ~/.claude/hooks/git-guard-test.sh` (exit 1 on mismatch).
# Kept as a file on purpose: typed inline, the very commands under test would trip the live hook.
G="$(dirname "$(readlink -f "$0")")/git-guard.py"
fail=0
# No exempt repository for the rows that do not ask for one, whatever this host's ~/.claude/git-guard-exempt says.
export GIT_GUARD_EXEMPT=""
# `git reset <one arg>` is allowed only for an existing path: give the matrix one to point at.
tmp=$(mktemp -d) && cd "$tmp" && touch existing.py
trap 'rm -rf "$tmp"' EXIT
run() {
printf '%s' "{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":$(python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$2")}}" | python3 "$G" 2>/dev/null
rc=$?
got=allow
[ $rc -eq 2 ] && got=block
[ "$got" = "$1" ] && mark=ok || {
mark=MISMATCH
fail=1
}
printf '%-8s %-6s %-6s %s\n' "$mark" "$1" "$got" "$(printf '%s' "$2" | head -1)"
}
echo "--- must block: commits / history ---"
run block 'git push'
run block 'git -C /home/coja/.dots push origin main'
run block 'git -c user.name=x commit -m fix'
run block '/usr/bin/git push'
run block 'env GIT_DIR=.git git push'
run block 'timeout 5 git push'
run block 'sudo -u me git push'
run block 'cd /tmp && git push'
run block 'git status; git commit -am wip'
run block 'x=1; git push'
run block 'git push 2>&1 | tee log'
run block "sh -c 'git push origin HEAD'"
run block 'eval "git push"'
run block 'git -C $(pwd) push'
run block 'echo "$(git push)"'
run block 'git --git-dir=/x/.git --work-tree=/x push'
run block 'git commit -m "fix: grep pattern; not a command"'
run block 'git revert HEAD'
run block 'git cherry-pick abc123'
run block 'git rebase -i HEAD~3'
run block 'git rebase --interactive main'
run block 'git -C . rebase -i --autosquash main'
run block 'git rebase --autostash origin/main'
run block 'git -c rebase.autoStash=true rebase main'
run block 'git merge feature'
run block 'git merge --no-ff feature'
echo "--- must block: discards working-tree changes ---"
run block 'git reset --hard HEAD~1'
run block 'git reset HEAD~1 --hard'
run block 'git reset --soft HEAD~1'
run block 'git reset --keep HEAD~2'
run block 'git reset --merge'
run block 'git reset'
run block 'git reset -q'
run block 'git reset HEAD'
run block 'git reset HEAD~1'
run block 'git reset abc1234'
run block 'git reset 0123456789abcdef0123456789abcdef01234567'
run block 'git reset origin/main'
run block 'git reset @{u}'
run block 'git restore --staged .'
run block 'git restore --staged :/'
run block 'git clean -fd'
run block 'git -C . clean -n'
run block 'git restore file.py'
run block 'git restore --staged --worktree file.py'
run block 'git restore -W file.py'
run block 'git checkout -- .'
run block 'git checkout -- file.py'
run block 'git checkout HEAD -- file.py'
run block 'git checkout .'
run block 'git checkout -f main'
run block 'git stash drop'
run block 'git stash pop'
run block 'git stash clear'
run block 'git branch -D feature'
run block 'git branch -f main HEAD~1'
run block 'git branch -M main trunk'
echo "--- must block: gh pr write ops (create only with --head, edit only title/body) ---"
run block 'gh pr merge 12 --squash'
run block 'gh pr close 4'
run block 'gh -R o/r pr create --fill'
run block 'gh pr create --title x --body y'
run block 'gh pr create --dry-run --fill'
run block 'gh pr edit 3 --add-reviewer bob'
run block 'gh pr edit 3 --title x --base main'
run block 'gh pr edit --add-label=bug 3'
run block 'gh pr edit 3 -b y -m v2'
echo "--- must allow ---"
run allow 'git status'
run allow 'git log -1 --oneline'
run allow 'git diff --cached --stat'
run allow 'git add -A common/.config/claude'
run allow 'git rev-parse --git-path CLAUDE_COMMIT_MSG'
run allow 'git -c core.pager=cat log -3'
run allow 'git reset -- file.txt'
run allow 'git reset HEAD file.txt'
run allow 'git reset HEAD existing.py other.py'
run allow 'git reset existing.py'
run allow 'git reset -p'
run allow 'git reset -- .'
run allow 'git restore --staged existing.py'
run allow 'git restore --staged file.py'
run allow 'git restore -S file.py'
run allow 'git checkout main'
run allow 'git checkout -b feature'
run allow 'git switch main'
run allow 'git merge --abort'
run allow 'git rebase main'
run allow 'git rebase origin/main'
run allow 'git rebase -Xtheirs main'
run allow 'git rebase --continue'
run allow 'git rebase --abort'
run allow 'git -c core.editor=true rebase --continue'
run allow 'GIT_EDITOR=true git rebase --continue'
run allow 'git stash'
run allow 'git stash list'
run allow 'git stash push -m wip'
run allow 'git stash show -p'
run allow 'git branch -d merged-branch'
run allow 'git branch --list'
run allow 'git branch -vv'
run allow 'git commit-tree HEAD^{tree} -m x'
run allow 'git worktree list'
run allow 'grep -rn "git push" README.md'
run allow 'grep -n "foo; git commit" file'
run allow "echo 'git push'"
run allow 'echo "run git push"'
run allow "cat > README.md <<'EOF'
Deploy with:
git status; git commit -am x; git push origin main
EOF
echo written"
run allow 'python3 - <<EOF
print("git commit is manual")
EOF'
run allow 'gh pr view 12 --json updatedAt'
run allow 'gh pr create --head feat --title x --body y'
run allow 'gh pr create -H feat --fill'
run allow 'gh -R o/r pr create --head=feat --fill'
run allow 'gh pr create --help'
run allow 'gh pr edit 3 --title x'
run allow 'gh pr edit 3 -t x -b "- item --base"'
run allow 'gh pr edit --body-file - 12'
run allow 'gh pr edit 12 -F body.md --repo o/r'
run allow 'gh pr edit 12 --title=x -bBody'
run allow 'gh workflow run ci.yml --ref main'
run allow 'gh run rerun 123 --failed'
run allow 'gh api graphql -f query="mutation{...}"'
run allow 'gh auth status'
run allow 'ls -la HEAD#x; git status'
run allow 'git log --grep="git push" -5'
run allow '~/.config/git/claude-commit-msg list'
echo "--- exempt repo (GIT_GUARD_EXEMPT = a scratch repo; commit and merge pass there, nothing else) ---"
# runin <expect> <cwd> <command>: the hook input carries the session's cwd, as Claude Code sends it.
R=$tmp/repo
WT=$tmp/repo-wt
git init -q "$R" && git -C "$R" -c user.name=t -c user.email=t@t commit -q --allow-empty -m init \
&& git -C "$R" worktree add -q "$WT" 2>/dev/null && mkdir -p "$R/sub" && git init -q "$tmp/other"
runin() {
printf '%s' "$(python3 -c 'import json,sys; print(json.dumps({"tool_name":"Bash","tool_input":{"command":sys.argv[1]},"cwd":sys.argv[2]}))' "$3" "$2")" | GIT_GUARD_EXEMPT=$R python3 "$G" 2>/dev/null
rc=$?
got=allow
[ $rc -eq 2 ] && got=block
[ "$got" = "$1" ] && mark=ok || {
mark=MISMATCH
fail=1
}
printf '%-8s %-6s %-6s [%s] %s\n' "$mark" "$1" "$got" "${2#"$tmp"/}" "$(printf '%s' "$3" | head -1)"
}
runin allow "$R" 'git commit -m "docs: x"'
runin allow "$R" 'git commit -m x -- docs/usage.md'
runin allow "$R" 'git commit -m"fix a bug"'
runin allow "$R" 'git commit -m "-a is not the flag here"'
runin allow "$R" 'git commit --allow-empty -m x'
runin allow "$R/sub" 'git commit -m x'
runin allow "$R" 'git merge --ff-only feature'
runin allow "$R" 'git merge --no-ff feature'
runin allow "$WT" 'git commit -m x'
runin allow "$tmp" "git -C $WT commit -m x"
runin allow "$tmp" "cd $R && git commit -m x"
runin allow "$tmp" 'cd repo && git commit -m x'
runin allow "$tmp" "cd $WT; git status; git merge main"
runin allow "$R" "sh -c 'git commit -m x'"
runin block "$R" 'git push'
runin block "$R" 'git commit --amend --no-edit'
runin block "$R" 'git commit -am wip'
runin block "$R" 'git commit -qa -m wip'
runin block "$R" 'git commit --all -m wip'
runin block "$R" 'git rebase -i main'
runin block "$R" 'git cherry-pick abc123'
runin block "$R" 'git revert HEAD'
runin block "$R" 'git reset --hard HEAD~1'
runin block "$R" 'git checkout -- file.py'
runin block "$R" 'GIT_DIR=/x/.git git commit -m x'
runin block "$R" 'env GIT_WORK_TREE=/x git commit -m x'
runin block "$R" 'git --git-dir=/x/.git commit -m x'
runin block "$R" 'git -C /tmp commit -m x'
runin block "$R" 'git -C $(mktemp -d) commit -m x'
runin block "$tmp" "cd $R && cd /tmp && git commit -m x"
runin block "$R" 'cd - && git commit -m x'
runin block "$R" 'cd $HOME && git commit -m x'
runin block "$R" 'pushd /tmp && git commit -m x'
runin block "$tmp" 'git commit -m x'
runin block "$tmp/other" 'git commit -m x'
runin block "$tmp" "git -C $tmp/other merge x"
echo "--- fail-open ---"
printf '%s' '{"tool_name":"Edit","tool_input":{"command":"git push"}}' | python3 "$G"
[ $? -eq 0 ] && echo "ok non-Bash tool ignored" || {
echo "MISMATCH non-Bash"
fail=1
}
printf 'not json' | python3 "$G"
[ $? -eq 0 ] && echo "ok garbage stdin passes" || {
echo "MISMATCH garbage"
fail=1
}
[ $fail -eq 0 ] && echo "GIT-GUARD MATRIX: all ok" || {
echo "GIT-GUARD MATRIX: mismatches above"
exit 1
}
+369
View File
@@ -0,0 +1,369 @@
#!/usr/bin/env python3
"""PreToolUse hook (Bash): enforce the no-commit / no-push contract structurally.
settings.json's deny rules (`Bash(git push:*)`, ...) match a literal *prefix* of the
command text, so `git -C . push`, `git -c k=v commit`, `/usr/bin/git push`,
`env X=1 git push`, `timeout 5 git push` and `sh -c 'git push'` all slip past them.
This hook parses each shell segment instead: finds the git/gh token wherever it sits,
skips git's global options (`-C dir`, `-c k=v`, `--git-dir=...`) and blocks
git commit | push | revert | cherry-pick | merge (not --abort/--quit/--continue)
git rebase -i / --interactive / --autostash
git clean | reset (any form that moves HEAD or unstages everything; `reset -- <paths>`,
`reset HEAD <path>` and `reset <existing path>` are fine) | restore <paths> (--staged
alone is fine, except `--staged .` / `:/`) | checkout -- / checkout . / -f
git stash drop | pop | clear git branch -D / -f / -M
gh pr merge | close | create without --head | edit beyond --title/--body
i.e. anything that commits, rewrites history, or discards working-tree changes -- the last
group matters most with several sessions sharing one checkout. Mirrors pi's permission-gate.
On GitHub Claude may open a PR (settings.json asks first) and retitle / redescribe one, nothing
more: `gh pr create` must name its branch with --head, without which gh pushes it itself (even
under --dry-run), and `gh pr edit` must not touch reviewers, labels, base or the like.
A plain `git rebase` (and its --continue / --abort) passes: Claude rebases and fixes the
conflicts when the user asks (global CLAUDE.md), and settings.json asks before each one, as
pi's gate does. `-i` stays blocked (the squash/reword tool, and it needs an editor), and so
does --autostash: it stashes and re-pops other sessions' uncommitted edits, where a plain
rebase refuses to start on a dirty tree.
Exit 2 + one stderr line = the call is blocked and Claude reads the reason (stage and
stop; /commit-msg drafts the message). Mirrors pi's permission-gate.ts.
Tokenizing is quote-aware first (shlex in punctuation mode), and only then split at the
separators `;`, `|`, `&&`, `(`, `)`: a quoted word that merely *contains* a separator and a
git verb (a grep pattern, a commit message) stays one word and is not a command. `$(...)`
and backtick bodies are scanned on their own and then collapsed, so `git -C $(pwd) push`
still parses as a push. `sh -c '...'` and `eval` bodies recurse.
Deliberate gaps: heredoc bodies are skipped -- they are file/script *contents*, and a
README that documents pushing must stay writable -- so a script piped in through a heredoc
is not inspected. Aliases (`git ci`) are not expanded. The deny list, the auto-mode
classifier and the global CLAUDE.md still cover those; this is the belt for the prefix
rules' braces. Fails open: any parse error lets the command through (exit 0).
Exempt repositories (one main checkout per line in ~/.claude/git-guard-exempt, host-local and
outside the dots repo on purpose: it names projects): there `git commit` and `git merge` pass
-- the user's decision for repos where Claude commits and merges itself. The repo is the one the call
actually targets: the hook input's `cwd`, moved by every `cd` before it in the command and by
`git -C`, resolved to its main checkout (so its worktrees count). Anything that hides the
target (`cd -`, `cd $VAR`, a substitution, `--git-dir`, `GIT_DIR=`) is judged not exempt.
`commit --amend` and `commit -a`/`--all` stay blocked there (they rewrite the last commit of
a shared checkout, or sweep other sessions' edits in), as do push, `rebase -i` and the discard
group. Known gap: a `cd` inside `( ... )` leaks into the commands after the parenthesis.
"""
import json
import os
import re
import shlex
import subprocess
import sys
GIT_BLOCK = {"commit", "push", "clean", "revert", "cherry-pick"}
MERGE_OK = {"--abort", "--quit", "--continue"}
REBASE_BLOCK = {"-i", "--interactive", "--autostash"}
STASH_BLOCK = {"drop", "pop", "clear"}
BRANCH_FORCE = {"-D", "-f", "--force", "-M"}
RESET_MODES = {"--hard", "--soft", "--merge", "--keep"}
UNSTAGE_ALL = {".", ":/", "*", ":"}
_HEX = re.compile(r"^[0-9a-f]{7,40}$")
def looks_like_ref(a):
return (a in ("HEAD", "ORIG_HEAD", "FETCH_HEAD", "MERGE_HEAD") or a.startswith("refs/")
or "~" in a or "^" in a or "@{" in a or bool(_HEX.match(a)))
GH_PR_BLOCK = {"merge", "close"}
# `gh pr edit` may only retitle and redescribe; these take their value as the next word (or as
# `--title=x` / `-tx`).
GH_EDIT_OK = {"-t", "--title", "-b", "--body", "-F", "--body-file", "-R", "--repo"}
# Repositories (main checkouts; their worktrees count) where Claude commits and merges itself:
# one path per line, `#` comments; a missing file exempts nothing. GIT_GUARD_EXEMPT
# (colon-separated) replaces the file for the test matrix; it is read from the hook's own
# environment (Claude Code's), which a prefix on the checked command cannot reach.
EXEMPT_FILE = "~/.claude/git-guard-exempt"
EXEMPT_VERBS = {"commit", "merge"}
# `git commit` options whose value is the next word (or, for the short ones, the rest of the word).
COMMIT_ARG_SHORT = set("mFCct")
COMMIT_ARG_LONG = {"--message", "--file", "--author", "--date", "--reuse-message", "--reedit-message",
"--fixup", "--squash", "--template", "--trailer", "--cleanup", "--pathspec-from-file"}
# global options that take a *separate* argument; the `--opt=value` spelling is one token.
GIT_OPT_ARG = {"-C", "-c", "--git-dir", "--work-tree", "--exec-path", "--namespace",
"--super-prefix", "--config-env"}
GH_OPT_ARG = {"-R", "--repo"}
SHELLS = {"sh", "bash", "dash", "zsh", "ksh", "fish"}
# `<<'EOF' ... EOF` / `<<-EOF ... EOF`: drop the body, keep the command around it.
_HEREDOC = re.compile(r"<<-?\s*(['\"]?)(\w+)\1[^\n]*\n.*?\n[ \t]*\2[ \t]*(?=\n|$)", re.S)
# innermost `$(...)` / `...` command substitutions (peeled repeatedly for nesting).
_SUBST = re.compile(r"\$\(([^()]*)\)|`([^`]*)`")
# tokens that end one simple command and start the next.
_SEP = {";", ";;", "|", "||", "|&", "&", "&&", "(", ")"}
def _skip_opts(args, with_arg):
j = 0
while j < len(args) and args[j].startswith("-"):
j += 2 if args[j] in with_arg else 1
return j
def exempt_repos():
env = os.environ.get("GIT_GUARD_EXEMPT")
if env is not None:
paths = env.split(":")
else:
try:
with open(os.path.expanduser(EXEMPT_FILE)) as f:
paths = [ln.split("#", 1)[0].strip() for ln in f]
except OSError:
return set()
return {os.path.realpath(os.path.expanduser(p)) for p in paths if p}
def main_checkout(d):
"""The main checkout of the repository `d` lies in (a worktree resolves to it), or None."""
try:
out = subprocess.run(["git", "-C", d, "rev-parse", "--path-format=absolute", "--git-common-dir"],
capture_output=True, text=True, timeout=3)
except (OSError, subprocess.SubprocessError):
return None
common = out.stdout.strip().rstrip("/")
if out.returncode != 0 or not common:
return None
return os.path.realpath(os.path.dirname(common))
def in_exempt_repo(opts, cwd, pre):
"""Whether a git call with global options `opts`, run from `cwd` after the words `pre` of
its own command (`env X=1`, ...), targets an exempt repository."""
exempt = exempt_repos()
if not exempt or cwd is None or any(t.startswith(("GIT_DIR=", "GIT_WORK_TREE=", "GIT_COMMON_DIR="))
for t in pre):
return False
d, j = cwd, 0
while j < len(opts):
a = opts[j]
if a in ("--git-dir", "--work-tree") or a.startswith(("--git-dir=", "--work-tree=")):
return False
if a == "-C":
if j + 1 >= len(opts) or "SUBST" in opts[j + 1] or "$" in opts[j + 1]:
return False
d = os.path.join(d, os.path.expanduser(opts[j + 1]))
j += 2 if a in GIT_OPT_ARG else 1
return main_checkout(d) in exempt
def commit_rewrites_or_sweeps(rest):
"""`commit --amend` (rewrites the last commit) or `-a`/`--all` (takes in every modified
tracked file, other sessions' edits included)."""
skip = False
for a in rest:
if skip:
skip = False
continue
if a == "--":
break
if a in ("--amend", "--all"):
return True
if a in COMMIT_ARG_LONG:
skip = True
elif a.startswith("-") and not a.startswith("--"):
for k, ch in enumerate(a[1:], 1):
if ch == "a":
return True
if ch in COMMIT_ARG_SHORT:
skip = k == len(a) - 1 # the value is the next word
break
return False
def change_dir(cwd, args):
"""Where `cd args` leaves the shell started in `cwd`; None when that cannot be told."""
args = [a for a in args if a not in ("-L", "-P", "--")]
if not args:
return os.path.expanduser("~")
t = args[0]
if t == "-" or "SUBST" in t or "$" in t or (cwd is None and not t.startswith(("/", "~"))):
return None
return os.path.normpath(os.path.join(cwd or "/", os.path.expanduser(t)))
def git_reason(args, cwd=None, pre=()):
j = _skip_opts(args, GIT_OPT_ARG)
if j >= len(args):
return None
sub, rest = args[j], args[j + 1:]
if (sub in EXEMPT_VERBS and not (sub == "commit" and commit_rewrites_or_sweeps(rest))
and in_exempt_repo(args[:j], cwd, pre)):
return None
if sub in GIT_BLOCK:
return f"git {sub}"
if sub == "rebase":
flag = next((a for a in rest if a in REBASE_BLOCK), None)
if flag == "--autostash" or any(o.lower().startswith("rebase.autostash") for o in args[:j]):
return "git rebase --autostash (stashes other sessions' uncommitted edits)"
return f"git rebase {flag} (interactive history rewrite)" if flag else None
if sub == "reset":
opts = [a for a in rest if a.startswith("-") and a != "--"]
if RESET_MODES & set(opts):
return "git reset --hard/--soft/--merge/--keep (moves HEAD)"
if "-p" in opts or "--patch" in opts or "--" in rest:
return None # interactive, or the explicit path form
pos = [a for a in rest if not a.startswith("-")]
if not pos or pos == ["HEAD"]:
return "git reset (unstages everything, other sessions' rounds included)"
if len(pos) == 1 and (looks_like_ref(pos[0]) or not os.path.exists(pos[0])):
return "git reset <commit> (moves HEAD)"
return None # `reset HEAD <paths>` / `reset <paths>`
if sub == "merge" and not (MERGE_OK & set(rest)):
return "git merge (creates a commit)"
if sub == "restore":
staged = any(a in ("--staged", "-S") for a in rest)
worktree = any(a in ("--worktree", "-W") for a in rest)
if not staged or worktree:
return "git restore (discards working-tree changes)"
if UNSTAGE_ALL & {a for a in rest if not a.startswith("-")}:
return "git restore --staged . (unstages everything, other sessions' rounds included)"
if sub == "checkout" and ("--" in rest or "." in rest or "-f" in rest or "--force" in rest):
return "git checkout -- <paths> (discards working-tree changes)"
if sub == "stash" and rest and rest[0] in STASH_BLOCK:
return f"git stash {rest[0]}"
if sub == "branch" and BRANCH_FORCE & set(rest):
return "git branch -D/-f (force-deletes or force-moves a branch)"
return None
def gh_edit_extra(rest):
"""The first `gh pr edit` option that is neither the title nor the body, else None."""
k = 0
while k < len(rest):
a = rest[k]
if a == "--":
break
name = a.split("=", 1)[0]
if name in GH_EDIT_OK:
k += 2 if name == a else 1 # skip the value, which may well start with `-`
continue
if a.startswith("-") and not (a[:2] in GH_EDIT_OK and not a.startswith("--")):
return a
k += 1
return None
def gh_reason(args):
j = _skip_opts(args, GH_OPT_ARG)
if j >= len(args) or args[j] != "pr":
return None
rest = args[j + 1:]
k = _skip_opts(rest, GH_OPT_ARG)
if k >= len(rest) or "--help" in rest:
return None
sub, rest = rest[k], rest[k + 1:]
if sub in GH_PR_BLOCK:
return f"gh pr {sub}"
if sub == "create" and not any(a in ("-H", "--head") or a.startswith("--head=")
or (a.startswith("-H") and not a.startswith("--")) for a in rest):
return "gh pr create without --head: gh would push the branch itself"
if sub == "edit":
extra = gh_edit_extra(rest)
if extra:
return f"gh pr edit {extra.split('=', 1)[0]}: only --title / --body edits are allowed"
return None
def tokenize(text):
"""Quote-aware shell words; the separator characters come out as their own tokens
(shlex punctuation mode). Comment handling is off: a `#` mid-word must not swallow
the rest of the line."""
lex = shlex.shlex(text, posix=True, punctuation_chars=True)
lex.whitespace_split = True
lex.commenters = ""
try:
return list(lex)
except ValueError: # unbalanced quotes: best effort
return text.split()
def segments(toks):
seg = []
for t in toks:
if t in _SEP:
if seg:
yield seg
seg = []
else:
seg.append(t)
if seg:
yield seg
def scan(text, depth=0, cwd=None):
"""Reason string for the first blocked invocation in `text` (run from `cwd`), else None."""
if depth > 4:
return None
text = _HEREDOC.sub(" ", text)
# command substitutions: scan each body on its own, then collapse it to a plain word so
# the enclosing command still parses (`git -C $(pwd) push` -> `git -C SUBST push`).
bodies = []
def _grab(m):
bodies.append(m.group(1) if m.group(1) is not None else m.group(2))
return " SUBST "
prev = None
while prev != text:
prev, text = text, _SUBST.sub(_grab, text)
for body in bodies:
r = scan(body, depth + 1, cwd)
if r:
return r
for toks in segments(tokenize(text)):
if toks[0] == "cd":
cwd = change_dir(cwd, toks[1:])
continue
if toks[0] in ("pushd", "popd"):
cwd = None
continue
for i, tok in enumerate(toks):
base = os.path.basename(tok)
r = None
if base == "git":
r = git_reason(toks[i + 1:], cwd, toks[:i])
elif base == "gh":
r = gh_reason(toks[i + 1:])
elif base == "eval":
r = scan(" ".join(toks[i + 1:]), depth + 1, cwd)
elif base in SHELLS and "-c" in toks[i + 1:]:
k = toks.index("-c", i + 1) # `sh -c '<cmd>'`: the real command is one word
if k + 1 < len(toks):
r = scan(toks[k + 1], depth + 1, cwd)
if r:
return r
return None
def main():
try:
data = json.load(sys.stdin)
if data.get("tool_name", "Bash") != "Bash":
return
cmd = (data.get("tool_input") or {}).get("command") or ""
reason = scan(cmd, 0, data.get("cwd") or os.getcwd()) if cmd else None
except Exception:
return # fail open: the deny list still applies
if reason:
short = cmd.strip().splitlines()[0]
short = short if len(short) <= 80 else short[:77] + "..."
hint = ("On a PR Claude reads, opens one when asked (with --head <pushed branch>) and edits its "
"--title / --body; pushing, merging, closing and every other edit are the user's."
if reason.startswith("gh ") else
"Rebase with a plain `git rebase` on a clean tree, and only when the user asked; if the "
"tree holds other sessions' edits, tell the user instead of stashing them."
if reason.startswith("git rebase") else
"The user commits, pushes and merges manually (global CLAUDE.md): stage and stop, "
"and draft the message with /commit-msg.")
sys.stderr.write(f"git-guard: blocked `{short}` ({reason}). {hint}\n")
sys.exit(2)
if __name__ == "__main__":
main()
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""UserPromptExpansion hook: run a skill TUI-side, without a model turn.
Custom slash commands in Claude Code are prompts -- typing `/x` expands skills/x/SKILL.md
and sends it to the model. For a command that is really just a local action (flip a
setting, print a state) that round trip is waste. This hook gives any skill a TUI-side
implementation: if `~/.claude/skills/<command_name>/local.py` exists, it is executed with
the command's arguments, its output is shown to you, and the expansion is blocked (exit 2),
so nothing reaches the model. Skills without a local.py expand as usual (exit 0).
Order matters: the hook fires AFTER the skill body has been expanded, so any `!` inline
commands in that SKILL.md have already run by the time this executes. A skill with a
local.py must therefore not also apply its action via `!` -- it would happen twice.
Input (stdin JSON): command_name, command_args (list), expanded_prompt, cwd, ...
Fails open: any error here means exit 0 and the normal expansion goes ahead.
"""
import json
import os
import subprocess
import sys
def main():
try:
data = json.load(sys.stdin)
name = data.get("command_name") or ""
args = data.get("command_args") or []
if isinstance(args, str):
args = args.split()
if not name or "/" in name or name.startswith("."):
return
script = os.path.expanduser(f"~/.claude/skills/{name}/local.py")
if not os.path.isfile(script):
return
r = subprocess.run(
[sys.executable, script, *[str(a) for a in args]],
capture_output=True, text=True, timeout=20, cwd=data.get("cwd") or None,
)
except Exception:
return # fail open: let the skill expand normally
out = (r.stdout or "") + (r.stderr or "")
sys.stderr.write(out.rstrip("\n") + f"\n[/{name}: handled TUI-side by skills/{name}/local.py, no model turn]\n")
sys.exit(2)
if __name__ == "__main__":
main()
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Notification hook: a desktop notification when Claude is waiting on you.
settings.json wires it to `idle_prompt|permission_prompt` (the Notification matcher is the
`notification_type`). Push notifications are off in this setup, so this is the local
counterpart of pi's notify.ts. Uses notify-send where present (the Wayland/GUI hosts) and
silently no-ops on a headless box or without a session bus. Payload fields are read
defensively -- the docs do not pin the Notification input schema: `message`, `title`,
`notification_type`, `cwd`.
"""
import json
import os
import shutil
import subprocess
import sys
TITLES = {
"idle_prompt": "Claude Code is waiting for you",
"permission_prompt": "Claude Code needs a permission",
}
def main():
try:
data = json.load(sys.stdin)
except Exception:
return
exe = shutil.which("notify-send")
if not exe:
return
kind = data.get("notification_type") or "notification"
title = data.get("title") or TITLES.get(kind, "Claude Code")
body = (data.get("message") or "").strip() or kind
cwd = data.get("cwd") or ""
if cwd:
home = os.path.expanduser("~")
body += "\n" + (("~" + cwd[len(home):]) if cwd.startswith(home) else cwd)
try:
subprocess.run(
[exe, "--app-name=Claude Code", "--urgency=normal", "--expire-time=8000",
# same tag -> a newer notification replaces the previous one instead of stacking
f"--hint=string:x-canonical-private-synchronous:claude-code-{kind}",
title, body],
timeout=5, capture_output=True,
)
except Exception:
pass
if __name__ == "__main__":
main()