dots: public mirror (history reset after licence cleanup)
This commit is contained in:
commit
693822ad5f
226 files changed
+22502
No files matched your search
@@ -0,0 +1,179 @@
|
||||
# Claude Code config
|
||||
|
||||
Portable [Claude Code](https://claude.com/claude-code) customizations, synced via these
|
||||
dots. Claude Code still uses its default `~/.claude/` directory; we surface the tracked
|
||||
files below into it via per-file/dir symlinks, so edits made through Claude write straight
|
||||
back into this repo.
|
||||
|
||||
## What's tracked here
|
||||
|
||||
- `settings.json` — global settings: permissions (deny git push, `gh pr merge` / `close`,
|
||||
and reads of secret files; ask before `gh pr create` and `git rebase`; allow `gh` reads, `gh pr edit`, `gh workflow run`
|
||||
and `gh run rerun`; `git commit` is left to `hooks/git-guard.py`, which exempts listed repos), default `model`, `enabledPlugins`, vim mode, dark theme, `effortLevel`,
|
||||
fullscreen TUI, `statusLine`, `hooks`, `worktree` defaults, a generic `autoMode.environment`, …
|
||||
Nothing in here may name a specific project, path or remote: this file is published by the
|
||||
public mirror, and the auto-mode classifier only reads `autoMode` from user/managed settings
|
||||
anyway (never from a project's `.claude/settings*.json`).
|
||||
- `statusline.py` — rich status line (dir, git, unresolved PR review threads, model, context %, cost, disk — system
|
||||
metrics live in the tmux bar).
|
||||
See [StatusBar.md](StatusBar.md) for what each segment and colour means.
|
||||
- `keybindings.json` — custom keybindings: vim-style scroll/navigation (`alt+j/k` and
|
||||
`ctrl+shift+j/k` scroll by line — kitty's own `kitty_mod+j/k` scroll only its main-screen
|
||||
scrollback and pass the key through to the fullscreen TUI's alternate screen, so they do not
|
||||
shadow these; dropped once by mistake on 2026-09-15), plus `ctrl+x v` for the
|
||||
verbose transcript view (`app:toggleTranscript`, same keystroke as opencode's `<leader>v`; the
|
||||
default `ctrl+o` still works, and `ctrl+e` inside the view expands everything).
|
||||
- `CLAUDE.md` — global user preferences applied to every project.
|
||||
- `hooks/format.py` — PostToolUse hook: formats edited files by extension (stylua / ruff /
|
||||
prettier / gofmt / rustfmt / fish_indent / shfmt / taplo). Every formatter is opt-in: stylua,
|
||||
ruff, prettier and taplo run only where the project has their config file (found walking up);
|
||||
gofmt and rustfmt gate on a project marker (`go.mod` / `Cargo.toml`); fish_indent and shfmt gate
|
||||
on an `.editorconfig` *section* that matches the file. Wired to `Edit|Write` **and** `Bash` —
|
||||
under auto mode Claude edits through the shell, so the Bash branch scans the command for
|
||||
path-like tokens and formats the ones modified in the last 30 s. No-ops if the formatter isn't
|
||||
installed, and always exits 0.
|
||||
- `hooks/git-guard.py` — PreToolUse hook on `Bash`: structurally blocks anything that commits,
|
||||
rewrites history or discards working-tree changes — `git commit` / `push` / `revert` /
|
||||
`cherry-pick` / `rebase -i|--autostash` / `merge` (not `--abort`), `clean` / `reset` in any form that moves HEAD
|
||||
or unstages everything (`reset -- <paths>`, `reset HEAD <path>` stay allowed) / `restore <paths>`
|
||||
(`--staged <path>` is fine, `--staged .` is not) / `checkout --` / `checkout .` / `stash drop|pop|clear` /
|
||||
`branch -D|-f|-M`, and `gh pr merge` / `close`, `gh pr create` without `--head` (gh would push
|
||||
the branch itself) and `gh pr edit` beyond `--title` / `--body` — wherever the flags sit
|
||||
(`git -C . push`, `/usr/bin/git push`, `sh -c 'git push'`), which the prefix-matched deny rules
|
||||
can't. A plain `rebase` and its `--continue` / `--abort` pass: Claude rebases and fixes
|
||||
conflicts when asked (`CLAUDE.md`), and settings.json asks before each `git rebase`. The
|
||||
discard group is what protects parallel sessions sharing one checkout. Exit 2 + a
|
||||
one-line reason. Heredoc bodies are skipped on purpose (file contents). Regression matrix:
|
||||
`bash ~/.claude/hooks/git-guard-test.sh` (a file on purpose — typed inline, the commands under
|
||||
test would trip the live hook). Repos listed in `~/.claude/git-guard-exempt` (host-local, not in
|
||||
this repo — it names projects; one main checkout per line, worktrees included): `commit` and
|
||||
`merge` pass there — judged from the hook input's
|
||||
`cwd`, every `cd` before the call and `git -C` — except `commit --amend` / `-a`. A user-scope deny
|
||||
cannot be lifted for one repo, so `git commit` is off the deny list: the hook is its only
|
||||
structural block.
|
||||
- `hooks/notify.py` — Notification hook (`idle_prompt|permission_prompt`): `notify-send` desktop
|
||||
notification when Claude is waiting on you; no-op on a headless host.
|
||||
- `../tmux/scripts/agent-state.sh` — UserPromptSubmit (busy) / Notification (input) / Stop (done) /
|
||||
StopFailure (error) / SessionEnd (off) hooks, all async: marks the tmux pane this session runs in
|
||||
(`@agent` pane option, drawn as ✓ ? ! after the window name by tmux.conf; visiting the pane
|
||||
greys it out, the next prompt removes it) and buzzes the phone for a new mark on a pane not in
|
||||
view (termux-notification, else a bell). Claude sessions run in daemon-spawned workers with no
|
||||
tmux env, so the script finds the pane by the session name Claude puts in the pane title. Shared with codex
|
||||
(`~/.codex/hooks.json`, untracked), pi and opencode. No-op outside tmux.
|
||||
- `hooks/drift-check.sh` — SessionStart + UserPromptSubmit hook, read-only: fails loudly when a
|
||||
`~/.config/claude/*` file has broken out of the repo into a plain file, or `~/.claude/*` no longer
|
||||
resolves into the dots repo. That is what Claude Code's atomic settings rewrite does through the
|
||||
stow layer — on 2026-09-15 it silently reverted the live config to a stale snapshot for an hour,
|
||||
dropping four hook events. At session start the warning is shown to you (exit 2, session goes
|
||||
on); on each prompt any drift is fed to Claude as context so it reports it. Fix is still
|
||||
`link.sh` (heals identical copies, warns otherwise).
|
||||
- `hooks/local-commands.py` — UserPromptExpansion hook: **TUI-side slash commands**. When you type
|
||||
`/x` and `skills/x/local.py` exists, the hook runs it with the arguments, shows its output to you
|
||||
and blocks the expansion (exit 2), so no prompt reaches the model and it costs nothing. Skills
|
||||
without a `local.py` expand as usual. Caveat baked into the design: the hook fires *after* the
|
||||
skill body expanded, so a skill with a `local.py` must not also act via a `!` inline command.
|
||||
- `skills/` — custom [Agent Skills](https://code.claude.com/docs/en/skills). See **Skills** below.
|
||||
- `link.sh` — idempotent bootstrap that creates the `~/.claude` symlinks below.
|
||||
- `../git/claude-commit-msg` + `../git/hooks/prepare-commit-msg` — the commit-message handoff.
|
||||
A session pipes its suggestion into `claude-commit-msg save` (run inside the target repo), which
|
||||
stores it as its own file under `$(git rev-parse --git-path CLAUDE_COMMIT_MSG.d)/` **with the paths
|
||||
it staged**; on the next `git commit` / lazygit `C` the hook prefills the editor with the message(s)
|
||||
whose paths are part of that commit and consumes them (`used/`). Parallel sessions therefore never
|
||||
overwrite each other, and committing one session's files gets that session's message.
|
||||
`claude-commit-msg list` shows what is pending. The old single `CLAUDE_COMMIT_MSG` file is still
|
||||
honoured. Both tracked here (deployed to `~/.config/git/`); the hook is installed **per repo** — see
|
||||
setup step 4 — and deliberately not via a global `core.hooksPath`, which would override a project's
|
||||
own hooks. The prefill only runs for an editor commit: lazygit's `c` panel passes the message to git
|
||||
directly, so the hook skips and the suggestion stays pending.
|
||||
|
||||
The `settings.json` hook commands for the newer scripts are wrapped in `[ -f … ]`, so a host that
|
||||
has pulled the repo but not yet re-stowed just skips them instead of blocking every Bash call.
|
||||
|
||||
Paths inside `settings.json` reference `~/.claude/...` via `$HOME`/`PATH` (`/usr/bin/env
|
||||
python3 ~/.claude/...`), so they work regardless of the username, python location, or where the
|
||||
dots repo is cloned (`~/.dots`, …).
|
||||
|
||||
## What is **not** tracked (stays local, per device)
|
||||
|
||||
Everything else under `~/.claude/` is machine-specific or secret and must never be committed:
|
||||
credentials (`.credentials.json`), session history, `projects/` (transcripts + memory),
|
||||
caches, and the `plugins/` cache/binaries.
|
||||
|
||||
## Setup on a new device
|
||||
|
||||
```sh
|
||||
# 1. Deploy the dotfiles repo — install.sh stows ~/.config/claude AND runs link.sh for you
|
||||
cd ~/.dots && ./install.sh
|
||||
|
||||
# 2. Launch Claude and log in once (credentials are NOT synced)
|
||||
claude
|
||||
|
||||
# 3. Reinstall the plugins from settings.json -> enabledPlugins
|
||||
# (typescript-lsp, frontend-design — anthropics/claude-plugins-official) via /plugin.
|
||||
# Optional: install any formatters you want the hook to use (stylua, ruff, prettier, …),
|
||||
# and libnotify (notify-send) on GUI hosts for hooks/notify.py.
|
||||
```
|
||||
|
||||
```fish
|
||||
# 4. In every repo you commit in: install the commit-message prefill hook. New clones/inits get it
|
||||
# from ~/.config/git/template (init.templateDir) once that template hook is a symlink to it too.
|
||||
ln -sf ~/.config/git/hooks/prepare-commit-msg (git rev-parse --git-path hooks)/prepare-commit-msg
|
||||
```
|
||||
|
||||
`install.sh` deploys `~/.config/claude` (via stow) and then runs `link.sh` automatically. You only
|
||||
need to run `link.sh` by hand (`bash ~/.config/claude/link.sh`) if a link later gets clobbered
|
||||
(e.g. Claude's `/config` replaces one with a plain file) — it's idempotent and self-healing.
|
||||
|
||||
Tracked *files* in `~/.claude` link straight at the repo copy, not through `~/.config/claude`:
|
||||
Claude Code follows one symlink hop and then replaces the file atomically (temp + rename), so the
|
||||
old two-hop chain lost its middle link to a plain file on every settings write (`/model`, effort,
|
||||
plugins, `/config`) and the repo stopped seeing changes. With one hop the rename lands in the
|
||||
checkout. Dirs (`hooks`, `skills`) still go through `~/.config/claude`.
|
||||
|
||||
A **new skill/hook** added to the repo shows up after a re-stow — `./install.sh` (or `dotsync`) links
|
||||
the new file into `~/.config/claude`, which `link.sh` then surfaces into `~/.claude`.
|
||||
|
||||
## Skills
|
||||
|
||||
Custom skills live in `skills/<name>/SKILL.md` (the directory name is the `/command`) and are
|
||||
linked in as `~/.claude/skills`. All are `disable-model-invocation: true` — explicit `/` only,
|
||||
so Claude never auto-triggers them. Run them inside the repo whose branch you're working on.
|
||||
|
||||
- **`/review-branch [base]`** — reviews the current branch's diff (vs its merge-base with the
|
||||
base branch) for 🐞 bugs / 🔒 security / ⚡ optimizations / 📖 readability, reports grouped
|
||||
findings with `file:line`, then applies the readability + safe fixes *after you approve*. Never
|
||||
commits.
|
||||
Borrows `/code-review`'s discipline: CLAUDE.md-aware, changed-lines-only, verified bugs with a
|
||||
false-positive filter (skips what linters/CI catch and pre-existing issues). Ends by pointing
|
||||
you at the relevant built-in follow-ups (`/security-review`, `/code-review`, `/verify`, …).
|
||||
- **`/pr-description [base]`** — auto-detects this repo's GitHub PR template
|
||||
(`.github/pull_request_template.md`, …), fills it from the branch diff + commits, prints a
|
||||
copy-paste markdown block, and copies it to the clipboard with `wl-copy`. Leaves verification
|
||||
checkboxes for you; never creates/pushes the PR.
|
||||
- **`/commit-msg [hint]`** — reads the **staged** diff, infers the repo's commit style from recent
|
||||
`git log` (e.g. this repo's `[Scope] summary`), drafts a matching message, prints it, and saves
|
||||
it for the `prepare-commit-msg` hook (lazygit `C` prefills it). Never stages or commits — draft
|
||||
only.
|
||||
- **`/verbose [on|off|status]`** — flips the *persisted* verbose view for the current project:
|
||||
`viewMode` (`verbose` / `default` — the key that actually decides the view and beats a sticky
|
||||
`/focus` choice for new sessions) plus `verbose` and `showThinkingSummaries`, written to the
|
||||
project's `.claude/settings.local.json` (machine-local, never committed) rather than the tracked
|
||||
`settings.json`, so a toggle never shows up as a dots diff. Runs **TUI-side** — `local.py` via
|
||||
`hooks/local-commands.py`, no model turn — with the SKILL.md body as the fallback on a host
|
||||
where the hook isn't deployed. The *live* toggle is a keypress: `ctrl+x v` / `ctrl+o`.
|
||||
- **`/pr-loop [pr]`** — babysits the current branch's PR in a self-paced loop: fixes review
|
||||
comments that don't need your input — from **any** reviewer (Codex, Claude, humans) plus any
|
||||
`@claude` request — `git add`s them, drafts the commit message (`/commit-msg` style) and marks
|
||||
each thread with a reaction instead of an "Addressed — …" reply: **👍** fixed, **👀** parked for
|
||||
your decision, **👎** a bot false positive (bots only, always with a one-line why). Then pings you
|
||||
to commit & push and re-checks every ~10 min (via `ScheduleWakeup`). Resolves threads once their
|
||||
fix is pushed — dismissals right away, since there's nothing to land. Stops when no unresolved comments
|
||||
remain or the automated reviewers (Codex/Claude) hit their limit. Prep-only — never
|
||||
commits/pushes/merges; needs `gh` authed and the session left open. Each cycle it prints when it
|
||||
will re-check and that `Esc` (between cycles) stops it; on the last cycle it prints a clear
|
||||
**"Finished — no more active issues"** and does not reschedule.
|
||||
|
||||
## Adding more config later
|
||||
|
||||
Drop the file/dir under `.config/claude/` here, add its name to the `items` list in `link.sh`,
|
||||
and re-run `bash ~/.config/claude/link.sh`. For example `commands/` or `agents/`.
|
||||
@@ -0,0 +1,83 @@
|
||||
# Status line (`statusline.py`)
|
||||
|
||||
The custom Claude Code status line, ordered **work info (left) → system info (right)**,
|
||||
segments joined by a light-gray `│`. It's **responsive**: always a single line — if the
|
||||
rendered width would exceed the terminal (`$COLUMNS`, which Claude Code re-exports on
|
||||
resize), trailing (lowest-priority) segments are dropped from the right until it fits.
|
||||
|
||||
Wide — everything:
|
||||
|
||||
```
|
||||
📁 ~/.dots │ 🌿 .dots main* │ 💬 #42 3 · codex 2 │ 🤖 Fable 5 (1M) · xhigh │ 📝 84% (843k) │ 📊 34% 2h54m │ 💰 $0.40 $12.00/h │ 🔢 ↑63M ↓595k │ ⚡ 63 t/s │ ♻️ 91% 1h │ 💾 81%
|
||||
```
|
||||
|
||||
Narrow — trailing segments trimmed:
|
||||
|
||||
```
|
||||
📁 ~/.dots │ 🌿 .dots main* │ 💬 #42 3 · codex 2 │ 🤖 Fable 5 (1M) · xhigh │ 📝 84% (843k) │ 📊 34% 2h54m
|
||||
```
|
||||
|
||||
Every segment is defensive: if its data is missing or a command fails, the segment is
|
||||
simply omitted (the bar never crashes the UI). Secondary detail (the parts in light gray)
|
||||
is supplementary to the main colored value.
|
||||
|
||||
## Live segments
|
||||
|
||||
| | Segment | Shows | Notes |
|
||||
|---|---|---|---|
|
||||
| | **Vim mode** | `[I]`/`[N]`/`[V]` editor mode | only with `editorMode: vim`; pair with `hideVimModeIndicator: true` so the built-in one doesn't duplicate it |
|
||||
| 📁 | **Directory** | Current working dir, with `~` for home | cyan |
|
||||
| 🌿 | **Git** | `repo branch` + `*` if dirty + `↑N`/`↓N` ahead/behind upstream | repo = magenta; branch = green when clean, yellow + red `*` when dirty; `↑` cyan, `↓` yellow. Omitted outside a repo |
|
||||
| 💬 | **PR review threads** | `#N` of the current branch's open PR + its **unresolved review threads** (any author, outdated ones included; `+` past 100), Codex's share broken out as `· codex N`; green `✓` when none are left | A thread counts for whoever opened it (its first comment's author; Codex = login matching `codex`, as in `/pr-loop`). PR-conversation comments are not counted — they have no resolved state, so a summary or an LGTM would never let it reach zero. A GitHub round trip is ~0.7 s, so a render only reads the per-branch cache `~/.claude/cache/statusline.pr.<hash>.json` and, once it is older than 90 s, spawns a detached `statusline.py --pr-refresh` that updates it (one at a time, via a `.lock` claim) — new counts show on the next render. A failed fetch (no GitHub remote — e.g. this repo on gitea —, gh not authed, offline) backs off 10 min and keeps the last counts with a gray `?`. Omitted with no `gh`, no open PR or a detached HEAD |
|
||||
| 🤖 | **Model** | Active model display name + `· effort` level (`low`/`medium`/`high`/`xhigh`) | name = blue, effort = light gray; effort omitted for models without the param |
|
||||
| 📝 | **Context** | `% of context window used` + `(Nk)` tokens | usage comes from the payload's `context_window` (`used_percentage` + `current_usage`, Claude Code 2.1.x); the transcript's last `message.usage` is only a fallback. Window from `context_window.context_window_size`, then `(1M …)` in the display name, else 200k — **not** from `model.id`, which arrives with any `[1m]` suffix already stripped. Adds a red **⚠compact** at ≥80% |
|
||||
| 📊 | **5h usage** | `% of the 5-hour rolling limit used` + time until it resets | from `rate_limits.five_hour`; Pro/Max only, and absent until the first API response of a session |
|
||||
| 💰 | **Cost** | `$` session cost so far + `$/h` burn rate | burn rate shown once the session exceeds ~30s |
|
||||
| 🔢 | **Session tokens** | `↑` input + `↓` output tokens used so far this session (cumulative, `k`/`M`) | summed over the transcript's assistant `message.usage` blocks, de-duplicated by message id (one line per content block shares the same usage). Input = `input + cache_creation + cache_read` — everything billed as input, so on a 1M session it dwarfs output (every call re-reads the cached prefix). Main transcript only: subagent usage lives in separate sidechain files. Incremental: a per-session state file `~/.claude/cache/statusline.tokens.<session>.json` remembers the byte offset already summed, so each refresh parses only the new tail (warm ≈ 0.2 ms), at most 8 MiB per refresh (≈ 150 ms) — Claude Code kills a status script when the next refresh fires, so a cold scan of a huge resumed transcript is spread over a few refreshes (totals climb, then settle) instead of restarting from zero each time. Stale state files are pruned after 7 days once 50+ pile up. Omitted when there is no transcript; `↑` cyan, `↓` green, no thresholds |
|
||||
| ⚡ | **Decode speed** | `N t/s` — tokens per second the model is generating | duration-weighted mean over the last 8 thinking blocks of the main conversation: `thinking_tokens / thinkingDurationMs` from the same transcript scan (blocks under 1 s or 50 tokens skipped). The only clean per-call timing Claude Code records: the payload's `cost.total_api_duration_ms` also absorbs subagent and advisor calls (it grew 28 s in a 12 s wall interval with no main-conversation completion) and its `output_tokens` is sometimes a mid-stream partial, so neither can give a rate. Includes first-token latency, so short blocks read a little low and long ones converge on the real decode speed (Fable 5.1 measured 60–85 t/s). Needs thinking enabled — omitted until a thinking block has completed, never shown with thinking off |
|
||||
| ♻️ | **Prompt cache** | hit `%` (higher is better) + cache TTL (`5m` / `1h`), yellow `·cold` once it has expired | from the payload's `prompt_cache` (2.1.260+: `hit_ratio` 0–1, `ttl`, `warm`); computed from usage on older payloads. A `1h` TTL is what keeps a 10-min `/pr-loop` cadence warm |
|
||||
| 💾 | **Disk** | `% used` of the filesystem at the cwd | from `statvfs` |
|
||||
|
||||
## Colour legend
|
||||
|
||||
Most numbers are **green / yellow / red** by threshold — green = healthy, red = needs
|
||||
attention. Light gray = secondary detail. Thresholds (`green < … < yellow < … ≤ red`):
|
||||
|
||||
| Segment | green | yellow | red |
|
||||
|---|---|---|---|
|
||||
| Context | `< 50%` | `50–80%` | `≥ 80%` (⚠compact) |
|
||||
| PR review threads | `✓` none unresolved | thread count | `codex N` |
|
||||
| 5h usage | `< 50%` | `50–80%` | `≥ 80%` |
|
||||
| Decode speed (inverted) | `≥ 40 t/s` | `20–40 t/s` | `< 20 t/s` |
|
||||
| Prompt cache (inverted) | `≥ 80%` | `50–80%` | `< 50%` |
|
||||
| Disk | `< 75%` | `75–90%` | `≥ 90%` |
|
||||
|
||||
> Light gray is `\033[37m`; dimming (`\033[2m`) is disabled because it blended the gray
|
||||
> detail text into dark terminal backgrounds. To go brighter, set `"gray"` to `\033[97m`
|
||||
> (bright white) in the `C` table near the top of `statusline.py`.
|
||||
|
||||
## Optional segments (defined but not shown)
|
||||
|
||||
These functions exist in `statusline.py` but aren't in the output. Enable one by adding it
|
||||
to the `work` or `system` list in `main()`:
|
||||
|
||||
RAM/CPU/temp were **retired 2026-07-26**: the status line only refreshes on message
|
||||
events, so system metrics sat visibly stale between turns — the tmux status bar
|
||||
(`tmux/scripts/`) owns live system metrics now.
|
||||
|
||||
| | Function | Shows |
|
||||
|---|---|---|
|
||||
| 🧠 | `ram_segment` | `% used` + `used/totalG` from `/proc/meminfo` (green `<70%` / yellow / red `≥85%`) |
|
||||
| 🖥️ | `cpu_segment` | `% busy` (diffed `/proc/stat` snapshot) + loadavg + cores (green `<60%` / red `≥85%`) |
|
||||
| 🌡️ | `temp_segment` | hottest CPU thermal zone °C (green `<60` / red `≥80`) |
|
||||
| ✏️ | `velocity_segment` | `+added/-removed` lines this session + lines/min |
|
||||
| ⚙️ | `api_segment` | share of wall-clock time spent in API/inference |
|
||||
| | `version_segment` | Claude Code version (`vX.Y.Z`) |
|
||||
| 🎨 | `style_segment` | active output-style name |
|
||||
|
||||
## Where it lives
|
||||
|
||||
`statusline.py` is tracked in this repo and symlinked to `~/.claude/statusline.py`;
|
||||
`settings.json` runs it via `statusLine` (`/usr/bin/env python3 ~/.claude/statusline.py`) on every
|
||||
message event and, through `refreshInterval: 60`, once a minute while the session idles — so the PR
|
||||
count moves while you wait on a review. Edits take effect on the next status refresh.
|
||||
Executable
+32
@@ -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
|
||||
Executable
+254
@@ -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
@@ -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
|
||||
}
|
||||
Executable
+369
@@ -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
@@ -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()
|
||||
Executable
+51
@@ -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()
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"$schema": "https://www.schemastore.org/claude-code-keybindings.json",
|
||||
"$docs": "https://code.claude.com/docs/en/keybindings",
|
||||
"bindings": [
|
||||
{
|
||||
"context": "Chat",
|
||||
"bindings": {
|
||||
"shift+enter": "chat:newline",
|
||||
"ctrl+x v": "app:toggleTranscript"
|
||||
}
|
||||
},
|
||||
{
|
||||
"context": "Transcript",
|
||||
"bindings": {
|
||||
"ctrl+x v": "app:toggleTranscript"
|
||||
}
|
||||
},
|
||||
{
|
||||
"context": "Global",
|
||||
"bindings": {
|
||||
"alt+j": "scroll:lineDown",
|
||||
"alt+k": "scroll:lineUp",
|
||||
"ctrl+shift+j": "scroll:lineDown",
|
||||
"ctrl+shift+k": "scroll:lineUp"
|
||||
}
|
||||
},
|
||||
{
|
||||
"context": "MessageSelector",
|
||||
"bindings": {
|
||||
"g": "messageSelector:top",
|
||||
"shift+g": "messageSelector:bottom"
|
||||
}
|
||||
},
|
||||
{
|
||||
"context": "Select",
|
||||
"bindings": {
|
||||
"g": "select:first",
|
||||
"shift+g": "select:last"
|
||||
}
|
||||
},
|
||||
{
|
||||
"context": "Footer",
|
||||
"bindings": {
|
||||
"j": "footer:down",
|
||||
"k": "footer:up"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Executable
+114
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env bash
|
||||
# Surface this repo's Claude Code config into ~/.claude via symlinks.
|
||||
#
|
||||
# `stow` deploys the repo to ~/.config/claude; Claude itself reads from ~/.claude,
|
||||
# so we link the individual files/dirs across. Idempotent and self-healing: re-run
|
||||
# any time. It also flags any file that has broken out of stow into a plain file —
|
||||
# which silently stops Claude's edits from reaching the repo.
|
||||
# (New skills/hooks added to the repo appear after a re-stow: `./install.sh` or `dotsync`.)
|
||||
#
|
||||
# bash ~/.config/claude/link.sh
|
||||
set -eu
|
||||
|
||||
SRC="$HOME/.config/claude"
|
||||
DST="$HOME/.claude"
|
||||
|
||||
if [ ! -e "$SRC" ]; then
|
||||
echo "error: $SRC not found — run 'cd ~/.dots && ./install.sh' first" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$DST"
|
||||
|
||||
# This repo's claude dir, resolved via link.sh's own symlink (location-independent).
|
||||
repo=$(dirname "$(readlink -f "$SRC/link.sh")")
|
||||
|
||||
# If link.sh itself has broken out of stow into a plain file, $repo resolves to $SRC and
|
||||
# the drift heal below would relink each drifted file onto ITSELF — destroying the only
|
||||
# copy of its content. Refuse to continue. Both sides are canonicalized before comparing:
|
||||
# $repo comes back from readlink -f, so a symlinked component anywhere in the path (say
|
||||
# /home -> /var/home) would otherwise make the two spellings differ and slip the guard.
|
||||
src_real=$(readlink -f "$SRC" || printf '%s' "$SRC")
|
||||
if [ "$repo" = "$src_real" ]; then
|
||||
echo "error: link.sh itself is a plain file (broken out of stow) — re-stow first:" >&2
|
||||
echo " cd ~/.dots && ./install.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Tracked items to expose in ~/.claude. Add new ones (e.g. commands agents) here.
|
||||
items="settings.json statusline.py keybindings.json CLAUDE.md hooks skills"
|
||||
|
||||
# Expose each item in ~/.claude (where Claude actually reads).
|
||||
for item in $items; do
|
||||
[ -e "$SRC/$item" ] || continue
|
||||
# Files link straight at the repo copy, not through ~/.config/claude: Claude Code
|
||||
# resolves ONE symlink hop, then writes atomically (temp + rename) at that path —
|
||||
# verified on 2.1.296 with `claude plugin disable` against a scratch CLAUDE_CONFIG_DIR.
|
||||
# Through a ~/.claude -> ~/.config/claude -> repo chain, every settings write (/model,
|
||||
# effort, plugins, /config) swapped the middle link for a plain file and severed the
|
||||
# repo. One hop puts the rename inside the checkout, so both links survive. A SRC file
|
||||
# that already drifted into a plain file keeps being the target (it may hold the newest
|
||||
# edits) until the drift guard below is reconciled. Dirs keep the stow path.
|
||||
target="$SRC/$item"
|
||||
[ -f "$repo/$item" ] && [ -L "$SRC/$item" ] && target="$repo/$item"
|
||||
if [ -d "$DST/$item" ] && [ ! -L "$DST/$item" ]; then
|
||||
echo "skip ~/.claude/$item (real directory in the way — move it aside first)" >&2
|
||||
continue
|
||||
fi
|
||||
# A plain FILE here means an atomic write replaced the link (Claude writes e.g.
|
||||
# ~/.claude/settings.json) — it may hold newer edits, so never clobber it silently:
|
||||
# heal only when provably lossless, warn otherwise (mirrors the SRC drift guard below).
|
||||
if [ -f "$DST/$item" ] && [ ! -L "$DST/$item" ]; then
|
||||
same=0
|
||||
case "$item" in
|
||||
*.json)
|
||||
python3 -c 'import json,sys; sys.exit(0 if json.load(open(sys.argv[1]))==json.load(open(sys.argv[2])) else 1)' \
|
||||
"$DST/$item" "$SRC/$item" 2>/dev/null && same=1
|
||||
;;
|
||||
*)
|
||||
cmp -s "$DST/$item" "$SRC/$item" && same=1
|
||||
;;
|
||||
esac
|
||||
if [ "$same" != 1 ]; then
|
||||
echo "DRIFT ~/.claude/$item is a real file that differs from the repo copy —" >&2
|
||||
echo " it may hold newer edits. Review, then re-link:" >&2
|
||||
echo " diff '$DST/$item' '$target' # compare; keep whichever is right" >&2
|
||||
echo " ln -sfn '$target' '$DST/$item' # re-link" >&2
|
||||
continue
|
||||
fi
|
||||
echo "healed ~/.claude/$item (plain copy identical to repo — re-linking)"
|
||||
fi
|
||||
ln -sfn "$target" "$DST/$item"
|
||||
echo "linked ~/.claude/$item -> ${target/#$HOME/\~}"
|
||||
done
|
||||
|
||||
# Stow-layer drift guard: each SRC *file* should be a symlink into the repo, so edits
|
||||
# Claude writes (e.g. via /config) flow back and stay tracked. If an atomic write
|
||||
# replaced one with a plain file, it has silently broken out of stow. Auto-heal only
|
||||
# when provably lossless — the plain file is identical to the repo copy (JSON compared
|
||||
# ignoring key order, since /config often just reorders keys). Otherwise warn and stop:
|
||||
# the file may hold newer edits worth diffing in before re-linking.
|
||||
for item in $items; do
|
||||
[ -f "$SRC/$item" ] && [ ! -L "$SRC/$item" ] || continue # a real file where a link belongs
|
||||
same=0
|
||||
if [ -f "$repo/$item" ]; then
|
||||
case "$item" in
|
||||
*.json)
|
||||
python3 -c 'import json,sys; sys.exit(0 if json.load(open(sys.argv[1]))==json.load(open(sys.argv[2])) else 1)' \
|
||||
"$SRC/$item" "$repo/$item" 2>/dev/null && same=1
|
||||
;;
|
||||
*)
|
||||
cmp -s "$SRC/$item" "$repo/$item" && same=1
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
if [ "$same" = 1 ]; then
|
||||
ln -sfrn "$repo/$item" "$SRC/$item" # -r: relative link, so stow keeps owning it
|
||||
echo "healed ~/.config/claude/$item (plain copy identical to repo — re-linked)"
|
||||
continue
|
||||
fi
|
||||
echo "DRIFT ~/.config/claude/$item is a real file that differs from the repo copy —" >&2
|
||||
echo " it may hold edits not yet tracked. Review, then re-link:" >&2
|
||||
echo " diff '$SRC/$item' '$repo/$item' # compare; keep whichever is right" >&2
|
||||
echo " ln -sfrn '$repo/$item' '$SRC/$item' # re-link (relative, stow-owned)" >&2
|
||||
done
|
||||
@@ -0,0 +1,274 @@
|
||||
{
|
||||
"attribution": {
|
||||
"commit": "",
|
||||
"pr": ""
|
||||
},
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(cat:*)",
|
||||
"Bash(head:*)",
|
||||
"Bash(tail:*)",
|
||||
"Bash(sed -n:*)",
|
||||
"Bash(grep:*)",
|
||||
"Bash(rg:*)",
|
||||
"Bash(ls:*)",
|
||||
"Bash(wc:*)",
|
||||
"Bash(git status:*)",
|
||||
"Bash(git diff:*)",
|
||||
"Bash(git log:*)",
|
||||
"Bash(git show:*)",
|
||||
"Bash(git rev-parse:*)",
|
||||
"Bash(git branch:*)",
|
||||
"Bash(git stash list:*)",
|
||||
"Bash(pnpm run:*)",
|
||||
"Bash(pnpm exec:*)",
|
||||
"Bash(node -p:*)",
|
||||
"Bash(gh pr view:*)",
|
||||
"Bash(gh pr list:*)",
|
||||
"Bash(gh pr diff:*)",
|
||||
"Bash(gh pr checks:*)",
|
||||
"Bash(gh pr status:*)",
|
||||
"Bash(gh issue view:*)",
|
||||
"Bash(gh issue list:*)",
|
||||
"Bash(gh issue status:*)",
|
||||
"Bash(gh run view:*)",
|
||||
"Bash(gh run list:*)",
|
||||
"Bash(gh run watch:*)",
|
||||
"Bash(gh workflow view:*)",
|
||||
"Bash(gh workflow list:*)",
|
||||
"Bash(gh repo view:*)",
|
||||
"Bash(gh release view:*)",
|
||||
"Bash(gh release list:*)",
|
||||
"Bash(gh search:*)",
|
||||
"Bash(gh label list:*)",
|
||||
"Bash(gh status:*)",
|
||||
"Bash(gh auth status:*)",
|
||||
"Bash(gh pr edit:*)",
|
||||
"Bash(gh workflow run:*)",
|
||||
"Bash(gh run rerun:*)"
|
||||
],
|
||||
"deny": [
|
||||
"Bash(git push)",
|
||||
"Bash(git push:*)",
|
||||
"Bash(git reset --hard)",
|
||||
"Bash(git reset --hard:*)",
|
||||
"Bash(git clean)",
|
||||
"Bash(git clean:*)",
|
||||
"Bash(gh pr merge)",
|
||||
"Bash(gh pr merge:*)",
|
||||
"Bash(gh pr close)",
|
||||
"Bash(gh pr close:*)",
|
||||
"Read(**/.env)",
|
||||
"Read(**/.env.*)",
|
||||
"Read(**/*.env)",
|
||||
"Read(**/*.pem)",
|
||||
"Read(**/*.key)",
|
||||
"Read(**/*.p12)",
|
||||
"Read(**/*.pfx)",
|
||||
"Read(**/*.keystore)",
|
||||
"Read(**/id_rsa*)",
|
||||
"Read(**/.ssh/**)",
|
||||
"Read(**/.aws/**)",
|
||||
"Read(**/.npmrc)",
|
||||
"Read(**/.netrc)",
|
||||
"Read(**/.git-credentials)",
|
||||
"Read(**/.claude/.credentials.json)",
|
||||
"Read(**/secrets.fish)",
|
||||
"Read(**/*.token)",
|
||||
"Read(**/.envrc)",
|
||||
"Read(**/.gnupg/**)",
|
||||
"Read(**/fish_variables)"
|
||||
],
|
||||
"ask": [
|
||||
"Bash(gh pr create)",
|
||||
"Bash(gh pr create:*)",
|
||||
"Bash(git rebase)",
|
||||
"Bash(git rebase:*)"
|
||||
],
|
||||
"defaultMode": "auto"
|
||||
},
|
||||
"model": "opus",
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "startup|resume",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "f=\"$HOME/.claude/hooks/drift-check.sh\"; if [ -f \"$f\" ]; then exec bash \"$f\"; fi",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"UserPromptSubmit": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "f=\"$HOME/.claude/hooks/drift-check.sh\"; if [ -f \"$f\" ]; then out=$(bash \"$f\" 2>&1); [ -n \"$out\" ] && printf \"%s\\n\" \"$out\"; fi; exit 0",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "f=\"$HOME/.config/tmux/scripts/agent-state.sh\"; [ -x \"$f\" ] && \"$f\" cc busy; exit 0",
|
||||
"timeout": 5,
|
||||
"async": true
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"UserPromptExpansion": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "f=\"$HOME/.claude/hooks/local-commands.py\"; if [ -f \"$f\" ]; then exec /usr/bin/env python3 \"$f\"; fi",
|
||||
"timeout": 25
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "f=\"$HOME/.claude/hooks/git-guard.py\"; if [ -f \"$f\" ]; then exec /usr/bin/env python3 \"$f\"; fi",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "/usr/bin/env python3 ~/.claude/hooks/format.py",
|
||||
"timeout": 20,
|
||||
"statusMessage": "format"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "/usr/bin/env python3 ~/.claude/hooks/format.py",
|
||||
"timeout": 20
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Notification": [
|
||||
{
|
||||
"matcher": "idle_prompt|permission_prompt",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "f=\"$HOME/.claude/hooks/notify.py\"; if [ -f \"$f\" ]; then exec /usr/bin/env python3 \"$f\"; fi",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "idle_prompt|permission_prompt",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "f=\"$HOME/.config/tmux/scripts/agent-state.sh\"; [ -x \"$f\" ] && \"$f\" cc input; exit 0",
|
||||
"timeout": 5,
|
||||
"async": true
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Stop": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "f=\"$HOME/.config/tmux/scripts/agent-state.sh\"; [ -x \"$f\" ] && \"$f\" cc done; exit 0",
|
||||
"timeout": 5,
|
||||
"async": true
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"StopFailure": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "f=\"$HOME/.config/tmux/scripts/agent-state.sh\"; [ -x \"$f\" ] && \"$f\" cc error; exit 0",
|
||||
"timeout": 5,
|
||||
"async": true
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"SessionEnd": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "f=\"$HOME/.config/tmux/scripts/agent-state.sh\"; [ -x \"$f\" ] && \"$f\" cc off; exit 0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"worktree": {
|
||||
"baseRef": "fresh"
|
||||
},
|
||||
"enableWorkflows": false,
|
||||
"statusLine": {
|
||||
"type": "command",
|
||||
"command": "/usr/bin/env python3 ~/.claude/statusline.py",
|
||||
"padding": 0,
|
||||
"refreshInterval": 60,
|
||||
"hideVimModeIndicator": true
|
||||
},
|
||||
"enabledPlugins": {
|
||||
"typescript-lsp@claude-plugins-official": true,
|
||||
"frontend-design@claude-plugins-official": true,
|
||||
"rust-analyzer-lsp@claude-plugins-official": true
|
||||
},
|
||||
"effortLevel": "xhigh",
|
||||
"modelSettings": {
|
||||
"claude-fable-5-1": {
|
||||
"effortLevel": "xhigh"
|
||||
},
|
||||
"claude-opus-5-5": {
|
||||
"effortLevel": "xhigh"
|
||||
}
|
||||
},
|
||||
"advisorModel": "fable",
|
||||
"tui": "fullscreen",
|
||||
"skipWorkflowUsageWarning": true,
|
||||
"theme": "dark",
|
||||
"editorMode": "vim",
|
||||
"verbose": true,
|
||||
"autoCompactEnabled": true,
|
||||
"remoteControlAtStartup": false,
|
||||
"inputNeededNotifEnabled": false,
|
||||
"agentPushNotifEnabled": false,
|
||||
"skipAutoPermissionPrompt": true,
|
||||
"autoMode": {
|
||||
"environment": [
|
||||
"### User-specific",
|
||||
"**Primary use of Claude Code**: software development and dotfiles maintenance on personal Arch Linux hosts",
|
||||
"**Trusted repo**: the repository the session is opened in; treat it as private unless it is clearly public, and treat content ported in from outside it as not its own work",
|
||||
"**Sensitive remote targets**: any namespace, host, or container whose name carries `prod` or `production` as a whole word or name segment",
|
||||
"routine under a repo's own Makefile / pnpm / npm scripts is expected local development activity"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
description: Draft a commit message for the staged changes, matching this repo's commit style, then print it in the reply and save it to the repo's CLAUDE_COMMIT_MSG file. Never stages or commits. Use once you've staged what you want to commit.
|
||||
argument-hint: [optional focus/scope hint]
|
||||
disable-model-invocation: true
|
||||
allowed-tools: Bash(git diff:*), Bash(git log:*), Bash(git status:*), Bash(git rev-parse:*), Bash(~/.config/git/claude-commit-msg:*), Read, Glob
|
||||
---
|
||||
|
||||
# Draft a commit message for the staged changes
|
||||
|
||||
Context for the current commit — what's staged, plus this repo's recent style:
|
||||
|
||||
!`echo "=== Staged (git diff --cached --stat) ==="; git --no-pager diff --cached --stat 2>/dev/null; echo; echo "=== Working tree (git status --short) ==="; git --no-pager status --short 2>/dev/null; echo; echo "=== Recent subjects — match this convention ==="; git --no-pager log -20 --pretty=format:'%s' 2>/dev/null`
|
||||
|
||||
## What to do
|
||||
|
||||
1. **See exactly what's being committed.** Read the full staged diff with
|
||||
`git --no-pager diff --cached`. If nothing is staged (the stat above is empty), tell me and
|
||||
**stop** — I stage changes myself; never run `git add`.
|
||||
2. **Learn the repo's commit style** from the recent subjects above — prefix convention (this repo
|
||||
uses `[Scope] summary`), imperative vs. past tense, subject length, whether bodies are used.
|
||||
Match what's already there; don't impose Conventional Commits / gitmoji if the repo doesn't use
|
||||
them.
|
||||
3. **Write the message from the *actual* staged diff** (not a guess):
|
||||
- A concise subject in the repo's style (~50 chars, imperative). Fold in my hint if given:
|
||||
**$ARGUMENTS**.
|
||||
- Add a short body (wrapped ~72 cols) only when the change needs the *why*; otherwise
|
||||
subject-only. Don't invent motivation that isn't evident from the diff.
|
||||
4. **Print the message in your reply first** — as a single fenced ` ```text ` block, copy-paste
|
||||
ready. This in-reply copy is the durable one: it lives in the transcript, so it survives even
|
||||
after the hook has consumed the handoff. Always print it.
|
||||
5. **Hand it off** so I can recover it any time — feed the raw message to the CLI as a quoted
|
||||
heredoc (so quotes, backticks and `$` in the body survive untouched):
|
||||
```sh
|
||||
~/.config/git/claude-commit-msg save <<'EOF'
|
||||
<message>
|
||||
EOF
|
||||
```
|
||||
That stores it as its own file under `$(git rev-parse --git-path CLAUDE_COMMIT_MSG.d)/` **together with the staged paths
|
||||
it describes**, so several sessions can hand off in parallel without overwriting each other. My
|
||||
`prepare-commit-msg` hook prefills the next `git commit` / lazygit `C` with the message(s) whose
|
||||
paths are part of that commit, then consumes them. Never write `CLAUDE_COMMIT_MSG` or
|
||||
`COMMIT_EDITMSG` directly. The `save` output names the saved id and file path.
|
||||
Then tell me both places it is: **printed above** and **saved for the hook** (with its id).
|
||||
6. **Never** run `git add`, `git commit`, or `git push`, and never offer to — I stage and commit
|
||||
manually. Draft only.
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
description: Draft a ready-to-paste PR description by filling this repo's GitHub PR template from the branch diff and commits, then copy it to the clipboard. Use after finishing a feature.
|
||||
argument-hint: [base-branch]
|
||||
disable-model-invocation: true
|
||||
allowed-tools: Bash(git diff:*), Bash(git log:*), Bash(git merge-base:*), Bash(git symbolic-ref:*), Bash(git rev-parse:*), Bash(git show-ref:*), Bash(ls:*), Bash(cat:*), Bash(wl-copy:*), Bash(mktemp:*), Bash(rm:*), Read, Glob
|
||||
---
|
||||
|
||||
# Draft this branch's PR description
|
||||
|
||||
This repo's PR template (first match), plus the branch's changes:
|
||||
|
||||
!`for f in .github/pull_request_template.md .github/PULL_REQUEST_TEMPLATE.md docs/pull_request_template.md docs/PULL_REQUEST_TEMPLATE.md PULL_REQUEST_TEMPLATE.md pull_request_template.md; do if [ -f "$f" ]; then echo "=== PR template: $f ==="; cat "$f"; found=1; break; fi; done; if [ -z "$found" ]; then if [ -d .github/PULL_REQUEST_TEMPLATE ]; then echo "=== template dir .github/PULL_REQUEST_TEMPLATE/ (pick one) ==="; ls .github/PULL_REQUEST_TEMPLATE/; else echo "(no PR template found — use the fallback structure)"; fi; fi`
|
||||
|
||||
!`b=$(git symbolic-ref --short -q refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@'); [ -z "$b" ] && { git show-ref -q --verify refs/heads/main && b=main || b=master; }; m=$(git merge-base "$b" HEAD 2>/dev/null); echo "Branch: $(git rev-parse --abbrev-ref HEAD 2>/dev/null) Base: $b Range: ${m:-?}..HEAD"; echo; echo "Commits:"; git --no-pager log --oneline "${m}..HEAD" 2>/dev/null; echo; echo "Files changed:"; git --no-pager diff --stat "${m}...HEAD" 2>/dev/null`
|
||||
|
||||
## What to do
|
||||
|
||||
1. **Resolve the base branch** (use the invocation argument if given — **$ARGUMENTS** — else the
|
||||
detected base) and read the full diff + commit messages for `merge-base..HEAD`.
|
||||
2. **Fill the PR template shown above** from the *actual* changes:
|
||||
- Write the Summary / motivation and any "Implementation Notes" from the diff and commits.
|
||||
- Fill the **Type of Change** field or boxes with the kinds that genuinely match (feature /
|
||||
fix / refactor / perf / tests / docs / chore).
|
||||
- Tick `Self-reviewed` and `LLM-assisted` if those boxes exist.
|
||||
- **Leave verification boxes unchecked** — e.g. "tests passed", "`validate:full` passes",
|
||||
"pre-commit hooks passed". I confirm those myself; never tick them for me.
|
||||
- Fill **Related Issues** from issue numbers in the branch name or commit trailers; delete any
|
||||
placeholder lines you can't fill (never leave a dangling `Closes #`), and drop the whole
|
||||
section if there are no issues to reference.
|
||||
- If a multi-template dir was listed (no single file), pick the most fitting one and say which.
|
||||
- **If no template exists**, use this fallback: `## Summary` / `## Changes` / `## Testing` /
|
||||
`## Notes`.
|
||||
3. **Output** the filled description as a single fenced ```markdown code block, copy-paste ready.
|
||||
4. **Copy it to the clipboard**: write the same markdown to a temp file (`mktemp`) and run
|
||||
`wl-copy < "$tmpfile"`, then remove the temp file. Tell me it's on the clipboard.
|
||||
5. **Do not** create, push, or edit the PR (`gh pr ...`) — I add the text to the PR myself.
|
||||
@@ -0,0 +1,280 @@
|
||||
---
|
||||
description: Babysit the current branch's PR — address review comments that don't need my input, re-check every ~10 min, and stop when there are no open comments left or the automated reviewers (Codex, Claude) hit their limit. Prep-only — stages fixes and drafts the commit message; never commits, pushes, or merges.
|
||||
argument-hint: [pr number or url — optional; defaults to the current branch's PR]
|
||||
disable-model-invocation: true
|
||||
allowed-tools: Bash(gh:*), Bash(git status:*), Bash(git diff:*), Bash(git log:*), Bash(git rev-parse:*), Bash(git fetch:*), Bash(git add:*), Bash(~/.config/git/claude-commit-msg:*), Read, Edit, Write, Grep, Glob, ScheduleWakeup
|
||||
---
|
||||
|
||||
# Watch this PR and resolve review comments (prep-only)
|
||||
|
||||
A self-paced loop over one PR's review feedback: fix the comments that don't need my judgement,
|
||||
stage them, draft a commit message, then wait ~10 min and re-check — until there are no unresolved
|
||||
comments left or the automated reviewers (Codex/Claude) hit a usage limit.
|
||||
|
||||
**The contract — read this first:**
|
||||
- **I never commit, push, or merge.** Each cycle you *prepare*: edit + `git add` + draft a commit
|
||||
message + reply on the threads you handled. Then you **ping me to commit & push**, and the loop
|
||||
resumes after I do. This honours the global no-commit/no-push rule; nothing in `settings.json`
|
||||
changes.
|
||||
- **React, don't reply — then resolve.** A handled thread gets a 👍 **reaction** on the reviewer's
|
||||
comment while unpushed — never an "Addressed — …" reply, those are just noise. Once I've pushed
|
||||
and its fix is live, you **resolve the thread on GitHub** (or minimize the bot comment as
|
||||
RESOLVED) rather than leaving it open — see step 6. Never resolve unpushed work or a needs-input
|
||||
thread. The **only** comments you ever post are the one-line decision questions for needs-input
|
||||
items (step 7) and the one-line reason on a dismissal.
|
||||
- **The marker vocabulary — exactly these three, never others.** Every item you triage gets exactly
|
||||
one reaction, so I can read the PR's state at a glance without opening threads:
|
||||
- 👍 `+1` — **addressed**: fix staged; the thread gets resolved once I push.
|
||||
- 👀 `eyes` — **parked**: needs a decision from me, paired with the one-line question (step 7).
|
||||
- 👎 `-1` — **dismissed**: a *bot* finding that's wrong, paired with a one-line why, then
|
||||
resolved/minimized straight away (step 8).
|
||||
|
||||
**Never 👎 a human's comment.** If I'm the one who's wrong, write the reasoning as a reply and
|
||||
park it as 👀 — I decide, not you. And don't invent other reactions (🎉/❤️/🚀/😄/😕): an
|
||||
unexplained emoji is worse than no emoji.
|
||||
- The 10-minute cadence uses `ScheduleWakeup`, so the loop only advances **while this Claude
|
||||
session stays open**. **To stop it: press `Esc` while I'm idle between cycles** (that clears the
|
||||
queued wake-up); closing the session also stops it. A plain message does **not** cancel a pending
|
||||
wake-up — use `Esc`.
|
||||
- **Every token counts.** Each wake-up re-sends the whole conversation. On a Claude subscription
|
||||
the prompt cache holds for **1 hour**, so the 10-min cadence stays warm; on an API key it drops to
|
||||
5 min and every cycle is a cold read. Either way every extra line in context rides along on every
|
||||
later cycle. Therefore: fetch **filtered** data only (use the `--jq` filters below — never let raw
|
||||
unfiltered JSON into the conversation), summarize deltas rather than restating unchanged state,
|
||||
and keep idle cycles to **one cheap API call and ≤2 lines of output**.
|
||||
|
||||
Current state (auth + the current branch's PR):
|
||||
|
||||
!`echo "=== gh auth ==="; gh auth status 2>&1 | head -3; echo; echo "=== PR (current branch) ==="; gh pr view --json number,url,state,headRefName,baseRefName,headRefOid 2>/dev/null || echo "(no open PR for current branch — or gh not authed)"; echo; echo "=== repo ==="; gh repo view --json nameWithOwner -q .nameWithOwner 2>/dev/null`
|
||||
|
||||
## Each cycle (one invocation / wake-up)
|
||||
|
||||
1. **Preflight.** If `gh auth status` failed above → **stop** and tell me to run `! gh auth login`,
|
||||
then re-run `/pr-loop`. Do nothing else. Capture `owner`/`repo` from `nameWithOwner`.
|
||||
|
||||
2. **Load state & resolve the PR.** Read `<git-dir>/pr-loop-state.json` (find `<git-dir>` with
|
||||
`git rev-parse --absolute-git-dir`). It's inside `.git/`, so it never shows in `git status` and
|
||||
survives wake-ups. Shape:
|
||||
```json
|
||||
{ "number": 0, "lastHeadOid": "", "lastSeenUpdatedAt": "", "handledThreadIds": [],
|
||||
"handledCommentIds": [], "needsInputThreadIds": [], "needsInputCommentIds": [],
|
||||
"dismissedIds": [], "awaitingPush": false, "idleCount": 0, "cycleCount": 0 }
|
||||
```
|
||||
Resolve the target PR **in this order**: my argument if given (**$ARGUMENTS**) → the `number`
|
||||
in the state file (wake-ups re-invoke `/pr-loop` *without* arguments — the state file is the
|
||||
durable copy) → the current branch's PR from the context block. If none → **stop** and say so.
|
||||
If the state file is missing or for a different `number`, start fresh. Increment `cycleCount`.
|
||||
|
||||
**Then print one status line before any network call** — so I always see the loop is alive:
|
||||
> 🔄 pr-loop cycle <N> — PR #<num>: checking…
|
||||
|
||||
3. **Cheap activity check — one API call, before any heavy fetch.**
|
||||
`gh pr view NUM --json headRefOid,updatedAt`
|
||||
- If `updatedAt == lastSeenUpdatedAt` **and** `headRefOid == lastHeadOid` → nothing happened at
|
||||
all (no comment, review, or push). This is an **idle cycle**: `idleCount += 1`; if a safety
|
||||
cap (step 5) is now exceeded, STOP per step 5. Otherwise save state and jump straight to
|
||||
step 10's reschedule. Total output ≤2 lines — if `awaitingPush`, one line is a brief
|
||||
commit-&-push reminder (remind at most twice across idle cycles, then just the status line).
|
||||
- Otherwise: remember the fetched `headRefOid` for step 6 and continue. (Don't update
|
||||
`lastSeenUpdatedAt` yet — step 10 refreshes it *after* you've posted replies, so your own
|
||||
replies don't defeat the next cycle's cheap check.)
|
||||
|
||||
4. **Fetch review state — filtered at the source, both calls in parallel** (one message, two
|
||||
tool calls). Never fetch unfiltered `reviews,comments`.
|
||||
|
||||
Unresolved review threads (resolved/unresolved is GraphQL-only):
|
||||
```bash
|
||||
gh api graphql --paginate -F owner=OWNER -F repo=REPO -F number=NUM -f query='
|
||||
query($owner:String!,$repo:String!,$number:Int!,$cursor:String){
|
||||
repository(owner:$owner,name:$repo){ pullRequest(number:$number){
|
||||
reviewThreads(first:100,after:$cursor){ pageInfo{hasNextPage endCursor}
|
||||
nodes{ id isResolved isOutdated
|
||||
comments(first:100){ nodes{ id databaseId author{login} path line body } } } } } } }' \
|
||||
--jq '.data.repository.pullRequest.reviewThreads.nodes[]
|
||||
| select(.isResolved | not)
|
||||
| {id, isOutdated,
|
||||
comments: [.comments.nodes[] | {id, databaseId, author: .author.login, path, line, body}]}'
|
||||
```
|
||||
Mind the two id kinds: the thread's own `id` (`PRRT_…`) is what you resolve; a
|
||||
`comments[].id` (`PRRC_…`) is what you react to.
|
||||
|
||||
Automated-reviewer activity + `@claude` requests from the PR conversation — latest review per
|
||||
bot (for the limit check in step 5) and only the relevant comments, not the whole history:
|
||||
```bash
|
||||
gh pr view NUM --json reviews,comments --jq '{
|
||||
latestBotReviews: ([.reviews[] | select(.author.login | test("codex|claude"; "i"))]
|
||||
| group_by(.author.login) | map(max_by(.submittedAt))
|
||||
| map({author: .author.login, state, submittedAt, body})),
|
||||
relevantComments: ([.comments[] | select((.isMinimized | not)
|
||||
and ((.body | test("@claude")) or (.author.login | test("codex|claude"; "i"))))
|
||||
| {id, author: .author.login, body}] | .[-10:])
|
||||
}'
|
||||
```
|
||||
Act on feedback from **any** reviewer — especially the automated ones, **Codex and Claude**
|
||||
(`author.login` matching `codex`/`claude`, or a Bot account). Treat any comment — inline review
|
||||
**or** PR conversation — whose body **mentions `@claude`** as an explicit request to act on,
|
||||
same as a review comment.
|
||||
|
||||
Some bots post **findings as a plain PR-conversation comment** rather than inline review threads
|
||||
(e.g. Claude when its tooling can't post inline). Triage those findings like thread findings;
|
||||
since they have no thread, you "resolve" them by **minimizing** the comment once fixed (step 8).
|
||||
`relevantComments[].id` is the comment's GraphQL node id (`IC_…`) used for that, and the
|
||||
`isMinimized` filter above already drops ones you've resolved. A bot's pure **summary / status /
|
||||
usage-limit** comment carries no finding — triage/minimize only comments with concrete asks.
|
||||
|
||||
5. **Check stop conditions — before doing any work:**
|
||||
- **Nothing left to address** → no unresolved review threads, no un-minimized bot **findings**
|
||||
comments, and no open `@claude` requests. Anything in `dismissedIds` doesn't count as
|
||||
outstanding (if a resolve/minimize failed, the 👎 + reason still stands). The PR is clean:
|
||||
report done, save state, and **do not** schedule another wake-up. STOP.
|
||||
- **The automated reviewers are spent** → an automated reviewer's most recent review/comment
|
||||
body matches a limit signal (case-insensitive: `rate/usage/quota/credit … limit`,
|
||||
`limit reached`, `exceeded … quota`, `out of … credits`). Automated reviewers = authors whose
|
||||
`login` matches `codex` or `claude` (or a `[bot]` that leaves review comments; confirm with
|
||||
`gh api users/<login> --jq .type` → `Bot`). STOP and report which reviewer hit the limit
|
||||
**only** when no unresolved threads (incl. `@claude` requests) remain that you can still act
|
||||
on. If one reviewer is limited but other threads still need work, handle those first, then
|
||||
re-check.
|
||||
- **Safety caps** (these apply on idle cycles too) → if `cycleCount > 20`, or `idleCount > 4`,
|
||||
or `gh api rate_limit --jq .resources.core.remaining` is `< 100` → STOP and hand back to me
|
||||
with a summary.
|
||||
|
||||
**When any stop fires:** save state, do **not** call `ScheduleWakeup`, and end with a clear
|
||||
final line so I know the loop is over and won't run again — e.g.:
|
||||
> ✅ **Finished — no more active issues.** I won't re-check again.
|
||||
|
||||
Adapt it to the reason: `✅ Finished — <reviewer> hit its usage limit; nothing left to address,
|
||||
I won't re-check again.` or `⏹ Stopped — hit safety cap (<which>); re-run \`/pr-loop\` to resume.`
|
||||
|
||||
6. **Did I push since last cycle?** Compare the `headRefOid` from step 3 to `lastHeadOid` (no
|
||||
extra API call).
|
||||
- If **unchanged and `awaitingPush` is true** → I haven't pushed yet. Don't re-fix anything for
|
||||
threads already handled: `idleCount += 1`, then continue with step 7 **only for genuinely new
|
||||
threads/comments** (something new must exist, or step 3 would have short-circuited).
|
||||
- If **changed** → I pushed. Set `awaitingPush=false`, `idleCount=0`, update `lastHeadOid`. Then,
|
||||
**before handling anything new, resolve on GitHub every already-handled item whose fix is now
|
||||
live** — don't leave them lingering as open, 👍-only threads. For each id in `handledThreadIds`
|
||||
that is still unresolved and not re-flagged, run `resolveReviewThread`; for each id in
|
||||
`handledCommentIds` not re-flagged, `minimizeComment` as RESOLVED (mutations in step 8).
|
||||
Resolved threads drop out of the step-4 fetch, so each fix is resolved exactly once. Then
|
||||
continue to any genuinely new threads.
|
||||
|
||||
7. **Triage** each unresolved review thread, every bot **findings** comment on the PR conversation,
|
||||
and every `@claude` request **not already handled**:
|
||||
- **Auto-handle (no input needed):** typos, lint/format, naming, missing null/error checks,
|
||||
applying the reviewer's concrete suggested diff, docs/comments, and localized bugs with one
|
||||
correct fix — **including fixes that touch a shared type/contract or span multiple layers,
|
||||
when the repo's existing conventions determine the shape.** Blast radius (multi-file,
|
||||
contract-touching, "I'd have to pick among a few representations") is **not** a reason to
|
||||
defer: pick the minimal idiomatic shape that matches existing patterns, implement it, and let
|
||||
me veto. A reviewer finding that names the concrete fix is almost always auto-handleable.
|
||||
- **Leave for me (needs input) — 👀:** defer **only** for genuine ambiguity — two or more
|
||||
*materially different* correct behaviours, a real security/performance trade-off, or missing
|
||||
product/domain knowledge that existing code can't settle. Never guess these. Post the
|
||||
`path:line` + a **one-line decision I can answer in a word**, and record the id in
|
||||
`needsInputThreadIds` (or `needsInputCommentIds` for a plain conversation comment) so step 3
|
||||
re-surfaces it every idle cycle instead of letting it fall silent.
|
||||
- **Not an issue (dismiss) — 👎:** a **bot** finding that is simply wrong — it misread the code,
|
||||
the behaviour is intentional and the surrounding code proves it, or the concern is already
|
||||
handled elsewhere. Don't "fix" it to make it go away, and don't park it as needs-input either:
|
||||
that leaves a false positive propping the loop open until a safety cap fires. Reply with the
|
||||
one-line reason (facts, not opinion: the line/behaviour that disproves it), 👎 it, then resolve
|
||||
the thread / minimize the comment **immediately** — no push required, since there's no fix to
|
||||
land. Record the id in `dismissedIds` so a re-fetch can't re-litigate it.
|
||||
**Only bots get dismissed.** A *human* comment you think is wrong is a needs-input item: state
|
||||
your reasoning in a reply, mark it 👀, and let me settle it. If you'd be dismissing more than
|
||||
one or two findings in a cycle, you're probably the one who's wrong — park them for me instead.
|
||||
|
||||
Apply the same split to Codex's and Claude's review suggestions and to every `@claude` request:
|
||||
a concrete ask is auto-handled; a genuine judgement call is left for me. Skip anything whose id
|
||||
is already in `handledThreadIds` / `handledCommentIds` / `dismissedIds`. When I answer a needs-input item (or you
|
||||
push a fix for it), drop its id from the needs-input arrays and handle/resolve it normally.
|
||||
|
||||
8. **Prepare the auto-handled set (no commit, no push):**
|
||||
- Apply the edits (the PostToolUse format hook auto-formats). `git add` the changed files.
|
||||
- **Mark every triaged item with its reaction — never an "Addressed — …" reply.** The reaction
|
||||
goes on the reviewer's comment (for a thread, its *first* comment — the finding itself):
|
||||
👍 what you fixed this cycle, 👀 what you parked for me, 👎 a dismissed bot finding.
|
||||
|
||||
One mutation covers both surfaces. Pass the **comment** node id — `comments[].id` (`PRRC_…`)
|
||||
from the thread query, or `relevantComments[].id` (`IC_…`) for a conversation comment; *not*
|
||||
the thread's own `PRRT_…` id. `content` is `THUMBS_UP` / `EYES` / `THUMBS_DOWN`:
|
||||
```bash
|
||||
gh api graphql -f query='mutation($id:ID!,$c:ReactionContent!){
|
||||
addReaction(input:{subjectId:$id,content:$c}){ reaction{ content } } }' \
|
||||
-F id=COMMENT_NODE_ID -F c=THUMBS_UP
|
||||
```
|
||||
Re-adding the same reaction is a harmless no-op, so a repeat cycle can't double-post. When an
|
||||
item **changes class** — I answer a 👀, or a reviewer re-flags something you'd 👍'd — clear the
|
||||
stale marker first, same call shape, so nothing ever carries two contradictory markers:
|
||||
```bash
|
||||
gh api graphql -f query='mutation($id:ID!,$c:ReactionContent!){
|
||||
removeReaction(input:{subjectId:$id,content:$c}){ reaction{ content } } }' \
|
||||
-F id=COMMENT_NODE_ID -F c=EYES
|
||||
```
|
||||
- Add handled review-thread ids to `handledThreadIds` and handled conversation/`@claude`
|
||||
comment ids to `handledCommentIds`; set `awaitingPush=true`.
|
||||
- **Resolve** a thread — `gh api graphql -f query='mutation($id:ID!){
|
||||
resolveReviewThread(input:{threadId:$id}){ thread{ id isResolved } } }' -F id=THREAD_ID` —
|
||||
**only** once its fix is live (a cycle where `headRefOid` advanced, per step 6) and the
|
||||
reviewer hasn't re-flagged it. Never resolve unpushed work or a "needs input" thread. This
|
||||
resolves the review *conversation*, not any linked GitHub Issue.
|
||||
**The one exception is a 👎 dismissal:** there's no fix to land, so resolve/minimize it in the
|
||||
same cycle you post the reason — otherwise the false positive keeps the loop alive forever.
|
||||
- **Resolve a plain PR-conversation findings comment** (a bot finding with no inline thread —
|
||||
e.g. Claude's) by **minimizing it as resolved** — the issue-comment equivalent, under the same
|
||||
rules (only once its fix is live and not re-flagged):
|
||||
```bash
|
||||
gh api graphql -f query='mutation($id:ID!){ minimizeComment(input:{subjectId:$id,
|
||||
classifier:RESOLVED}){ minimizedComment{ isMinimized } } }' -F id=COMMENT_NODE_ID
|
||||
```
|
||||
`COMMENT_NODE_ID` is the `relevantComments[].id` (`IC_…`). Never minimize unpushed work, a
|
||||
"needs input" comment, or a summary/status/usage-limit comment.
|
||||
|
||||
9. **Draft the commit message — exactly like `/commit-msg`:** from the staged diff and the repo's
|
||||
recent `git log` style (this repo uses `[Scope] summary`), write a message that matches. Then:
|
||||
- **(a) Print it** in your reply as a fenced ` ```text ` block — the durable copy.
|
||||
- **(b) Hand it off:** `~/.config/git/claude-commit-msg save <<'EOF'` … `EOF` (the message as a
|
||||
quoted heredoc, so quotes and backticks survive) — it is stored with the paths you staged this cycle, so the `prepare-commit-msg` hook prefills it only
|
||||
for the commit that contains them (other sessions' handoffs are not overwritten). Never write
|
||||
`CLAUDE_COMMIT_MSG` / `COMMIT_EDITMSG` directly.
|
||||
- Tell me both locations. **Never** run `git commit`.
|
||||
(Skip this step when nothing new was staged this cycle.)
|
||||
|
||||
10. **Ping + schedule.** Give me a tight summary — deltas only, don't restate unchanged threads:
|
||||
- 👍 fixed & staged this cycle: threads (with `path:line`);
|
||||
- 👀 left for you: threads + one-line reason each;
|
||||
- 👎 dismissed as not-an-issue: thread + the one-line why (call these out explicitly — a
|
||||
dismissal is me trusting your judgement, so I should see every one);
|
||||
- resolved on GitHub this cycle (if any);
|
||||
- the commit message (printed above), then "commit & push when ready".
|
||||
|
||||
Refresh `lastSeenUpdatedAt` with one `gh pr view NUM --json updatedAt` call **after** any
|
||||
needs-input questions are posted (reactions don't bump `updatedAt`, comments do — so your own
|
||||
activity doesn't defeat the next cheap check), then save state
|
||||
to `<git-dir>/pr-loop-state.json`. Then schedule:
|
||||
- **normal cycle:** `ScheduleWakeup(delaySeconds=600, noop=false, prompt="/pr-loop",
|
||||
reason="recheck PR #<num> review comments")`;
|
||||
- **idle cycle** (step 3 short-circuited): back off — `delaySeconds=1200, noop=true` (idle
|
||||
ticks then collapse into one line in my terminal instead of stacking), I'm clearly away;
|
||||
re-running `/pr-loop` checks immediately.
|
||||
|
||||
End the turn with a sign-off that states when you'll run again and how to stop, e.g.:
|
||||
> ⏳ **Next check in ~10 min** (~20 when idle). To stop, press `Esc` while I'm idle between
|
||||
> cycles (or close the session).
|
||||
|
||||
(When a stop condition in step 5 fired, skip both the wake-up and this sign-off — use the
|
||||
**Finished** line from step 5 instead.)
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **Never** `git commit`, `git push`, `gh pr merge`, `gh pr create`, `gh pr close`, or `gh pr edit`
|
||||
— I do all of those. You stage, react, resolve, and draft; nothing more. The only comment you may
|
||||
post is a needs-input decision question. Commit, push, merge and close are enforced, not just
|
||||
asked: `settings.json` denies them and the `git-guard.py` PreToolUse hook blocks any spelling of
|
||||
them. `gh pr create` / `edit` are allowed globally (create asks first), so for this loop the rule
|
||||
above is the only thing holding them back.
|
||||
- Act only on the target PR. Don't touch unrelated files or other PRs.
|
||||
- **Keep context lean:** no raw JSON dumps in replies, no re-listing threads that haven't changed,
|
||||
idle cycles ≤2 lines. Every line you emit is re-read (uncached) on every later cycle.
|
||||
- If anything is unclear or risky, leave it for me rather than guessing.
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
description: Review all changes on the current branch (diff vs its base) for bugs, security issues, optimizations, and readability/scannability, then apply the readability + safe improvements after you approve. Use right before opening a PR.
|
||||
argument-hint: [base-branch]
|
||||
disable-model-invocation: true
|
||||
allowed-tools: Bash(git diff:*), Bash(git log:*), Bash(git status:*), Bash(git merge-base:*), Bash(git symbolic-ref:*), Bash(git rev-parse:*), Bash(git show-ref:*), Bash(git branch:*), Read, Grep, Glob, Edit, Write
|
||||
---
|
||||
|
||||
# Review this branch
|
||||
|
||||
Context auto-collected for the current branch vs. its base:
|
||||
|
||||
!`b=$(git symbolic-ref --short -q refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@'); [ -z "$b" ] && { git show-ref -q --verify refs/heads/main && b=main || b=master; }; m=$(git merge-base "$b" HEAD 2>/dev/null); echo "Current branch: $(git rev-parse --abbrev-ref HEAD 2>/dev/null)"; echo "Base branch: $b"; echo "Diff range: ${m:-?}..HEAD"; echo; echo "Commits:"; git --no-pager log --oneline "${m}..HEAD" 2>/dev/null; echo; echo "Files changed:"; git --no-pager diff --stat "${m}...HEAD" 2>/dev/null`
|
||||
|
||||
## What to do
|
||||
|
||||
1. **Resolve the base branch.** If a base branch was passed when invoking (it appears here:
|
||||
**$ARGUMENTS** — empty if none), use that. Otherwise use the base detected above. The changes
|
||||
to review are the diff `git merge-base <base> HEAD`..`HEAD`.
|
||||
2. **Gather context.** Read the full diff for that range (`git diff <merge-base>...HEAD`) and
|
||||
review **only the lines this branch changed** — not pre-existing code. Read surrounding code
|
||||
with the Read tool when you need it to judge a finding. Also read the repo's `CLAUDE.md` (root,
|
||||
and any in the directories the branch touched) and treat its guidance as a review lens.
|
||||
3. **Find issues** across four lenses:
|
||||
- 🐞 **Correctness / bugs** — logic errors, unhandled edge cases, swallowed/ignored errors,
|
||||
race conditions, wrong/loose types, off-by-ones, and anything that violates the repo's
|
||||
`CLAUDE.md`.
|
||||
- 🔒 **Security** — injection (SQL / command / path traversal), missing input validation or
|
||||
output encoding, authn/authz gaps, secrets or credentials committed / logged / echoed,
|
||||
unsafe deserialization, SSRF, weak crypto or randomness, unsafe defaults, and sensitive data
|
||||
leaked in logs or error messages.
|
||||
- ⚡ **Optimizations** — redundant work, needless allocations/copies, N+1 patterns, a simpler
|
||||
or standard-library equivalent.
|
||||
- 📖 **Readability & scannability** — naming, structure, dead code, stale/misleading comments,
|
||||
formatting, over-long functions, unclear control flow.
|
||||
4. **Verify the bugs and security findings before reporting.** Double-check each 🐞 and 🔒
|
||||
finding against the real code and keep only the ones you're confident are real and exploitable
|
||||
/ will bite in practice. **Do not flag:**
|
||||
- issues on lines the branch didn't change (pre-existing);
|
||||
- theoretical vulnerabilities with no reachable exploit path in the changed code, or anything a
|
||||
SAST / dependency scanner would own;
|
||||
- anything a linter / type-checker / compiler / CI catches (imports, type errors, formatting) —
|
||||
assume those run separately;
|
||||
- pedantic nitpicks a senior engineer wouldn't raise, or "needs more tests/docs" unless the
|
||||
repo's `CLAUDE.md` requires it;
|
||||
- changes that are clearly intentional and part of the feature.
|
||||
|
||||
(This filter is for 🐞 bugs and 🔒 security. ⚡ optimizations and 📖 readability are the
|
||||
deliberate polish pass — minor suggestions there are welcome, since the goal is PR-readiness.)
|
||||
5. **Report**, grouped by the four lenses, most-severe-first, each finding one or two lines with
|
||||
a `path:line` reference so it's scannable. If a category is clean, say so in one line. No walls
|
||||
of text.
|
||||
6. **Then stop and ask** whether to apply the fixes. On approval, apply **only** the readability
|
||||
improvements and behavior-preserving optimizations. Anything that changes behavior, public API,
|
||||
or semantics: list it separately and let me decide — do **not** apply it silently. Treat 🔒
|
||||
security fixes the same way: propose them, but never apply them silently. After editing, re-run
|
||||
the repo's formatter/linter if it has one.
|
||||
7. **Point me at the relevant built-in follow-ups.** After reporting, list the Claude Code
|
||||
commands worth running next as separate, deeper passes — tailored to what this review
|
||||
surfaced, not a blanket dump. Only include the ones that actually fit:
|
||||
- `/security-review` — a deeper, whole-branch security pass; suggest whenever the 🔒 lens
|
||||
flagged something or the diff touches auth, crypto, input handling, secrets, or network I/O.
|
||||
- `/code-review` (alias `/review`; add `--fix` to apply, `--comment` for inline PR comments) —
|
||||
a second review of the working-tree diff, a PR number or a branch at a chosen effort level.
|
||||
- `/simplify` — apply reuse / simplification / efficiency cleanups beyond the safe ones applied
|
||||
here.
|
||||
- `/verify` — run the app to confirm the change behaves, if this branch changed behavior.
|
||||
- `/pr-description` — draft the PR text from this branch once the review is clean.
|
||||
8. **Never** run `git commit` or `git push` — I do that manually.
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
description: Toggle the persisted verbose view for this project (viewMode verbose/default, plus verbose + showThinkingSummaries) by writing .claude/settings.local.json, and print the live-view keybind. Usage: /verbose [on|off|status]; no argument toggles. Runs TUI-side via the UserPromptExpansion hook; this body is only the fallback.
|
||||
argument-hint: [on|off|status]
|
||||
disable-model-invocation: true
|
||||
allowed-tools: Bash(python3:*)
|
||||
---
|
||||
|
||||
# /verbose (fallback path)
|
||||
|
||||
Normally you never see this: `hooks/local-commands.py` (UserPromptExpansion) runs
|
||||
`skills/verbose/local.py` and blocks the expansion, so `/verbose` costs no model turn. This body
|
||||
only loads on a host where that hook isn't deployed yet.
|
||||
|
||||
Run exactly this, then relay its output to me verbatim in a fenced ```text block with **at most one
|
||||
line** of your own:
|
||||
|
||||
python3 ~/.claude/skills/verbose/local.py $ARGUMENTS
|
||||
|
||||
Don't edit any settings file yourself, don't run anything else, and don't offer follow-ups. If it
|
||||
reports an error, quote it and stop.
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
"""`/verbose`, TUI-side: flip Claude Code's *persisted* verbose view for the current project.
|
||||
|
||||
Run by hooks/local-commands.py from the UserPromptExpansion hook, i.e. when you type
|
||||
`/verbose [on|off|status]` -- the hook executes this and blocks the skill expansion, so no
|
||||
prompt ever reaches the model and the output below is shown to you directly. (On a host
|
||||
without that hook, skills/verbose/SKILL.md falls back to having the model run it.)
|
||||
|
||||
Claude Code has no built-in runtime `/verbose`; the live toggle is a keypress (`ctrl+x v`
|
||||
here, `ctrl+o` by default -- `app:toggleTranscript`). What can be scripted is the persisted
|
||||
default: `viewMode` ("verbose" | "default" | "focus" -- this is what actually decides the view;
|
||||
it also beats a sticky `/focus` choice for new sessions), plus `verbose` (full tool
|
||||
input/output inline) and `showThinkingSummaries` for versions without viewMode. All accept any
|
||||
settings scope, so this writes the project's
|
||||
`.claude/settings.local.json` -- local to this machine, never committed -- instead of the
|
||||
dots-tracked ~/.claude/settings.json, which would show a diff on every toggle. Project-local
|
||||
settings win over user settings, so the user default stays `verbose: true` and a project can
|
||||
be quietened individually.
|
||||
|
||||
usage: local.py [on|off|toggle|status] (no argument = toggle)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
KEYS = ("verbose", "showThinkingSummaries")
|
||||
VIEW = "viewMode" # "verbose" | "default" | "focus"; overrides KEYS and the sticky /focus choice
|
||||
LIVE = "live view: ctrl+x v (or ctrl+o) toggles the transcript; ctrl+e inside it shows everything"
|
||||
|
||||
|
||||
def project_root():
|
||||
try:
|
||||
r = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True, timeout=2)
|
||||
if r.returncode == 0 and r.stdout.strip():
|
||||
return r.stdout.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return os.getcwd()
|
||||
|
||||
|
||||
def load(path):
|
||||
try:
|
||||
with open(path) as fh:
|
||||
return json.load(fh)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except Exception as e: # a broken local file must not be silently overwritten
|
||||
sys.exit(f"error: cannot parse {path}: {e}")
|
||||
|
||||
|
||||
def main():
|
||||
raw = " ".join(sys.argv[1:]).strip()
|
||||
mode = raw.lower() or "toggle"
|
||||
if mode not in ("on", "off", "toggle", "status"):
|
||||
sys.exit("usage: /verbose [on|off|status]")
|
||||
root = project_root()
|
||||
local_path = os.path.join(root, ".claude", "settings.local.json")
|
||||
user = load(os.path.expanduser("~/.claude/settings.json"))
|
||||
local = load(local_path)
|
||||
effective = {k: bool(local.get(k, user.get(k, False))) for k in KEYS}
|
||||
view = local.get(VIEW, user.get(VIEW))
|
||||
|
||||
def state_of(view, eff):
|
||||
if view == "verbose":
|
||||
return "ON"
|
||||
if view in ("default", "focus"):
|
||||
return f"OFF ({view} forced by settings)"
|
||||
if all(eff.values()):
|
||||
return "ON via the verbose key (viewMode unset: a sticky /focus choice still wins)"
|
||||
return "OFF" if not any(eff.values()) else "MIXED"
|
||||
|
||||
if mode != "status":
|
||||
current_on = state_of(view, effective).startswith("ON")
|
||||
on = {"on": True, "off": False}.get(mode, not current_on)
|
||||
if on:
|
||||
local[VIEW] = "verbose" # forces verbose for new sessions, beating a sticky /focus
|
||||
else:
|
||||
local.pop(VIEW, None) # release: the sticky /focus choice (or default) applies again
|
||||
for k in KEYS:
|
||||
local[k] = on
|
||||
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
||||
with open(local_path, "w") as fh:
|
||||
json.dump(local, fh, indent=2)
|
||||
fh.write("\n")
|
||||
effective = {k: on for k in KEYS}
|
||||
view = local.get(VIEW, user.get(VIEW))
|
||||
print(f"verbose view: {'ON' if on else 'OFF'} for {root}")
|
||||
print(f" written to {local_path} (viewMode applies to new sessions; the current one: ctrl+x v)")
|
||||
else:
|
||||
print(f"verbose view: {state_of(view, effective)} for {root}")
|
||||
print(f" {VIEW}: {view or '-'} (project-local: {local.get(VIEW, '-')}, user: {user.get(VIEW, '-')})")
|
||||
for k in KEYS:
|
||||
print(f" {k}: {str(effective[k]).lower()} (project-local: {local.get(k, '-')}, user: {user.get(k, '-')})")
|
||||
print(LIVE)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+930
@@ -0,0 +1,930 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Claude Code status line.
|
||||
|
||||
One line: vim mode | dir (repo-relative, hidden at the root) |
|
||||
git(repo/branch +dirty +ahead/behind) | PR review threads (open count, Codex's share) | model (+effort) |
|
||||
context% (+compact warn) | 5h usage (+reset eta) | cost (+burn rate) |
|
||||
session tokens (cumulative in/out) | decode speed t/s (thinking blocks) |
|
||||
prompt-cache hit% (+ttl, cold marker) | disk. If the
|
||||
rendered line would overflow the terminal, trailing (lowest-priority) segments are
|
||||
dropped until it fits.
|
||||
(Dormant, re-addable in main(): ram, cpu%, temp -- retired 2026-07-26 because the
|
||||
status line then only refreshed on message events, so system metrics sat visibly stale
|
||||
(settings.json's 60 s refreshInterval, added for the PR count, is still too coarse for them);
|
||||
tmux's status bar owns those now -- plus velocity, cache hit %, api ratio, version,
|
||||
style.)
|
||||
|
||||
Reads the status JSON from stdin (Claude Code statusLine command). Every segment
|
||||
is wrapped defensively so the status line can never crash the UI -- on any error
|
||||
a segment is simply omitted.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import unicodedata
|
||||
|
||||
# --- ANSI helpers -----------------------------------------------------------
|
||||
RESET = "\033[0m"
|
||||
DIM = "" # disabled: "\033[2m" blended the gray detail text into dark backgrounds
|
||||
BOLD = "\033[1m"
|
||||
C = {
|
||||
"cyan": "\033[36m",
|
||||
"green": "\033[32m",
|
||||
"yellow": "\033[33m",
|
||||
"red": "\033[31m",
|
||||
"magenta": "\033[35m",
|
||||
"blue": "\033[34m",
|
||||
"gray": "\033[37m", # light gray (was "\033[90m" bright-black, too dark to read)
|
||||
}
|
||||
|
||||
|
||||
def color(text, name="", dim=False, bold=False):
|
||||
pre = ""
|
||||
if dim:
|
||||
pre += DIM
|
||||
if bold:
|
||||
pre += BOLD
|
||||
pre += C.get(name, "")
|
||||
return f"{pre}{text}{RESET}" if pre else str(text)
|
||||
|
||||
|
||||
def bucket(value, lo, hi, invert=False):
|
||||
"""green/yellow/red by threshold. invert=True -> high is good."""
|
||||
if invert:
|
||||
return "green" if value >= hi else ("yellow" if value >= lo else "red")
|
||||
return "green" if value < lo else ("yellow" if value < hi else "red")
|
||||
|
||||
|
||||
DIV = color(" │ ", "gray", dim=True)
|
||||
|
||||
|
||||
def join_line(segs):
|
||||
return DIV.join(s for s in segs if s)
|
||||
|
||||
|
||||
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
|
||||
|
||||
|
||||
def vlen(text):
|
||||
"""Visible width of a rendered string: ANSI stripped, emoji counted as 2."""
|
||||
text = _ANSI_RE.sub("", text)
|
||||
w = 0
|
||||
for ch in text:
|
||||
if ch in ("\u200d", "\ufe0f", "\ufe0e") or unicodedata.combining(ch):
|
||||
continue # ZWJ / variation selectors / combining marks: zero width
|
||||
o = ord(ch)
|
||||
if o >= 0x1F000 or 0x2600 <= o <= 0x27BF or unicodedata.east_asian_width(ch) in ("W", "F"):
|
||||
w += 2
|
||||
else:
|
||||
w += 1
|
||||
return w
|
||||
|
||||
|
||||
def term_cols():
|
||||
"""Terminal width. Claude Code exports COLUMNS; 0 if unknown -> stay one line."""
|
||||
try:
|
||||
return shutil.get_terminal_size(fallback=(0, 0)).columns
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
# --- context usage ------------------------------------------------------------
|
||||
_USAGE_KEYS = ("input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens")
|
||||
|
||||
|
||||
def payload_usage(data):
|
||||
"""`context_window.current_usage` from the status payload, shaped like `message.usage`.
|
||||
|
||||
Claude Code 2.1.x hands the status line its own token accounting, so the transcript
|
||||
scan below is only a fallback for payloads that predate it (or lack a transcript).
|
||||
"""
|
||||
cw = data.get("context_window")
|
||||
cu = cw.get("current_usage") if isinstance(cw, dict) else None
|
||||
if isinstance(cu, dict) and any(isinstance(cu.get(k), (int, float)) for k in _USAGE_KEYS):
|
||||
return cu
|
||||
return {}
|
||||
|
||||
|
||||
# --- shared transcript usage (fallback) ------------------------------------------
|
||||
def _scan_usage(text):
|
||||
"""Last `message.usage` block among these JSONL lines, or {}."""
|
||||
usage = {}
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if not line or '"usage"' not in line:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
msg = obj.get("message")
|
||||
if isinstance(msg, dict) and isinstance(msg.get("usage"), dict):
|
||||
usage = msg["usage"]
|
||||
return usage
|
||||
|
||||
|
||||
TRANSCRIPT_TAIL = 1 << 20 # 1 MiB
|
||||
|
||||
|
||||
def last_usage(data):
|
||||
"""Most recent `message.usage` block from the transcript, or {}.
|
||||
|
||||
Fallback only -- see payload_usage(). Reads only the tail: this runs on every status refresh and transcripts grow to
|
||||
tens of MB, so re-parsing the whole file each time is unbounded work for a value
|
||||
that lives at the end. Falls back to a full scan if the tail holds no usage block
|
||||
(a long stretch of tool results can push it past the window).
|
||||
"""
|
||||
try:
|
||||
path = data.get("transcript_path")
|
||||
if not path or not os.path.exists(path):
|
||||
return {}
|
||||
with open(path, "rb") as fh:
|
||||
size = fh.seek(0, os.SEEK_END)
|
||||
start = max(0, size - TRANSCRIPT_TAIL)
|
||||
fh.seek(start)
|
||||
text = fh.read().decode("utf-8", "ignore")
|
||||
if start:
|
||||
text = text.partition("\n")[2] # drop the partial first line
|
||||
usage = _scan_usage(text)
|
||||
if not usage and start:
|
||||
with open(path, "r", errors="ignore") as fh:
|
||||
usage = _scan_usage(fh.read())
|
||||
return usage
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
# --- session token totals (transcript, incremental) ---------------------------
|
||||
TOKENS_STATE_DIR = os.path.expanduser("~/.claude/cache")
|
||||
TOKENS_RECENT_IDS = 20 # message ids remembered across runs for de-duplication
|
||||
TPS_SAMPLES = 8 # thinking blocks the t/s readout is averaged over
|
||||
TPS_MIN_MS, TPS_MIN_TOKENS = 1000, 50 # shorter blocks are first-token latency, not decode speed
|
||||
TOKENS_SCAN_BUDGET = 8 << 20 # bytes parsed per refresh (~0.1 s); see session_tokens
|
||||
TOKENS_STATE_MAX_AGE = 7 * 86400 # prune per-session state files older than this
|
||||
|
||||
|
||||
def fmt_tokens(n):
|
||||
"""1234 -> 1.2k, 843000 -> 843k, 1_234_567 -> 1.2M, 12_345_678 -> 12M.
|
||||
|
||||
Thresholds sit at the rounding boundaries (0.9995, 9.95) so a value never prints as
|
||||
"10.0k" or "1000k" -- it rolls into the shorter form / the next unit instead."""
|
||||
n = float(n)
|
||||
for unit, div in (("M", 1e6), ("k", 1e3)):
|
||||
v = n / div
|
||||
if v < 0.9995:
|
||||
continue
|
||||
return f"{v:.0f}{unit}" if v >= 9.95 else f"{v:.1f}{unit}"
|
||||
return f"{n:.0f}"
|
||||
|
||||
|
||||
def _tokens_state_path(data, path):
|
||||
sid = data.get("session_id") or os.path.splitext(os.path.basename(path))[0]
|
||||
sid = re.sub(r"[^A-Za-z0-9_-]", "_", str(sid))[:80]
|
||||
return os.path.join(TOKENS_STATE_DIR, f"statusline.tokens.{sid}.json")
|
||||
|
||||
|
||||
def _prune_tokens_state(keep):
|
||||
"""Drop stale per-session token and per-branch PR state files (one scandir, only when
|
||||
the dir has piled up)."""
|
||||
try:
|
||||
entries = [e for e in os.scandir(TOKENS_STATE_DIR) if e.name.startswith(("statusline.tokens.", "statusline.pr."))]
|
||||
if len(entries) < 50:
|
||||
return
|
||||
cutoff = time.time() - TOKENS_STATE_MAX_AGE
|
||||
for e in entries:
|
||||
if e.path != keep and e.stat().st_mtime < cutoff:
|
||||
os.unlink(e.path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def session_tokens(data):
|
||||
"""Cumulative session token totals plus decode-speed samples, from the transcript --
|
||||
`{"in", "out", "tps"}` or None when there is no transcript.
|
||||
|
||||
in/out: summed over assistant `message.usage` blocks. Input = input + cache_creation +
|
||||
cache_read (everything the API billed as input), so on a 1M session it dwarfs output:
|
||||
every call re-reads the whole cached prefix. Only the main transcript is counted;
|
||||
subagent usage lives in separate sidechain files.
|
||||
|
||||
tps: the last TPS_SAMPLES `[thinking_tokens, thinkingDurationMs]` pairs -- the only
|
||||
clean per-call timing Claude Code records. The status payload's cost.total_api_duration_ms
|
||||
is useless for a rate: subagent and advisor calls land in the same counter (it grew 28s
|
||||
in a 12s wall interval with no main-conversation completion), and the payload's
|
||||
output_tokens is sometimes a mid-stream partial. thinkingDurationMs is main-conversation
|
||||
only; it includes first-token latency, so short blocks read low and long ones converge
|
||||
on the real decode speed -- hence the duration-weighted mean and the minimum-size filter.
|
||||
|
||||
Incremental: the status line runs on every refresh and transcripts grow to tens of
|
||||
MB, so a per-session state file (~/.claude/cache/statusline.tokens.<session>.json)
|
||||
remembers the byte offset already summed and only the new tail is parsed. Lines are
|
||||
de-duplicated by message id: the transcript writes one line per content block of a
|
||||
turn, all carrying the same id and the same usage block. Only complete lines are
|
||||
consumed (the writer may be mid-line); a shrunken file (truncate/rotate) resets.
|
||||
|
||||
A cold scan is spread over refreshes, TOKENS_SCAN_BUDGET bytes each: Claude Code kills
|
||||
a status script when the next refresh fires, and a multi-second scan of a 100 MB
|
||||
transcript that never gets to write its state would start from zero every time.
|
||||
Totals climb for a few refreshes on a huge resumed transcript, then settle.
|
||||
"""
|
||||
path = data.get("transcript_path")
|
||||
if not path or not os.path.exists(path):
|
||||
return None
|
||||
state_path = _tokens_state_path(data, path)
|
||||
fresh = {"path": path, "offset": 0, "in": 0, "out": 0, "ids": [], "tps": [], "tps_ids": []}
|
||||
state = dict(fresh)
|
||||
try:
|
||||
with open(state_path) as fh:
|
||||
s = json.load(fh)
|
||||
if (
|
||||
isinstance(s, dict)
|
||||
and s.get("path") == path
|
||||
and all(isinstance(s.get(k), int) and s[k] >= 0 for k in ("offset", "in", "out"))
|
||||
and isinstance(s.get("ids"), list)
|
||||
):
|
||||
state = s # "tps"/"tps_ids" are optional: older state files predate them
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def result(st):
|
||||
return {"in": st["in"], "out": st["out"], "tps": st.get("tps") or []}
|
||||
|
||||
size = os.path.getsize(path)
|
||||
if size < state["offset"]: # truncated or rotated under us: start over
|
||||
state = dict(fresh)
|
||||
if size == state["offset"]:
|
||||
return result(state)
|
||||
|
||||
with open(path, "rb") as fh:
|
||||
fh.seek(state["offset"])
|
||||
chunk = fh.read(TOKENS_SCAN_BUDGET)
|
||||
end = chunk.rfind(b"\n")
|
||||
if end < 0 and len(chunk) == TOKENS_SCAN_BUDGET: # one line bigger than the budget: finish it
|
||||
chunk += fh.readline()
|
||||
end = chunk.rfind(b"\n")
|
||||
if end < 0: # no complete new line yet
|
||||
return result(state)
|
||||
text = chunk[: end + 1].decode("utf-8", "ignore")
|
||||
|
||||
tin, tout = state["in"], state["out"]
|
||||
ids = [i for i in state["ids"] if isinstance(i, str)]
|
||||
seen = set(ids)
|
||||
tps = [s for s in (state.get("tps") or []) if isinstance(s, list) and len(s) == 2]
|
||||
tps_ids = [i for i in (state.get("tps_ids") or []) if isinstance(i, str)]
|
||||
tps_seen = set(tps_ids)
|
||||
for line in text.splitlines():
|
||||
if '"usage"' not in line:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
msg = obj.get("message") if isinstance(obj, dict) else None
|
||||
usage = msg.get("usage") if isinstance(msg, dict) else None
|
||||
if not isinstance(usage, dict):
|
||||
continue
|
||||
mid = msg.get("id") or obj.get("requestId") or obj.get("uuid")
|
||||
if not isinstance(mid, str):
|
||||
continue
|
||||
|
||||
def num(d, k):
|
||||
v = d.get(k, 0) if isinstance(d, dict) else 0
|
||||
return int(v) if isinstance(v, (int, float)) else 0
|
||||
|
||||
# Decode-speed sample: checked on every line (not just the first-wins one below) so
|
||||
# it does not depend on the thinking block being the message's first line.
|
||||
ms = num(obj, "thinkingDurationMs")
|
||||
toks = num(usage.get("output_tokens_details"), "thinking_tokens")
|
||||
if ms >= TPS_MIN_MS and toks >= TPS_MIN_TOKENS and mid not in tps_seen:
|
||||
tps_seen.add(mid)
|
||||
tps_ids.append(mid)
|
||||
tps.append([toks, ms])
|
||||
|
||||
if mid in seen:
|
||||
continue
|
||||
seen.add(mid)
|
||||
ids.append(mid)
|
||||
tin += num(usage, "input_tokens") + num(usage, "cache_creation_input_tokens") + num(usage, "cache_read_input_tokens")
|
||||
tout += num(usage, "output_tokens")
|
||||
|
||||
state = {
|
||||
"path": path,
|
||||
"offset": state["offset"] + end + 1,
|
||||
"in": tin,
|
||||
"out": tout,
|
||||
"ids": ids[-TOKENS_RECENT_IDS:],
|
||||
"tps": tps[-TPS_SAMPLES:],
|
||||
"tps_ids": tps_ids[-TOKENS_RECENT_IDS:],
|
||||
}
|
||||
try:
|
||||
os.makedirs(TOKENS_STATE_DIR, exist_ok=True)
|
||||
tmp = f"{state_path}.{os.getpid()}.tmp"
|
||||
with open(tmp, "w") as fh:
|
||||
json.dump(state, fh)
|
||||
os.replace(tmp, state_path) # atomic: a concurrent refresh never reads a half-written file
|
||||
_prune_tokens_state(state_path)
|
||||
except Exception:
|
||||
pass
|
||||
return result(state)
|
||||
|
||||
|
||||
# --- row 1: work ------------------------------------------------------------
|
||||
def vim_segment(data):
|
||||
"""Vim editor mode as a compact [I]/[N]/[V] (only present with editorMode: vim).
|
||||
|
||||
Pair with `"hideVimModeIndicator": true` in the statusLine settings block so
|
||||
Claude's own built-in indicator doesn't duplicate this one.
|
||||
"""
|
||||
mode = (data.get("vim") or {}).get("mode")
|
||||
if not mode:
|
||||
return ""
|
||||
m = mode.upper()
|
||||
if m.startswith("INSERT"):
|
||||
return color("[I]", "green", bold=True)
|
||||
if m.startswith("VISUAL"):
|
||||
return color("[V]", "magenta", bold=True)
|
||||
if m.startswith("NORMAL"):
|
||||
return color("[N]", "blue", bold=True)
|
||||
return color(f"[{m[:1]}]", "gray")
|
||||
|
||||
|
||||
def abbrev(path):
|
||||
"""fish-style prompt_pwd: shrink every component but the last to one char,
|
||||
keeping a leading dot (`.config` -> `.c`)."""
|
||||
parts = path.split(os.sep)
|
||||
out = []
|
||||
for i, p in enumerate(parts):
|
||||
if i == len(parts) - 1 or p in ("", "~"):
|
||||
out.append(p)
|
||||
elif p.startswith("."):
|
||||
out.append(p[:2])
|
||||
else:
|
||||
out.append(p[:1])
|
||||
return os.sep.join(out)
|
||||
|
||||
|
||||
def dir_segment(cwd, top=None):
|
||||
"""Path *inside* the repo -- git_segment already names the repo itself, so
|
||||
repeating the full ~-path here was pure duplication. Empty at the repo root;
|
||||
a fish-shortened ~-path when we're not in a repo at all."""
|
||||
try:
|
||||
rel = os.path.relpath(cwd, top) if top else None
|
||||
if rel and not rel.startswith(os.pardir): # `..` -> cwd is outside `top` (symlinked in); use the ~-path
|
||||
if rel == os.curdir:
|
||||
return ""
|
||||
shown = rel if len(rel) <= 28 else abbrev(rel)
|
||||
else:
|
||||
home = os.path.expanduser("~")
|
||||
shown = cwd
|
||||
if cwd == home:
|
||||
shown = "~"
|
||||
elif cwd.startswith(home + os.sep):
|
||||
shown = "~" + cwd[len(home):]
|
||||
shown = abbrev(shown)
|
||||
return "📁 " + color(shown, "cyan")
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _git(cwd, *args):
|
||||
return subprocess.run(
|
||||
["git", "-C", cwd, *args], capture_output=True, text=True, timeout=1
|
||||
)
|
||||
|
||||
|
||||
def git_top(cwd):
|
||||
"""Absolute path of the enclosing work tree, or None."""
|
||||
try:
|
||||
r = _git(cwd, "rev-parse", "--show-toplevel")
|
||||
return r.stdout.strip() or None if r.returncode == 0 else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def git_segment(cwd, top):
|
||||
try:
|
||||
if not top:
|
||||
return ""
|
||||
repo = os.path.basename(top) or "repo"
|
||||
branch = _git(cwd, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip() or "?"
|
||||
|
||||
# `status --porcelain` walks the whole work tree, so in a big repo it can blow
|
||||
# the 1s timeout -- in its own try, because letting that escape dropped the repo
|
||||
# and branch we already had: a decoration failing must not take the segment down.
|
||||
try:
|
||||
dirty = bool(_git(cwd, "status", "--porcelain").stdout.strip())
|
||||
except Exception:
|
||||
dirty = False
|
||||
|
||||
# ahead/behind vs upstream (omitted when no upstream is configured)
|
||||
ab = ""
|
||||
rl = _git(cwd, "rev-list", "--left-right", "--count", "@{upstream}...HEAD")
|
||||
if rl.returncode == 0 and rl.stdout.strip():
|
||||
try:
|
||||
behind, ahead = (int(x) for x in rl.stdout.split())
|
||||
bits = []
|
||||
if ahead:
|
||||
bits.append(color(f"↑{ahead}", "cyan"))
|
||||
if behind:
|
||||
bits.append(color(f"↓{behind}", "yellow"))
|
||||
if bits:
|
||||
ab = " " + "".join(bits)
|
||||
except Exception:
|
||||
ab = ""
|
||||
|
||||
mark = color("*", "red") if dirty else ""
|
||||
label = color(repo, "magenta", bold=True)
|
||||
br = color(branch, "yellow" if dirty else "green")
|
||||
return f"🌿 {label} {br}{mark}{ab}"
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
# --- PR review threads (gh, cached, fetched in the background) ------------------
|
||||
PR_TTL = 90 # seconds a fetched count stays fresh
|
||||
PR_ERR_TTL = 600 # back-off after a failed fetch (no GitHub remote, gh not authed, offline)
|
||||
PR_CLAIM = 30 # a refresher spawned this recently is still running: don't start another
|
||||
PR_CODEX = re.compile(r"codex", re.I) # chatgpt-codex-connector; same match as /pr-loop
|
||||
PR_QUERY = """query($owner:String!,$repo:String!,$branch:String!){
|
||||
repository(owner:$owner,name:$repo){
|
||||
pullRequests(headRefName:$branch,states:OPEN,first:1,orderBy:{field:UPDATED_AT,direction:DESC}){
|
||||
nodes{ number reviewThreads(first:100){ pageInfo{hasNextPage}
|
||||
nodes{ isResolved comments(first:1){ nodes{ author{login} } } } } } } } }"""
|
||||
|
||||
|
||||
def _pr_cache_path(top, branch):
|
||||
key = hashlib.sha1(f"{top}\0{branch}".encode()).hexdigest()[:16]
|
||||
return os.path.join(TOKENS_STATE_DIR, f"statusline.pr.{key}.json")
|
||||
|
||||
|
||||
def _read_json(path):
|
||||
try:
|
||||
with open(path) as fh:
|
||||
d = json.load(fh)
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def pr_refresh(cwd, branch, path):
|
||||
"""Background half of pr_segment (`statusline.py --pr-refresh CWD BRANCH CACHE`): fetch the
|
||||
branch's open PR and write its unresolved review-thread counts to the cache. `{owner}` /
|
||||
`{repo}` are gh placeholders resolved from the repo at `cwd`. A failed fetch keeps the last
|
||||
counts and flags them stale; a branch without an open PR clears them."""
|
||||
state = _read_json(path)
|
||||
state["ts"] = time.time()
|
||||
try:
|
||||
r = subprocess.run(
|
||||
["gh", "api", "graphql", "-F", "owner={owner}", "-F", "repo={repo}",
|
||||
"-f", f"branch={branch}", "-f", f"query={PR_QUERY}"],
|
||||
cwd=cwd, capture_output=True, text=True, timeout=20,
|
||||
)
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError(r.stderr)
|
||||
nodes = json.loads(r.stdout)["data"]["repository"]["pullRequests"]["nodes"]
|
||||
state = {"ts": state["ts"]}
|
||||
if nodes:
|
||||
threads = nodes[0]["reviewThreads"]
|
||||
# a thread belongs to whoever opened it: its first comment's author
|
||||
authors = [((t["comments"]["nodes"] or [{}])[0].get("author") or {}).get("login") or ""
|
||||
for t in threads["nodes"] if not t["isResolved"]]
|
||||
state.update(number=nodes[0]["number"], open=len(authors),
|
||||
codex=sum(1 for a in authors if PR_CODEX.search(a)),
|
||||
more=threads["pageInfo"]["hasNextPage"])
|
||||
except Exception:
|
||||
state["error"] = True
|
||||
try:
|
||||
os.makedirs(TOKENS_STATE_DIR, exist_ok=True)
|
||||
tmp = f"{path}.{os.getpid()}.tmp"
|
||||
with open(tmp, "w") as fh:
|
||||
json.dump(state, fh)
|
||||
os.replace(tmp, path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def pr_segment(cwd, top):
|
||||
"""Unresolved review threads (any author, outdated ones included) on the current branch's
|
||||
open PR: `💬 #N ✓` when none are left, else the count with Codex's share broken out.
|
||||
|
||||
A GitHub round trip takes ~0.7 s, too slow for a render, so this only reads a per-branch
|
||||
cache (~/.claude/cache/statusline.pr.<hash>.json) and, once it is older than PR_TTL,
|
||||
spawns a detached `--pr-refresh` child to update it -- the new count shows on the next
|
||||
render. PR-conversation comments are not counted: they have no resolved state, so a
|
||||
summary or an LGTM would keep the count from ever reaching zero.
|
||||
"""
|
||||
try:
|
||||
if not top or not shutil.which("gh"):
|
||||
return ""
|
||||
branch = _git(cwd, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
|
||||
if not branch or branch == "HEAD":
|
||||
return ""
|
||||
path = _pr_cache_path(top, branch)
|
||||
state = _read_json(path)
|
||||
if time.time() - (state.get("ts") or 0) > (PR_ERR_TTL if state.get("error") else PR_TTL):
|
||||
claim = path + ".lock"
|
||||
try:
|
||||
claimed = time.time() - os.path.getmtime(claim) < PR_CLAIM
|
||||
except OSError:
|
||||
claimed = False
|
||||
if not claimed:
|
||||
os.makedirs(TOKENS_STATE_DIR, exist_ok=True)
|
||||
with open(claim, "w"):
|
||||
pass
|
||||
# own session + no inherited stdout: Claude Code reads ours to EOF, and
|
||||
# cancels an in-flight render when the next one triggers
|
||||
subprocess.Popen(
|
||||
[sys.executable, os.path.abspath(__file__), "--pr-refresh", cwd, branch, path],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
)
|
||||
num = state.get("number")
|
||||
if not num:
|
||||
return ""
|
||||
n, codex = state.get("open") or 0, state.get("codex") or 0
|
||||
out = "💬 " + color(f"#{num} ", "gray")
|
||||
if not n:
|
||||
out += color("✓", "green")
|
||||
else:
|
||||
out += color(f"{n}{'+' if state.get('more') else ''}", "yellow", bold=True)
|
||||
if codex:
|
||||
out += color(" · ", "gray") + color(f"codex {codex}", "red")
|
||||
if state.get("error"):
|
||||
out += color(" ?", "gray") # last fetch failed: these counts are stale
|
||||
return out
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def model_segment(data):
|
||||
name = (data.get("model") or {}).get("display_name")
|
||||
if not name:
|
||||
return ""
|
||||
name = name.replace(" context)", ")") # "Opus 4.8 (1M context)" -> "Opus 4.8 (1M)"
|
||||
out = "🤖 " + color(name, "blue")
|
||||
level = (data.get("effort") or {}).get("level")
|
||||
if level:
|
||||
out += color(f" · {level}", "gray")
|
||||
return out
|
||||
|
||||
|
||||
def context_window(data):
|
||||
"""Size of this session's context window, in tokens.
|
||||
|
||||
Claude Code resolves the `[1m]` model suffix away before handing the status line
|
||||
its JSON -- `model.id` is always the bare API id ("claude-fable-5") -- so sniffing
|
||||
the id for "1m" could never detect a 1M session and every one of them was measured
|
||||
against a 200k window (5x overstated %, ⚠compact from ~16% real usage). The payload
|
||||
carries the real number; display_name ("Opus 4.8 (1M context)") is the fallback.
|
||||
"""
|
||||
cw = data.get("context_window")
|
||||
if isinstance(cw, dict):
|
||||
for key in ("context_window_size", "max_tokens", "size"):
|
||||
val = cw.get(key)
|
||||
if isinstance(val, (int, float)) and val > 0:
|
||||
return int(val)
|
||||
name = ((data.get("model") or {}).get("display_name") or "").lower()
|
||||
return 1_000_000 if "1m" in name else 200_000
|
||||
|
||||
|
||||
def context_segment(data, usage):
|
||||
try:
|
||||
if not usage:
|
||||
return ""
|
||||
used = (
|
||||
usage.get("input_tokens", 0)
|
||||
+ usage.get("cache_creation_input_tokens", 0)
|
||||
+ usage.get("cache_read_input_tokens", 0)
|
||||
)
|
||||
window = context_window(data)
|
||||
pct = used / window * 100 if window else 0
|
||||
# Prefer Claude Code's own percentage when the payload carries it (2.1.x) -- it
|
||||
# already accounts for the auto-compact reserve and window quirks we can't see.
|
||||
cw = data.get("context_window")
|
||||
if isinstance(cw, dict) and isinstance(cw.get("used_percentage"), (int, float)):
|
||||
pct = float(cw["used_percentage"])
|
||||
col = bucket(pct, 50, 80)
|
||||
out = "📝 " + color(f"{pct:.0f}%", col) + color(f" ({used / 1000:.0f}k)", "gray", dim=True)
|
||||
if pct >= 80:
|
||||
out += color(" ⚠compact", "red", bold=True)
|
||||
return out
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def usage_segment(data):
|
||||
"""5-hour rolling usage window: used % (+ time until it resets)."""
|
||||
try:
|
||||
five = (data.get("rate_limits") or {}).get("five_hour") or {}
|
||||
pct = five.get("used_percentage")
|
||||
if pct is None:
|
||||
return ""
|
||||
out = "📊 " + color(f"{pct:.0f}%", bucket(pct, 50, 80))
|
||||
resets = five.get("resets_at")
|
||||
if resets:
|
||||
secs = int(resets) - int(time.time())
|
||||
if secs > 0:
|
||||
h, m = divmod(secs // 60, 60)
|
||||
out += color(f" {h}h{m:02d}m" if h else f" {m}m", "gray")
|
||||
return out
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def cost_segment(data):
|
||||
try:
|
||||
cost = data.get("cost") or {}
|
||||
usd = cost.get("total_cost_usd")
|
||||
if usd is None:
|
||||
return ""
|
||||
out = "💰 " + color(f"${usd:.2f}", "yellow")
|
||||
dur_ms = cost.get("total_duration_ms") or 0
|
||||
if dur_ms > 30_000: # need a meaningful window before extrapolating
|
||||
per_hr = usd / (dur_ms / 3_600_000)
|
||||
out += color(f" ${per_hr:.2f}/h", "gray", dim=True)
|
||||
return out
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def velocity_segment(data):
|
||||
try:
|
||||
cost = data.get("cost") or {}
|
||||
added = cost.get("total_lines_added", 0)
|
||||
removed = cost.get("total_lines_removed", 0)
|
||||
if not (added or removed):
|
||||
return ""
|
||||
out = "✏️ " + color(f"+{added}", "green") + color("/", "gray", dim=True) + color(f"-{removed}", "red")
|
||||
dur_ms = cost.get("total_duration_ms") or 0
|
||||
if dur_ms > 30_000:
|
||||
per_min = added / (dur_ms / 60_000)
|
||||
out += color(f" {per_min:.0f}/m", "gray", dim=True)
|
||||
return out
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def tokens_segment(totals):
|
||||
"""Cumulative session tokens: ↑ input (incl. cache reads/writes) and ↓ output."""
|
||||
try:
|
||||
if not totals:
|
||||
return ""
|
||||
tin, tout = totals["in"], totals["out"]
|
||||
if not (tin or tout):
|
||||
return ""
|
||||
return "🔢 " + color(f"↑{fmt_tokens(tin)}", "cyan") + " " + color(f"↓{fmt_tokens(tout)}", "green")
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def tps_segment(totals):
|
||||
"""Decode speed in tokens/s: duration-weighted mean over the last few thinking blocks
|
||||
(see session_tokens). Omitted until a thinking block ≥1s has completed -- so never
|
||||
shown with thinking disabled."""
|
||||
try:
|
||||
samples = (totals or {}).get("tps") or []
|
||||
toks = sum(s[0] for s in samples)
|
||||
ms = sum(s[1] for s in samples)
|
||||
if toks <= 0 or ms <= 0:
|
||||
return ""
|
||||
rate = toks / ms * 1000
|
||||
return "⚡ " + color(f"{rate:.0f} t/s", bucket(rate, 20, 40, invert=True))
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def cache_segment(usage, data=None):
|
||||
"""Prompt-cache hit % (higher is better) + the cache TTL, `·cold` when the cache has
|
||||
expired. Hit % from the 2.1.260+ payload `prompt_cache.hit_ratio` (a 0..1 fraction, null
|
||||
while all counts are zero), else computed from the usage block; ttl/cold always from the
|
||||
payload when present. A 1h TTL is what keeps a 10-minute pr-loop cadence warm."""
|
||||
try:
|
||||
pc = (data or {}).get("prompt_cache")
|
||||
pc = pc if isinstance(pc, dict) else {}
|
||||
pct = None
|
||||
if isinstance(pc.get("hit_ratio"), (int, float)):
|
||||
pct = float(pc["hit_ratio"]) * 100
|
||||
elif usage:
|
||||
read = usage.get("cache_read_input_tokens", 0)
|
||||
total = usage.get("input_tokens", 0) + usage.get("cache_creation_input_tokens", 0) + read
|
||||
if total > 0:
|
||||
pct = read / total * 100
|
||||
if pct is None:
|
||||
return ""
|
||||
out = "♻️ " + color(f"{pct:.0f}%", bucket(pct, 50, 80, invert=True))
|
||||
ttl = pc.get("ttl")
|
||||
if isinstance(ttl, str) and ttl:
|
||||
out += color(f" {ttl}", "gray")
|
||||
if pc.get("warm") is False:
|
||||
out += color(" ·cold", "yellow")
|
||||
return out
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def api_segment(data):
|
||||
"""Share of wall-clock time spent in API/inference (rough 'busy' ratio)."""
|
||||
try:
|
||||
cost = data.get("cost") or {}
|
||||
wall = cost.get("total_duration_ms") or 0
|
||||
api = cost.get("total_api_duration_ms") or 0
|
||||
if wall <= 0 or api <= 0:
|
||||
return ""
|
||||
pct = min(api / wall * 100, 100)
|
||||
return "⚙️ " + color(f"{pct:.0f}%", "blue")
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
# --- row 2: system ----------------------------------------------------------
|
||||
def ram_segment():
|
||||
try:
|
||||
info = {}
|
||||
with open("/proc/meminfo") as fh:
|
||||
for line in fh:
|
||||
k, _, v = line.partition(":")
|
||||
info[k.strip()] = int(v.split()[0]) # kB
|
||||
total = info.get("MemTotal", 0)
|
||||
avail = info.get("MemAvailable", info.get("MemFree", 0))
|
||||
if total <= 0:
|
||||
return ""
|
||||
used = total - avail
|
||||
pct = used / total * 100
|
||||
g = 1024 * 1024
|
||||
return (
|
||||
"🧠 " + color(f"{pct:.0f}%", bucket(pct, 70, 85))
|
||||
+ color(f" {used / g:.1f}/{total / g:.0f}G", "gray", dim=True)
|
||||
)
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def disk_segment(cwd):
|
||||
try:
|
||||
st = os.statvfs(cwd)
|
||||
total = st.f_blocks
|
||||
if total <= 0:
|
||||
return ""
|
||||
used = total - st.f_bfree
|
||||
pct = used / total * 100
|
||||
return "💾 " + color(f"{pct:.0f}%", bucket(pct, 75, 90))
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _cpu_pct():
|
||||
"""Live CPU% diffed against a cached /proc/stat snapshot (no sleeping)."""
|
||||
try:
|
||||
with open("/proc/stat") as fh:
|
||||
parts = fh.readline().split()
|
||||
if not parts or parts[0] != "cpu":
|
||||
return None
|
||||
vals = [int(x) for x in parts[1:]]
|
||||
idle = vals[3] + (vals[4] if len(vals) > 4 else 0) # idle + iowait
|
||||
total = sum(vals)
|
||||
|
||||
state = os.path.expanduser("~/.claude/cache/statusline.cpu")
|
||||
prev = None
|
||||
try:
|
||||
with open(state) as fh:
|
||||
pt, pi = fh.read().split()
|
||||
prev = (int(pt), int(pi))
|
||||
except Exception:
|
||||
prev = None
|
||||
try:
|
||||
os.makedirs(os.path.dirname(state), exist_ok=True)
|
||||
with open(state, "w") as fh:
|
||||
fh.write(f"{total} {idle}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not prev:
|
||||
return None
|
||||
dt = total - prev[0]
|
||||
di = idle - prev[1]
|
||||
if dt <= 0 or di < 0:
|
||||
return None
|
||||
return max(0.0, min(100.0, (1 - di / dt) * 100))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def cpu_segment():
|
||||
try:
|
||||
load1 = os.getloadavg()[0]
|
||||
cores = os.cpu_count() or 1
|
||||
pct = _cpu_pct()
|
||||
if pct is not None:
|
||||
head = color(f"{pct:.0f}%", bucket(pct, 60, 85))
|
||||
tail = color(f" {load1:.1f} {cores}c", "gray", dim=True)
|
||||
else:
|
||||
head = color(f"{load1:.2f}", bucket(load1 / cores, 0.7, 1.0))
|
||||
tail = color(f" {cores}c", "gray", dim=True)
|
||||
return "🖥️ " + head + tail
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def temp_segment():
|
||||
"""Hottest CPU-ish thermal zone in °C, falling back to the max zone."""
|
||||
try:
|
||||
base = "/sys/class/thermal"
|
||||
if not os.path.isdir(base):
|
||||
return ""
|
||||
prefer = ("x86_pkg_temp", "coretemp", "cpu", "k10temp", "tctl")
|
||||
chosen = None
|
||||
fallback = None
|
||||
for name in os.listdir(base):
|
||||
if not name.startswith("thermal_zone"):
|
||||
continue
|
||||
d = os.path.join(base, name)
|
||||
try:
|
||||
with open(os.path.join(d, "temp")) as fh:
|
||||
milli = int(fh.read().strip())
|
||||
except Exception:
|
||||
continue
|
||||
ztype = ""
|
||||
try:
|
||||
with open(os.path.join(d, "type")) as fh:
|
||||
ztype = fh.read().strip().lower()
|
||||
except Exception:
|
||||
pass
|
||||
if fallback is None or milli > fallback:
|
||||
fallback = milli
|
||||
if any(p in ztype for p in prefer) and (chosen is None or milli > chosen):
|
||||
chosen = milli
|
||||
milli = chosen if chosen is not None else fallback
|
||||
if milli is None:
|
||||
return ""
|
||||
c = milli / 1000.0
|
||||
return "🌡️ " + color(f"{c:.0f}°C", bucket(c, 60, 80))
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def version_segment(data):
|
||||
v = data.get("version")
|
||||
return color(f"v{v}", "gray", dim=True) if v else ""
|
||||
|
||||
|
||||
def style_segment(data):
|
||||
name = (data.get("output_style") or {}).get("name")
|
||||
return color(f"🎨{name}", "gray", dim=True) if name else ""
|
||||
|
||||
|
||||
def main():
|
||||
if sys.argv[1:2] == ["--pr-refresh"] and len(sys.argv) == 5:
|
||||
pr_refresh(*sys.argv[2:])
|
||||
return
|
||||
try:
|
||||
data = json.load(sys.stdin)
|
||||
except Exception:
|
||||
data = {}
|
||||
|
||||
cwd = (
|
||||
(data.get("workspace") or {}).get("current_dir")
|
||||
or data.get("cwd")
|
||||
or os.getcwd()
|
||||
)
|
||||
usage = payload_usage(data) or last_usage(data)
|
||||
totals = session_tokens(data)
|
||||
top = git_top(cwd)
|
||||
|
||||
# One row: work (left) then system (right), joined. If it would overflow the
|
||||
# terminal, trailing (lowest-priority) segments are dropped so it stays one line.
|
||||
# Dormant helpers kept above for easy re-add: ram_segment, cpu_segment,
|
||||
# temp_segment (retired -- they only refresh on message events, so they sat
|
||||
# stale; the tmux status bar owns system metrics now), velocity_segment,
|
||||
# api_segment, version_segment, style_segment.
|
||||
work = [s for s in (
|
||||
vim_segment(data),
|
||||
dir_segment(cwd, top),
|
||||
git_segment(cwd, top),
|
||||
pr_segment(cwd, top),
|
||||
model_segment(data),
|
||||
context_segment(data, usage),
|
||||
usage_segment(data),
|
||||
cost_segment(data),
|
||||
tokens_segment(totals),
|
||||
tps_segment(totals),
|
||||
cache_segment(usage, data),
|
||||
) if s]
|
||||
system = [s for s in (
|
||||
disk_segment(cwd),
|
||||
) if s]
|
||||
|
||||
segs = work + system
|
||||
cols = term_cols()
|
||||
if cols: # trim from the right until it fits one line (cols=0 -> width unknown, keep all)
|
||||
while len(segs) > 1 and vlen(join_line(segs)) > cols:
|
||||
segs.pop()
|
||||
sys.stdout.write(join_line(segs))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user