dots: public mirror (history reset after licence cleanup)

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

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
# NOTE: the lw/ and wm/ host overlays carry full-file copies of this config — mirror changes there.
# see https://github.com/sigoden/aichat/blob/main/config.example.yaml
keybindings: vi
editor: nvim
model: local:Qwen3.6-35B-A3B-Thinking
# Sessions: persist REPL sessions and keep more history before summarizing.
# The default compress_threshold (4000) summarizes far too early for 24k+ windows.
save_session: true
compress_threshold: 16000
# REPL prompts show live context usage (needs max_input_tokens, set per model below)
left_prompt: '{color.green}{?session {session}{?role /}}{role}{color.cyan}{?rag @{rag}}{color.reset}> '
right_prompt: '{color.purple}{?session {consume_tokens}/{max_input_tokens} }{color.reset}'
# NOTE: temperature/top_p are intentionally unset — the LAN server applies tuned
# per-model sampling via --jinja (e.g. GLM 0.6/0.95); a global value would clobber it.
# max_input_tokens = real ctx-size (from the router) minus output headroom.
clients:
# LAN access (fast; only reachable on the home network)
- type: openai-compatible
name: local
api_base: http://192.168.0.204:11343/v1
models: &lan_models
# Speeds are benched decode t/s (clean-night sweeps) — see fl/.config/llamacpp/README.md roster.
- name: Qwen3-Coder-30B-Instruct-UD-Q3_K_XL
max_input_tokens: 30000 # ctx 32768 · ~30 t/s — main agent coder
- name: Qwen3-Coder-Next-UD-IQ3_XXS
max_input_tokens: 128000 # ctx 131072 · ~16 t/s — long sessions (128k)
- name: Qwen3.6-35B-A3B-MTP-UD-IQ3_XXS
max_input_tokens: 22000 # ctx 24576 · ~36 t/s — daily driver
supports_vision: true
- name: Qwen3.6-35B-A3B-Thinking
max_input_tokens: 22000 # ctx 24576 · ~39 t/s — hard problems
supports_vision: true
- name: Qwen3.5-9B-UD-Q6_K_XL
max_input_tokens: 30000 # ctx 32768 · ~32 t/s — quick tasks
supports_vision: true
- name: Qwen3.8-27B-UD-IQ3_XXS
max_input_tokens: 22000 # ctx 24576 · ~15 t/s — hybrid reasoner, quiet desktop only
supports_vision: true
- name: gemma-4-26B-A4B-it-UD-IQ4_XS
max_input_tokens: 22000 # ctx 24576 · ~34 t/s — quality generalist, best vision
supports_vision: true
- name: gemma-4-E4B-it-UD-Q8_K_XL
max_input_tokens: 62000 # ctx 65536 · ~57 t/s — fast generalist, long docs
supports_vision: true
- name: GLM-4.7-Flash-UD-Q4_K_XL
max_input_tokens: 22000 # ctx 24576 · ~21 t/s — quality coder
- name: GLM-4.7-Flash-UD-Q3_K_XL
max_input_tokens: 22000 # ctx 24576 · ~28 t/s — fast coder (3-bit)
- name: Ornith-1.5-35B-A3B-IQ3_XXS
max_input_tokens: 30000 # ctx 32768 · ~32 t/s — agentic coder, thinking
supports_vision: true
- name: gpt-oss-20b
max_input_tokens: 62000 # ctx 65536 · ~38 t/s — fast reasoning + tools
- name: gpt-oss-20b-low
max_input_tokens: 62000 # ctx 65536 · ~37 t/s — snappy answers
# Remote access via duskadiy.com (reachable from anywhere; requires an API key —
# $DUSKADIY_API_KEY, from the gitignored conf.d/secrets.fish). The LAN endpoint above is keyless.
# Same server, same model ids — reuse the list above via a YAML anchor.
- type: openai-compatible
name: duskadiy
api_base: https://llm.duskadiy.com/api/v1
models: *lan_models
+9
View File
@@ -0,0 +1,9 @@
---
temperature: 0.2
---
You are a terse coding assistant.
- Lead with the code, as a single fenced block.
- Add at most 1–2 short sentences of explanation, and only if genuinely needed. No preamble, no "here is", no closing summary.
- Match the language and style implied by the question; if unspecified, infer the most likely one.
- If the request is ambiguous, make the most reasonable assumption and state it in one line above the code.
+11
View File
@@ -0,0 +1,11 @@
---
temperature: 0.2
---
You write a git commit message from a diff. Output ONLY the message — no preamble, no code fences, no explanation.
- Subject: `[Scope] imperative summary`, where Scope is a short tag inferred from the changed paths, matching the style of recent `git log` (e.g. [Waybar], [Fish], [LLM]). Keep it under 70 characters.
- Imperative mood ("add", "fix", "rename"), never past tense.
- For a non-trivial change, leave a blank line then add 1–4 terse bullets ("- ...") covering what changed and why. Omit the body for small, self-explanatory changes.
- Describe only what the diff actually shows; do not invent rationale or files.
The user's input is the diff (typically `git diff --cached`).
+9
View File
@@ -0,0 +1,9 @@
---
temperature: 0.1
---
You translate a request into a single shell command for the fish shell on Arch Linux. Output ONLY the command on one line — no code fence, no explanation.
- Use fish syntax, not bash. Notably: `set -x VAR value` (not `export`), `$status` (not `$?`), the `test` / `string` / `math` builtins, and `(cmd)` for command substitution (not `$(cmd)`). `&&` / `||` work in modern fish.
- Package management is pacman / yay (`yay -S`, `pacman -Qi`, `pacman -Qo`). Clipboard is Wayland: `wl-copy` / `wl-paste`.
- Prefer one pipeline. If several steps are unavoidable, chain them with `; and`.
- If it can't be done safely in one command, output a single `# ...` comment saying why instead.
+11
View File
@@ -0,0 +1,11 @@
---
temperature: 0.2
---
You review a code diff for defects. Be concise and specific.
- Focus on correctness bugs, edge cases, error handling, security issues, and clear regressions. Skip style and formatting nits unless they cause a bug.
- Format each finding as `file:line — issue — why it matters`, most severe first.
- Reference exact identifiers and lines from the diff; do not speculate about code you cannot see.
- If nothing substantive is wrong, say so in one line rather than inventing issues.
The user's input is the diff (typically `git diff`).
+10
View File
@@ -0,0 +1,10 @@
---
model: local:gemma-4-E4B-it-UD-Q8_K_XL
temperature: 0.1
---
You translate a request into a single shell command for the fish shell on Arch Linux. Output ONLY the command on one line — no code fence, no explanation.
- Use fish syntax, not bash. Notably: `set -x VAR value` (not `export`), `$status` (not `$?`), the `test` / `string` / `math` builtins, and `(cmd)` for command substitution (not `$(cmd)`). `&&` / `||` work in modern fish.
- Package management is pacman / yay (`yay -S`, `pacman -Qi`, `pacman -Qo`). Clipboard is Wayland: `wl-copy` / `wl-paste`.
- Prefer one pipeline. If several steps are unavoidable, chain them with `; and`.
- If it can't be done safely in one command, output a single `# ...` comment saying why instead.
+34
View File
@@ -0,0 +1,34 @@
# This is `bat`s configuration file. Each line either contains a comment or
# a command-line option that you want to pass to `bat` by default. You can
# run `bat --help` to get a list of all possible configuration options.
# Specify desired highlighting theme (e.g. "TwoDark"). Run `bat --list-themes`
# for a list of all available themes
# OneHalfDark is built into bat — no custom themes are tracked, so no `bat cache --build` step
--theme="OneHalfDark"
--style="numbers,changes,header,snip"
# Enable this to use italic text on the terminal. This is not supported on all
# terminal emulators (like tmux, by default):
--italic-text=always
# Uncomment the following line to disable automatic paging:
#--paging=never
# Uncomment the following line if you are using less version >= 551 and want to
# enable mouse scrolling support in `bat` when running inside tmux. This might
# disable text selection, unless you press shift.
--pager="less --RAW-CONTROL-CHARS --quit-if-one-screen --mouse --ignore-case"
# Syntax mappings: map a certain filename pattern to a language.
# Example 1: use the C++ syntax for Arduino .ino files
# Example 2: Use ".gitignore"-style highlighting for ".ignore" files
--map-syntax "*.ino:C++"
--map-syntax ".ignore:Git Ignore"
--map-syntax "**/hypr/**/*.conf:INI"
--map-syntax "**/kitty/*.conf:INI"
--map-syntax "*.ctl:INI"
--map-syntax ".inputrc:bash"
--map-syntax "**/cava/config:INI"
--map-syntax "**/mpv/*.conf:INI"
--map-syntax "**/btop/btop.conf:INI"
+286
View File
@@ -0,0 +1,286 @@
#? Config file for btop v.1.4.7
#* Name of a btop++/bpytop/bashtop formatted ".theme" file, "Default" and "TTY" for builtin themes.
#* Themes should be placed in "../share/btop/themes" relative to binary or "$HOME/.config/btop/themes"
color_theme = "Default"
#* If the theme set background should be shown, set to False if you want terminal background transparency.
theme_background = false
#* Sets if 24-bit truecolor should be used, will convert 24-bit colors to 256 color (6x6x6 color cube) if false.
truecolor = true
#* Set to true to force tty mode regardless if a real tty has been detected or not.
#* Will force 16-color mode and TTY theme, set all graph symbols to "tty" and swap out other non tty friendly symbols.
force_tty = false
#* Option to disable presets. Either the default preset, custom presets, or all presets.
#* "Off" All presets are enabled.
#* "Default" preset is disabled.#* "Custom" presets are disabled.#* "All" presets are disabled.
disable_presets = "Off"
#* Define presets for the layout of the boxes. Preset 0 is always all boxes shown with default settings. Max 9 presets.
#* Format: "box_name:P:G,box_name:P:G" P=(0 or 1) for alternate positions, G=graph symbol to use for box.
#* Use whitespace " " as separator between different presets.
#* Example: "cpu:0:default,mem:0:tty,proc:1:default cpu:0:braille,proc:0:tty"
presets = "cpu:1:default,proc:0:default cpu:0:default,mem:0:default,net:0:default cpu:0:block,net:0:tty"
#* Set to True to enable "h,j,k,l,g,G" keys for directional control in lists.
#* Conflicting keys for h:"help" and k:"kill" is accessible while holding shift.
vim_keys = true
#* Disable all mouse events.
disable_mouse = false
#* Rounded corners on boxes, is ignored if TTY mode is ON.
rounded_corners = true
#* Use terminal synchronized output sequences to reduce flickering on supported terminals.
terminal_sync = true
#* Default symbols to use for graph creation, "braille", "block" or "tty".
#* "braille" offers the highest resolution but might not be included in all fonts.
#* "block" has half the resolution of braille but uses more common characters.
#* "tty" uses only 3 different symbols but will work with most fonts and should work in a real TTY.
#* Note that "tty" only has half the horizontal resolution of the other two, so will show a shorter historical view.
graph_symbol = "braille"
# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty".
graph_symbol_cpu = "default"
# Graph symbol to use for graphs in gpu box, "default", "braille", "block" or "tty".
graph_symbol_gpu = "default"
# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty".
graph_symbol_mem = "default"
# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty".
graph_symbol_net = "default"
# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty".
graph_symbol_proc = "default"
#* Manually set which boxes to show. Available values are "cpu mem net proc" and "gpu0" through "gpu5", separate values with whitespace.
shown_boxes = "proc cpu mem net"
#* Update time in milliseconds, recommended 2000 ms or above for better sample times for graphs.
update_ms = 2000
#* Processes sorting, "pid" "program" "arguments" "threads" "user" "memory" "cpu lazy" "cpu direct",
#* "cpu lazy" sorts top process over time (easier to follow), "cpu direct" updates top process directly.
proc_sorting = "cpu lazy"
#* Reverse sorting order, True or False.
proc_reversed = false
#* Show processes as a tree.
proc_tree = true
#* Use the cpu graph colors in the process list.
proc_colors = true
#* Use a darkening gradient in the process list.
proc_gradient = true
#* If process cpu usage should be of the core it's running on or usage of the total available cpu power.
proc_per_core = false
#* Show process memory as bytes instead of percent.
proc_mem_bytes = true
#* Show cpu graph for each process.
proc_cpu_graphs = true
#* Use /proc/[pid]/smaps for memory information in the process info box (very slow but more accurate)
proc_info_smaps = false
#* Show proc box on left side of screen instead of right.
proc_left = false
#* (Linux) Filter processes tied to the Linux kernel(similar behavior to htop).
proc_filter_kernel = false
#* Should the process list follow the selected process when detailed view is open.
proc_follow_detailed = true
#* In tree-view, always accumulate child process resources in the parent process.
proc_aggregate = false
#* Should cpu and memory usage display be preserved for dead processes when paused.
keep_dead_proc_usage = false
#* Sets the CPU stat shown in upper half of the CPU graph, "total" is always available.
#* Select from a list of detected attributes from the options menu.
cpu_graph_upper = "Auto"
#* Sets the CPU stat shown in lower half of the CPU graph, "total" is always available.
#* Select from a list of detected attributes from the options menu.
cpu_graph_lower = "Auto"
#* If gpu info should be shown in the cpu box. Available values = "Auto", "On" and "Off".
show_gpu_info = "Auto"
#* Toggles if the lower CPU graph should be inverted.
cpu_invert_lower = true
#* Set to True to completely disable the lower CPU graph.
cpu_single_graph = false
#* Show cpu box at bottom of screen instead of top.
cpu_bottom = false
#* Shows the system uptime in the CPU box.
show_uptime = true
#* Shows the CPU package current power consumption in watts. Requires running `make setcap` or `make setuid` or running with sudo.
show_cpu_watts = true
#* Show cpu temperature.
check_temp = true
#* Which sensor to use for cpu temperature, use options menu to select from list of available sensors.
cpu_sensor = "Auto"
#* Show temperatures for cpu cores also if check_temp is True and sensors has been found.
show_coretemp = true
#* Set a custom mapping between core and coretemp, can be needed on certain cpus to get correct temperature for correct core.
#* Use lm-sensors or similar to see which cores are reporting temperatures on your machine.
#* Format "x:y" x=core with wrong temp, y=core with correct temp, use space as separator between multiple entries.
#* Example: "4:0 5:1 6:3"
cpu_core_map = ""
#* Which temperature scale to use, available values: "celsius", "fahrenheit", "kelvin" and "rankine".
temp_scale = "celsius"
#* Use base 10 for bits/bytes sizes, KB = 1000 instead of KiB = 1024.
base_10_sizes = false
#* Show CPU frequency.
show_cpu_freq = true
#* How to calculate CPU frequency, available values: "first", "range", "lowest", "highest" and "average".
freq_mode = "first"
#* Draw a clock at top of screen, formatting according to strftime, empty string to disable.
#* Special formatting: /host = hostname | /user = username | /uptime = system uptime
clock_format = "%X"
#* Update main ui in background when menus are showing, set this to false if the menus is flickering too much for comfort.
background_update = true
#* Custom cpu model name, empty string to disable.
custom_cpu_name = ""
#* Optional filter for shown disks, should be full path of a mountpoint, separate multiple values with whitespace " ".
#* Only disks matching the filter will be shown. Prepend exclude= to only show disks not matching the filter. Examples: disk_filter="/boot /home/user", disks_filter="exclude=/boot /home/user"
disks_filter = ""
#* Show graphs instead of meters for memory values.
mem_graphs = true
#* Show mem box below net box instead of above.
mem_below_net = false
#* Count ZFS ARC in cached and available memory.
zfs_arc_cached = true
#* If swap memory should be shown in memory box.
show_swap = true
#* Show swap as a disk, ignores show_swap value above, inserts itself after first disk.
swap_disk = true
#* If mem box should be split to also show disks info.
show_disks = true
#* Filter out non physical disks. Set this to False to include network disks, RAM disks and similar.
only_physical = true
#* Read disks list from /etc/fstab. This also disables only_physical.
use_fstab = true
#* Setting this to True will hide all datasets, and only show ZFS pools. (IO stats will be calculated per-pool)
zfs_hide_datasets = false
#* Set to true to show available disk space for privileged users.
disk_free_priv = false
#* Toggles if io activity % (disk busy time) should be shown in regular disk usage view.
show_io_stat = true
#* Toggles io mode for disks, showing big graphs for disk read/write speeds.
io_mode = false
#* Set to True to show combined read/write io graphs in io mode.
io_graph_combined = false
#* Set the top speed for the io graphs in MiB/s (100 by default), use format "mountpoint:speed" separate disks with whitespace " ".
#* Example: "/mnt/media:100 /:20 /boot:1".
io_graph_speeds = ""
#* Swap the positions of the upload and download speed graphs. When true, upload will be on top.
swap_upload_download = false
#* Set fixed values for network graphs in Mebibits. Is only used if net_auto is also set to False.
net_download = 100
net_upload = 100
#* Use network graphs auto rescaling mode, ignores any values set above and rescales down to 10 Kibibytes at the lowest.
net_auto = true
#* Sync the auto scaling for download and upload to whichever currently has the highest scale.
net_sync = true
#* Starts with the Network Interface specified here.
net_iface = ""
#* "True" shows bitrates in base 10 (Kbps, Mbps). "False" shows bitrates in binary sizes (Kibps, Mibps, etc.). "Auto" uses base_10_sizes.
base_10_bitrate = "Auto"
#* Show battery stats in top right if battery is present.
show_battery = true
#* Which battery to use if multiple are present. "Auto" for auto detection.
selected_battery = "Auto"
#* Show power stats of battery next to charge indicator.
show_battery_watts = true
#* Set loglevel for "~/.local/state/btop.log" levels are: "ERROR" "WARNING" "INFO" "DEBUG".
#* The level set includes all lower levels, i.e. "DEBUG" will show all logging info.
log_level = "WARNING"
#* Automatically save current settings to config file on exit.
save_config_on_exit = false
#* Measure PCIe throughput on NVIDIA cards, may impact performance on certain cards.
nvml_measure_pcie_speeds = true
#* Measure PCIe throughput on AMD cards, may impact performance on certain cards.
rsmi_measure_pcie_speeds = true
#* Horizontally mirror the GPU graph.
gpu_mirror_graph = true
#* Set which GPU vendors to show. Available values are "nvidia amd intel apple"
shown_gpus = "nvidia amd intel"
#* Custom gpu0 model name, empty string to disable.
custom_gpu_name0 = ""
#* Custom gpu1 model name, empty string to disable.
custom_gpu_name1 = ""
#* Custom gpu2 model name, empty string to disable.
custom_gpu_name2 = ""
#* Custom gpu3 model name, empty string to disable.
custom_gpu_name3 = ""
#* Custom gpu4 model name, empty string to disable.
custom_gpu_name4 = ""
#* Custom gpu5 model name, empty string to disable.
custom_gpu_name5 = ""
+19
View File
@@ -0,0 +1,19 @@
## cava — only this repo's own settings. Every key left out falls back to cava's built-in
## default; cava documents them all in the config it writes to an empty ~/.config/cava/config,
## and it regenerates its own shaders/ and themes/ there on first run (so the repo ships none
## of cava's files).
[general]
framerate = 60
autosens = 1
[color]
gradient = 1
gradient_color_1 = '#d34b11'
gradient_color_2 = '#cc5933'
gradient_color_3 = '#cc8033'
gradient_color_4 = '#cca633'
gradient_color_5 = '#cccc33'
gradient_color_6 = '#a6cc33'
gradient_color_7 = '#80cc33'
gradient_color_8 = '#59cc33'
+179
View File
@@ -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/`.
+83
View File
@@ -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.
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
# SessionStart hook: refuse to let a severed dotfiles link go unnoticed.
#
# Claude Code writes settings with an atomic temp+rename. Through the stow layer that can
# replace ~/.config/claude/<file> (a symlink into the repo) with a plain FILE holding whatever
# snapshot the writing process had in memory -- silently freezing every later repo edit out
# of the live config. It happened on 2026-09-15 23:31: a stale copy dropped four hook events
# (git-guard among them) and nobody noticed for an hour. link.sh heals the identical case but
# only when run; this makes every session start say so instead.
#
# Read-only: it never relinks. Exit 2 on SessionStart shows stderr to the user and the session
# continues. Exit 0 when everything resolves into the repo.
set -u
src="$HOME/.config/claude"
bad=""
for f in settings.json statusline.py keybindings.json CLAUDE.md link.sh; do
p="$src/$f"
[ -e "$p" ] || continue
if [ ! -L "$p" ]; then bad="$bad $p is a plain file (should be a symlink into the dots repo)"$'\n'; fi
done
# the ~/.claude side too: link.sh's own guard covers it, but only when link.sh runs
for f in settings.json keybindings.json CLAUDE.md statusline.py; do
p="$HOME/.claude/$f"
[ -e "$p" ] || continue
case "$(readlink -f "$p")" in
*"/.dots/"*) ;;
*) bad="$bad $p resolves to $(readlink -f "$p"), not into the dots repo"$'\n' ;;
esac
done
[ -z "$bad" ] && exit 0
printf 'DRIFT: Claude config has broken out of the dots repo; the live config is a stale copy.\n%s fix: review with `diff`, then `bash ~/.config/claude/link.sh` (heals identical copies, warns otherwise)\n' "$bad" >&2
exit 2
+254
View File
@@ -0,0 +1,254 @@
#!/usr/bin/env python3
"""PostToolUse hook: format an edited file with the right formatter.
Reads the hook JSON from stdin, works out which file(s) were just edited, and runs a
language-appropriate formatter -- but, to avoid imposing a style on a project
that never asked for it, every formatter here only runs when the project opts in
via a config file discoverable by walking up from the edited file: stylua, ruff,
prettier and taplo on their own configs, gofmt and rustfmt on go.mod / Cargo.toml,
shfmt and fish_indent on .editorconfig. No marker, no formatting -- a repo that
hand-formats its shell keeps its own layout.
Two entry points, both wired in settings.json > hooks > PostToolUse:
* Edit|Write -- the edited path is `tool_input.file_path`.
* Bash -- under `defaultMode: auto` Claude is steered to edit through the shell
(sed -i, heredocs, python), which the Edit|Write matcher never sees.
There is no per-file event for that (`FileChanged` only watches literal
filenames), so this scans `tool_input.command` for path-like tokens with a
handled extension and formats the ones modified in the last few seconds --
the mtime gate keeps a parallel session's dirty files out of it.
Best-effort: always exits 0 so a format hiccup never blocks an edit. jq is not
guaranteed on the host, hence python for the stdin JSON parse.
"""
import fnmatch
import json
import os
import re
import shutil
import subprocess
import sys
import time
def find_up(start, names):
"""Nearest ancestor dir (incl. the file's own) containing any of `names`."""
d = os.path.dirname(os.path.abspath(start))
while True:
if any(os.path.exists(os.path.join(d, n)) for n in names):
return d
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _expand_braces(pat):
"""`a{b,c}` -> [`ab`, `ac`] (editorconfig sections use {,} alternation)."""
m = re.search(r"\{([^{}]*)\}", pat)
if not m:
return [pat]
out = []
for alt in m.group(1).split(","):
out.extend(_expand_braces(pat[: m.start()] + alt + pat[m.end():]))
return out
def editorconfig_covers(path):
"""True if the nearest ancestor .editorconfig has a section matching `path`.
Mere existence is NOT opt-in: this repo's .editorconfig is deliberately scoped
to `[{*.sh,dotsync,dotpub}]` with no [*] block precisely so fish files stay
untouched, and a generic upstream .editorconfig must not switch a formatter on
for filetypes it never mentions. Patterns without a `/` match the basename
(the editorconfig convention); ones with a `/` match the path relative to the
.editorconfig's directory.
"""
d = find_up(path, [".editorconfig"])
if not d:
return False
name = os.path.basename(path)
rel = os.path.relpath(os.path.abspath(path), d)
try:
with open(os.path.join(d, ".editorconfig"), errors="ignore") as fh:
for line in fh:
line = line.strip()
if not (line.startswith("[") and line.endswith("]")):
continue
for pat in _expand_braces(line[1:-1]):
target = rel if "/" in pat else name
if fnmatch.fnmatch(target, pat.lstrip("/")):
return True
except Exception:
pass
return False
def has_toml_section(start, filename, section):
"""True if the nearest ancestor `filename` contains `section`."""
d = find_up(start, [filename])
if not d:
return False
try:
with open(os.path.join(d, filename), errors="ignore") as fh:
return section in fh.read()
except Exception:
return False
def stylua_cmd(path):
exe = os.path.expanduser("~/.local/share/nvim/mason/bin/stylua")
if not os.access(exe, os.X_OK):
exe = shutil.which("stylua")
if exe and find_up(path, [".stylua.toml", "stylua.toml"]):
return [exe, path]
return None
def ruff_cmd(path):
exe = shutil.which("ruff")
if exe and (find_up(path, ["ruff.toml", ".ruff.toml"])
or has_toml_section(path, "pyproject.toml", "[tool.ruff")):
return [exe, "format", path]
return None
_PRETTIER_CFGS = [
".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml",
".prettierrc.json5", ".prettierrc.js", ".prettierrc.cjs", ".prettierrc.mjs",
".prettierrc.toml", "prettier.config.js", "prettier.config.cjs",
"prettier.config.mjs",
]
def prettier_cmd(path):
exe = shutil.which("prettier")
if exe and find_up(path, _PRETTIER_CFGS):
return [exe, "--write", path]
return None
def gofmt_cmd(path):
exe = shutil.which("gofmt")
if exe and find_up(path, ["go.mod"]): # one canonical style
return [exe, "-w", path]
return None
def rustfmt_cmd(path):
exe = shutil.which("rustfmt")
if exe and find_up(path, ["Cargo.toml", "rustfmt.toml", ".rustfmt.toml"]):
return [exe, path]
return None
# Shell and fish are opt-in too, gated on an .editorconfig SECTION that matches the file
# (shfmt reads .editorconfig natively for its settings, so the marker and the tool agree).
# "One canonical style" turned out not to mean "the style the project uses": 3 of ~/.dots's
# 25 fish files are not fish_indent-clean, so running these on sight rewrote whole files and
# buried a 40-line change in a 200-line diff. ~/.dots opts its shell in via
# `[{*.sh,dotsync,dotpub}]` while its fish files stay hand-formatted — existence of the
# .editorconfig alone must not turn either formatter on.
# Neovim agrees: conform.nvim there lists lua/css/html/ts/js only — never sh or fish.
def fish_cmd(path):
exe = shutil.which("fish_indent")
if exe and editorconfig_covers(path):
return [exe, "-w", path]
return None
def shfmt_cmd(path):
exe = shutil.which("shfmt")
if exe and editorconfig_covers(path):
return [exe, "-w", path]
return None
def taplo_cmd(path):
exe = shutil.which("taplo")
# opt-in: TOML reflow/align is intrusive, so only where the project asked.
if exe and find_up(path, ["taplo.toml", ".taplo.toml"]):
return [exe, "format", path]
return None
HANDLERS = {
".lua": stylua_cmd,
".py": ruff_cmd,
".js": prettier_cmd, ".jsx": prettier_cmd, ".mjs": prettier_cmd,
".cjs": prettier_cmd, ".ts": prettier_cmd, ".tsx": prettier_cmd,
".css": prettier_cmd, ".scss": prettier_cmd, ".less": prettier_cmd,
".html": prettier_cmd, ".vue": prettier_cmd, ".json": prettier_cmd,
".md": prettier_cmd, ".yaml": prettier_cmd, ".yml": prettier_cmd,
".go": gofmt_cmd,
".rs": rustfmt_cmd,
".fish": fish_cmd,
".sh": shfmt_cmd, ".bash": shfmt_cmd,
".toml": taplo_cmd,
}
RECENT_SECS = 30 # a Bash edit is "ours" if the file changed this recently
_EXT_ALT = "|".join(re.escape(e[1:]) for e in HANDLERS)
_PATHISH = re.compile(r"[\w.~/@+-]+\.(?:" + _EXT_ALT + r")\b")
def format_one(path):
if not path or not os.path.isfile(path):
return
# Resolve symlinks before walking for markers: deployed dotfiles get edited via
# their ~/.config/... links, but the opt-in configs live beside the real file in
# the repo — a lexical walk from the link's path would never find them.
path = os.path.realpath(path)
handler = HANDLERS.get(os.path.splitext(path)[1].lower())
if not handler:
return
cmd = handler(path)
if not cmd:
return
try:
subprocess.run(cmd, timeout=15, capture_output=True)
except Exception:
pass
def recent_paths_in_command(command, cwd):
"""Files a shell command plausibly just wrote: path-like tokens with a handled
extension, resolved against the tool's cwd, that exist and changed within RECENT_SECS.
Unchanged mentions (the source of a `cp`, a file merely grepped) fail the mtime gate."""
now = time.time()
seen, out = set(), []
for tok in _PATHISH.findall(command or ""):
p = os.path.expanduser(tok)
if not os.path.isabs(p):
p = os.path.join(cwd, p)
p = os.path.normpath(p)
if p in seen:
continue
seen.add(p)
try:
if os.path.isfile(p) and now - os.path.getmtime(p) <= RECENT_SECS:
out.append(p)
except OSError:
pass
return out
def main():
try:
data = json.load(sys.stdin)
except Exception:
return
ti = data.get("tool_input") or {}
tr = data.get("tool_response") or {}
if data.get("tool_name") == "Bash":
cwd = data.get("cwd") or os.getcwd()
for p in recent_paths_in_command(ti.get("command"), cwd):
format_one(p)
return
format_one(ti.get("file_path") or tr.get("filePath") or "")
if __name__ == "__main__":
main()
+223
View File
@@ -0,0 +1,223 @@
#!/usr/bin/env bash
# Regression matrix for git-guard.py: `bash ~/.claude/hooks/git-guard-test.sh` (exit 1 on mismatch).
# Kept as a file on purpose: typed inline, the very commands under test would trip the live hook.
G="$(dirname "$(readlink -f "$0")")/git-guard.py"
fail=0
# No exempt repository for the rows that do not ask for one, whatever this host's ~/.claude/git-guard-exempt says.
export GIT_GUARD_EXEMPT=""
# `git reset <one arg>` is allowed only for an existing path: give the matrix one to point at.
tmp=$(mktemp -d) && cd "$tmp" && touch existing.py
trap 'rm -rf "$tmp"' EXIT
run() {
printf '%s' "{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":$(python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$2")}}" | python3 "$G" 2>/dev/null
rc=$?
got=allow
[ $rc -eq 2 ] && got=block
[ "$got" = "$1" ] && mark=ok || {
mark=MISMATCH
fail=1
}
printf '%-8s %-6s %-6s %s\n' "$mark" "$1" "$got" "$(printf '%s' "$2" | head -1)"
}
echo "--- must block: commits / history ---"
run block 'git push'
run block 'git -C /home/coja/.dots push origin main'
run block 'git -c user.name=x commit -m fix'
run block '/usr/bin/git push'
run block 'env GIT_DIR=.git git push'
run block 'timeout 5 git push'
run block 'sudo -u me git push'
run block 'cd /tmp && git push'
run block 'git status; git commit -am wip'
run block 'x=1; git push'
run block 'git push 2>&1 | tee log'
run block "sh -c 'git push origin HEAD'"
run block 'eval "git push"'
run block 'git -C $(pwd) push'
run block 'echo "$(git push)"'
run block 'git --git-dir=/x/.git --work-tree=/x push'
run block 'git commit -m "fix: grep pattern; not a command"'
run block 'git revert HEAD'
run block 'git cherry-pick abc123'
run block 'git rebase -i HEAD~3'
run block 'git rebase --interactive main'
run block 'git -C . rebase -i --autosquash main'
run block 'git rebase --autostash origin/main'
run block 'git -c rebase.autoStash=true rebase main'
run block 'git merge feature'
run block 'git merge --no-ff feature'
echo "--- must block: discards working-tree changes ---"
run block 'git reset --hard HEAD~1'
run block 'git reset HEAD~1 --hard'
run block 'git reset --soft HEAD~1'
run block 'git reset --keep HEAD~2'
run block 'git reset --merge'
run block 'git reset'
run block 'git reset -q'
run block 'git reset HEAD'
run block 'git reset HEAD~1'
run block 'git reset abc1234'
run block 'git reset 0123456789abcdef0123456789abcdef01234567'
run block 'git reset origin/main'
run block 'git reset @{u}'
run block 'git restore --staged .'
run block 'git restore --staged :/'
run block 'git clean -fd'
run block 'git -C . clean -n'
run block 'git restore file.py'
run block 'git restore --staged --worktree file.py'
run block 'git restore -W file.py'
run block 'git checkout -- .'
run block 'git checkout -- file.py'
run block 'git checkout HEAD -- file.py'
run block 'git checkout .'
run block 'git checkout -f main'
run block 'git stash drop'
run block 'git stash pop'
run block 'git stash clear'
run block 'git branch -D feature'
run block 'git branch -f main HEAD~1'
run block 'git branch -M main trunk'
echo "--- must block: gh pr write ops (create only with --head, edit only title/body) ---"
run block 'gh pr merge 12 --squash'
run block 'gh pr close 4'
run block 'gh -R o/r pr create --fill'
run block 'gh pr create --title x --body y'
run block 'gh pr create --dry-run --fill'
run block 'gh pr edit 3 --add-reviewer bob'
run block 'gh pr edit 3 --title x --base main'
run block 'gh pr edit --add-label=bug 3'
run block 'gh pr edit 3 -b y -m v2'
echo "--- must allow ---"
run allow 'git status'
run allow 'git log -1 --oneline'
run allow 'git diff --cached --stat'
run allow 'git add -A common/.config/claude'
run allow 'git rev-parse --git-path CLAUDE_COMMIT_MSG'
run allow 'git -c core.pager=cat log -3'
run allow 'git reset -- file.txt'
run allow 'git reset HEAD file.txt'
run allow 'git reset HEAD existing.py other.py'
run allow 'git reset existing.py'
run allow 'git reset -p'
run allow 'git reset -- .'
run allow 'git restore --staged existing.py'
run allow 'git restore --staged file.py'
run allow 'git restore -S file.py'
run allow 'git checkout main'
run allow 'git checkout -b feature'
run allow 'git switch main'
run allow 'git merge --abort'
run allow 'git rebase main'
run allow 'git rebase origin/main'
run allow 'git rebase -Xtheirs main'
run allow 'git rebase --continue'
run allow 'git rebase --abort'
run allow 'git -c core.editor=true rebase --continue'
run allow 'GIT_EDITOR=true git rebase --continue'
run allow 'git stash'
run allow 'git stash list'
run allow 'git stash push -m wip'
run allow 'git stash show -p'
run allow 'git branch -d merged-branch'
run allow 'git branch --list'
run allow 'git branch -vv'
run allow 'git commit-tree HEAD^{tree} -m x'
run allow 'git worktree list'
run allow 'grep -rn "git push" README.md'
run allow 'grep -n "foo; git commit" file'
run allow "echo 'git push'"
run allow 'echo "run git push"'
run allow "cat > README.md <<'EOF'
Deploy with:
git status; git commit -am x; git push origin main
EOF
echo written"
run allow 'python3 - <<EOF
print("git commit is manual")
EOF'
run allow 'gh pr view 12 --json updatedAt'
run allow 'gh pr create --head feat --title x --body y'
run allow 'gh pr create -H feat --fill'
run allow 'gh -R o/r pr create --head=feat --fill'
run allow 'gh pr create --help'
run allow 'gh pr edit 3 --title x'
run allow 'gh pr edit 3 -t x -b "- item --base"'
run allow 'gh pr edit --body-file - 12'
run allow 'gh pr edit 12 -F body.md --repo o/r'
run allow 'gh pr edit 12 --title=x -bBody'
run allow 'gh workflow run ci.yml --ref main'
run allow 'gh run rerun 123 --failed'
run allow 'gh api graphql -f query="mutation{...}"'
run allow 'gh auth status'
run allow 'ls -la HEAD#x; git status'
run allow 'git log --grep="git push" -5'
run allow '~/.config/git/claude-commit-msg list'
echo "--- exempt repo (GIT_GUARD_EXEMPT = a scratch repo; commit and merge pass there, nothing else) ---"
# runin <expect> <cwd> <command>: the hook input carries the session's cwd, as Claude Code sends it.
R=$tmp/repo
WT=$tmp/repo-wt
git init -q "$R" && git -C "$R" -c user.name=t -c user.email=t@t commit -q --allow-empty -m init \
&& git -C "$R" worktree add -q "$WT" 2>/dev/null && mkdir -p "$R/sub" && git init -q "$tmp/other"
runin() {
printf '%s' "$(python3 -c 'import json,sys; print(json.dumps({"tool_name":"Bash","tool_input":{"command":sys.argv[1]},"cwd":sys.argv[2]}))' "$3" "$2")" | GIT_GUARD_EXEMPT=$R python3 "$G" 2>/dev/null
rc=$?
got=allow
[ $rc -eq 2 ] && got=block
[ "$got" = "$1" ] && mark=ok || {
mark=MISMATCH
fail=1
}
printf '%-8s %-6s %-6s [%s] %s\n' "$mark" "$1" "$got" "${2#"$tmp"/}" "$(printf '%s' "$3" | head -1)"
}
runin allow "$R" 'git commit -m "docs: x"'
runin allow "$R" 'git commit -m x -- docs/usage.md'
runin allow "$R" 'git commit -m"fix a bug"'
runin allow "$R" 'git commit -m "-a is not the flag here"'
runin allow "$R" 'git commit --allow-empty -m x'
runin allow "$R/sub" 'git commit -m x'
runin allow "$R" 'git merge --ff-only feature'
runin allow "$R" 'git merge --no-ff feature'
runin allow "$WT" 'git commit -m x'
runin allow "$tmp" "git -C $WT commit -m x"
runin allow "$tmp" "cd $R && git commit -m x"
runin allow "$tmp" 'cd repo && git commit -m x'
runin allow "$tmp" "cd $WT; git status; git merge main"
runin allow "$R" "sh -c 'git commit -m x'"
runin block "$R" 'git push'
runin block "$R" 'git commit --amend --no-edit'
runin block "$R" 'git commit -am wip'
runin block "$R" 'git commit -qa -m wip'
runin block "$R" 'git commit --all -m wip'
runin block "$R" 'git rebase -i main'
runin block "$R" 'git cherry-pick abc123'
runin block "$R" 'git revert HEAD'
runin block "$R" 'git reset --hard HEAD~1'
runin block "$R" 'git checkout -- file.py'
runin block "$R" 'GIT_DIR=/x/.git git commit -m x'
runin block "$R" 'env GIT_WORK_TREE=/x git commit -m x'
runin block "$R" 'git --git-dir=/x/.git commit -m x'
runin block "$R" 'git -C /tmp commit -m x'
runin block "$R" 'git -C $(mktemp -d) commit -m x'
runin block "$tmp" "cd $R && cd /tmp && git commit -m x"
runin block "$R" 'cd - && git commit -m x'
runin block "$R" 'cd $HOME && git commit -m x'
runin block "$R" 'pushd /tmp && git commit -m x'
runin block "$tmp" 'git commit -m x'
runin block "$tmp/other" 'git commit -m x'
runin block "$tmp" "git -C $tmp/other merge x"
echo "--- fail-open ---"
printf '%s' '{"tool_name":"Edit","tool_input":{"command":"git push"}}' | python3 "$G"
[ $? -eq 0 ] && echo "ok non-Bash tool ignored" || {
echo "MISMATCH non-Bash"
fail=1
}
printf 'not json' | python3 "$G"
[ $? -eq 0 ] && echo "ok garbage stdin passes" || {
echo "MISMATCH garbage"
fail=1
}
[ $fail -eq 0 ] && echo "GIT-GUARD MATRIX: all ok" || {
echo "GIT-GUARD MATRIX: mismatches above"
exit 1
}
+369
View File
@@ -0,0 +1,369 @@
#!/usr/bin/env python3
"""PreToolUse hook (Bash): enforce the no-commit / no-push contract structurally.
settings.json's deny rules (`Bash(git push:*)`, ...) match a literal *prefix* of the
command text, so `git -C . push`, `git -c k=v commit`, `/usr/bin/git push`,
`env X=1 git push`, `timeout 5 git push` and `sh -c 'git push'` all slip past them.
This hook parses each shell segment instead: finds the git/gh token wherever it sits,
skips git's global options (`-C dir`, `-c k=v`, `--git-dir=...`) and blocks
git commit | push | revert | cherry-pick | merge (not --abort/--quit/--continue)
git rebase -i / --interactive / --autostash
git clean | reset (any form that moves HEAD or unstages everything; `reset -- <paths>`,
`reset HEAD <path>` and `reset <existing path>` are fine) | restore <paths> (--staged
alone is fine, except `--staged .` / `:/`) | checkout -- / checkout . / -f
git stash drop | pop | clear git branch -D / -f / -M
gh pr merge | close | create without --head | edit beyond --title/--body
i.e. anything that commits, rewrites history, or discards working-tree changes -- the last
group matters most with several sessions sharing one checkout. Mirrors pi's permission-gate.
On GitHub Claude may open a PR (settings.json asks first) and retitle / redescribe one, nothing
more: `gh pr create` must name its branch with --head, without which gh pushes it itself (even
under --dry-run), and `gh pr edit` must not touch reviewers, labels, base or the like.
A plain `git rebase` (and its --continue / --abort) passes: Claude rebases and fixes the
conflicts when the user asks (global CLAUDE.md), and settings.json asks before each one, as
pi's gate does. `-i` stays blocked (the squash/reword tool, and it needs an editor), and so
does --autostash: it stashes and re-pops other sessions' uncommitted edits, where a plain
rebase refuses to start on a dirty tree.
Exit 2 + one stderr line = the call is blocked and Claude reads the reason (stage and
stop; /commit-msg drafts the message). Mirrors pi's permission-gate.ts.
Tokenizing is quote-aware first (shlex in punctuation mode), and only then split at the
separators `;`, `|`, `&&`, `(`, `)`: a quoted word that merely *contains* a separator and a
git verb (a grep pattern, a commit message) stays one word and is not a command. `$(...)`
and backtick bodies are scanned on their own and then collapsed, so `git -C $(pwd) push`
still parses as a push. `sh -c '...'` and `eval` bodies recurse.
Deliberate gaps: heredoc bodies are skipped -- they are file/script *contents*, and a
README that documents pushing must stay writable -- so a script piped in through a heredoc
is not inspected. Aliases (`git ci`) are not expanded. The deny list, the auto-mode
classifier and the global CLAUDE.md still cover those; this is the belt for the prefix
rules' braces. Fails open: any parse error lets the command through (exit 0).
Exempt repositories (one main checkout per line in ~/.claude/git-guard-exempt, host-local and
outside the dots repo on purpose: it names projects): there `git commit` and `git merge` pass
-- the user's decision for repos where Claude commits and merges itself. The repo is the one the call
actually targets: the hook input's `cwd`, moved by every `cd` before it in the command and by
`git -C`, resolved to its main checkout (so its worktrees count). Anything that hides the
target (`cd -`, `cd $VAR`, a substitution, `--git-dir`, `GIT_DIR=`) is judged not exempt.
`commit --amend` and `commit -a`/`--all` stay blocked there (they rewrite the last commit of
a shared checkout, or sweep other sessions' edits in), as do push, `rebase -i` and the discard
group. Known gap: a `cd` inside `( ... )` leaks into the commands after the parenthesis.
"""
import json
import os
import re
import shlex
import subprocess
import sys
GIT_BLOCK = {"commit", "push", "clean", "revert", "cherry-pick"}
MERGE_OK = {"--abort", "--quit", "--continue"}
REBASE_BLOCK = {"-i", "--interactive", "--autostash"}
STASH_BLOCK = {"drop", "pop", "clear"}
BRANCH_FORCE = {"-D", "-f", "--force", "-M"}
RESET_MODES = {"--hard", "--soft", "--merge", "--keep"}
UNSTAGE_ALL = {".", ":/", "*", ":"}
_HEX = re.compile(r"^[0-9a-f]{7,40}$")
def looks_like_ref(a):
return (a in ("HEAD", "ORIG_HEAD", "FETCH_HEAD", "MERGE_HEAD") or a.startswith("refs/")
or "~" in a or "^" in a or "@{" in a or bool(_HEX.match(a)))
GH_PR_BLOCK = {"merge", "close"}
# `gh pr edit` may only retitle and redescribe; these take their value as the next word (or as
# `--title=x` / `-tx`).
GH_EDIT_OK = {"-t", "--title", "-b", "--body", "-F", "--body-file", "-R", "--repo"}
# Repositories (main checkouts; their worktrees count) where Claude commits and merges itself:
# one path per line, `#` comments; a missing file exempts nothing. GIT_GUARD_EXEMPT
# (colon-separated) replaces the file for the test matrix; it is read from the hook's own
# environment (Claude Code's), which a prefix on the checked command cannot reach.
EXEMPT_FILE = "~/.claude/git-guard-exempt"
EXEMPT_VERBS = {"commit", "merge"}
# `git commit` options whose value is the next word (or, for the short ones, the rest of the word).
COMMIT_ARG_SHORT = set("mFCct")
COMMIT_ARG_LONG = {"--message", "--file", "--author", "--date", "--reuse-message", "--reedit-message",
"--fixup", "--squash", "--template", "--trailer", "--cleanup", "--pathspec-from-file"}
# global options that take a *separate* argument; the `--opt=value` spelling is one token.
GIT_OPT_ARG = {"-C", "-c", "--git-dir", "--work-tree", "--exec-path", "--namespace",
"--super-prefix", "--config-env"}
GH_OPT_ARG = {"-R", "--repo"}
SHELLS = {"sh", "bash", "dash", "zsh", "ksh", "fish"}
# `<<'EOF' ... EOF` / `<<-EOF ... EOF`: drop the body, keep the command around it.
_HEREDOC = re.compile(r"<<-?\s*(['\"]?)(\w+)\1[^\n]*\n.*?\n[ \t]*\2[ \t]*(?=\n|$)", re.S)
# innermost `$(...)` / `...` command substitutions (peeled repeatedly for nesting).
_SUBST = re.compile(r"\$\(([^()]*)\)|`([^`]*)`")
# tokens that end one simple command and start the next.
_SEP = {";", ";;", "|", "||", "|&", "&", "&&", "(", ")"}
def _skip_opts(args, with_arg):
j = 0
while j < len(args) and args[j].startswith("-"):
j += 2 if args[j] in with_arg else 1
return j
def exempt_repos():
env = os.environ.get("GIT_GUARD_EXEMPT")
if env is not None:
paths = env.split(":")
else:
try:
with open(os.path.expanduser(EXEMPT_FILE)) as f:
paths = [ln.split("#", 1)[0].strip() for ln in f]
except OSError:
return set()
return {os.path.realpath(os.path.expanduser(p)) for p in paths if p}
def main_checkout(d):
"""The main checkout of the repository `d` lies in (a worktree resolves to it), or None."""
try:
out = subprocess.run(["git", "-C", d, "rev-parse", "--path-format=absolute", "--git-common-dir"],
capture_output=True, text=True, timeout=3)
except (OSError, subprocess.SubprocessError):
return None
common = out.stdout.strip().rstrip("/")
if out.returncode != 0 or not common:
return None
return os.path.realpath(os.path.dirname(common))
def in_exempt_repo(opts, cwd, pre):
"""Whether a git call with global options `opts`, run from `cwd` after the words `pre` of
its own command (`env X=1`, ...), targets an exempt repository."""
exempt = exempt_repos()
if not exempt or cwd is None or any(t.startswith(("GIT_DIR=", "GIT_WORK_TREE=", "GIT_COMMON_DIR="))
for t in pre):
return False
d, j = cwd, 0
while j < len(opts):
a = opts[j]
if a in ("--git-dir", "--work-tree") or a.startswith(("--git-dir=", "--work-tree=")):
return False
if a == "-C":
if j + 1 >= len(opts) or "SUBST" in opts[j + 1] or "$" in opts[j + 1]:
return False
d = os.path.join(d, os.path.expanduser(opts[j + 1]))
j += 2 if a in GIT_OPT_ARG else 1
return main_checkout(d) in exempt
def commit_rewrites_or_sweeps(rest):
"""`commit --amend` (rewrites the last commit) or `-a`/`--all` (takes in every modified
tracked file, other sessions' edits included)."""
skip = False
for a in rest:
if skip:
skip = False
continue
if a == "--":
break
if a in ("--amend", "--all"):
return True
if a in COMMIT_ARG_LONG:
skip = True
elif a.startswith("-") and not a.startswith("--"):
for k, ch in enumerate(a[1:], 1):
if ch == "a":
return True
if ch in COMMIT_ARG_SHORT:
skip = k == len(a) - 1 # the value is the next word
break
return False
def change_dir(cwd, args):
"""Where `cd args` leaves the shell started in `cwd`; None when that cannot be told."""
args = [a for a in args if a not in ("-L", "-P", "--")]
if not args:
return os.path.expanduser("~")
t = args[0]
if t == "-" or "SUBST" in t or "$" in t or (cwd is None and not t.startswith(("/", "~"))):
return None
return os.path.normpath(os.path.join(cwd or "/", os.path.expanduser(t)))
def git_reason(args, cwd=None, pre=()):
j = _skip_opts(args, GIT_OPT_ARG)
if j >= len(args):
return None
sub, rest = args[j], args[j + 1:]
if (sub in EXEMPT_VERBS and not (sub == "commit" and commit_rewrites_or_sweeps(rest))
and in_exempt_repo(args[:j], cwd, pre)):
return None
if sub in GIT_BLOCK:
return f"git {sub}"
if sub == "rebase":
flag = next((a for a in rest if a in REBASE_BLOCK), None)
if flag == "--autostash" or any(o.lower().startswith("rebase.autostash") for o in args[:j]):
return "git rebase --autostash (stashes other sessions' uncommitted edits)"
return f"git rebase {flag} (interactive history rewrite)" if flag else None
if sub == "reset":
opts = [a for a in rest if a.startswith("-") and a != "--"]
if RESET_MODES & set(opts):
return "git reset --hard/--soft/--merge/--keep (moves HEAD)"
if "-p" in opts or "--patch" in opts or "--" in rest:
return None # interactive, or the explicit path form
pos = [a for a in rest if not a.startswith("-")]
if not pos or pos == ["HEAD"]:
return "git reset (unstages everything, other sessions' rounds included)"
if len(pos) == 1 and (looks_like_ref(pos[0]) or not os.path.exists(pos[0])):
return "git reset <commit> (moves HEAD)"
return None # `reset HEAD <paths>` / `reset <paths>`
if sub == "merge" and not (MERGE_OK & set(rest)):
return "git merge (creates a commit)"
if sub == "restore":
staged = any(a in ("--staged", "-S") for a in rest)
worktree = any(a in ("--worktree", "-W") for a in rest)
if not staged or worktree:
return "git restore (discards working-tree changes)"
if UNSTAGE_ALL & {a for a in rest if not a.startswith("-")}:
return "git restore --staged . (unstages everything, other sessions' rounds included)"
if sub == "checkout" and ("--" in rest or "." in rest or "-f" in rest or "--force" in rest):
return "git checkout -- <paths> (discards working-tree changes)"
if sub == "stash" and rest and rest[0] in STASH_BLOCK:
return f"git stash {rest[0]}"
if sub == "branch" and BRANCH_FORCE & set(rest):
return "git branch -D/-f (force-deletes or force-moves a branch)"
return None
def gh_edit_extra(rest):
"""The first `gh pr edit` option that is neither the title nor the body, else None."""
k = 0
while k < len(rest):
a = rest[k]
if a == "--":
break
name = a.split("=", 1)[0]
if name in GH_EDIT_OK:
k += 2 if name == a else 1 # skip the value, which may well start with `-`
continue
if a.startswith("-") and not (a[:2] in GH_EDIT_OK and not a.startswith("--")):
return a
k += 1
return None
def gh_reason(args):
j = _skip_opts(args, GH_OPT_ARG)
if j >= len(args) or args[j] != "pr":
return None
rest = args[j + 1:]
k = _skip_opts(rest, GH_OPT_ARG)
if k >= len(rest) or "--help" in rest:
return None
sub, rest = rest[k], rest[k + 1:]
if sub in GH_PR_BLOCK:
return f"gh pr {sub}"
if sub == "create" and not any(a in ("-H", "--head") or a.startswith("--head=")
or (a.startswith("-H") and not a.startswith("--")) for a in rest):
return "gh pr create without --head: gh would push the branch itself"
if sub == "edit":
extra = gh_edit_extra(rest)
if extra:
return f"gh pr edit {extra.split('=', 1)[0]}: only --title / --body edits are allowed"
return None
def tokenize(text):
"""Quote-aware shell words; the separator characters come out as their own tokens
(shlex punctuation mode). Comment handling is off: a `#` mid-word must not swallow
the rest of the line."""
lex = shlex.shlex(text, posix=True, punctuation_chars=True)
lex.whitespace_split = True
lex.commenters = ""
try:
return list(lex)
except ValueError: # unbalanced quotes: best effort
return text.split()
def segments(toks):
seg = []
for t in toks:
if t in _SEP:
if seg:
yield seg
seg = []
else:
seg.append(t)
if seg:
yield seg
def scan(text, depth=0, cwd=None):
"""Reason string for the first blocked invocation in `text` (run from `cwd`), else None."""
if depth > 4:
return None
text = _HEREDOC.sub(" ", text)
# command substitutions: scan each body on its own, then collapse it to a plain word so
# the enclosing command still parses (`git -C $(pwd) push` -> `git -C SUBST push`).
bodies = []
def _grab(m):
bodies.append(m.group(1) if m.group(1) is not None else m.group(2))
return " SUBST "
prev = None
while prev != text:
prev, text = text, _SUBST.sub(_grab, text)
for body in bodies:
r = scan(body, depth + 1, cwd)
if r:
return r
for toks in segments(tokenize(text)):
if toks[0] == "cd":
cwd = change_dir(cwd, toks[1:])
continue
if toks[0] in ("pushd", "popd"):
cwd = None
continue
for i, tok in enumerate(toks):
base = os.path.basename(tok)
r = None
if base == "git":
r = git_reason(toks[i + 1:], cwd, toks[:i])
elif base == "gh":
r = gh_reason(toks[i + 1:])
elif base == "eval":
r = scan(" ".join(toks[i + 1:]), depth + 1, cwd)
elif base in SHELLS and "-c" in toks[i + 1:]:
k = toks.index("-c", i + 1) # `sh -c '<cmd>'`: the real command is one word
if k + 1 < len(toks):
r = scan(toks[k + 1], depth + 1, cwd)
if r:
return r
return None
def main():
try:
data = json.load(sys.stdin)
if data.get("tool_name", "Bash") != "Bash":
return
cmd = (data.get("tool_input") or {}).get("command") or ""
reason = scan(cmd, 0, data.get("cwd") or os.getcwd()) if cmd else None
except Exception:
return # fail open: the deny list still applies
if reason:
short = cmd.strip().splitlines()[0]
short = short if len(short) <= 80 else short[:77] + "..."
hint = ("On a PR Claude reads, opens one when asked (with --head <pushed branch>) and edits its "
"--title / --body; pushing, merging, closing and every other edit are the user's."
if reason.startswith("gh ") else
"Rebase with a plain `git rebase` on a clean tree, and only when the user asked; if the "
"tree holds other sessions' edits, tell the user instead of stashing them."
if reason.startswith("git rebase") else
"The user commits, pushes and merges manually (global CLAUDE.md): stage and stop, "
"and draft the message with /commit-msg.")
sys.stderr.write(f"git-guard: blocked `{short}` ({reason}). {hint}\n")
sys.exit(2)
if __name__ == "__main__":
main()
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""UserPromptExpansion hook: run a skill TUI-side, without a model turn.
Custom slash commands in Claude Code are prompts -- typing `/x` expands skills/x/SKILL.md
and sends it to the model. For a command that is really just a local action (flip a
setting, print a state) that round trip is waste. This hook gives any skill a TUI-side
implementation: if `~/.claude/skills/<command_name>/local.py` exists, it is executed with
the command's arguments, its output is shown to you, and the expansion is blocked (exit 2),
so nothing reaches the model. Skills without a local.py expand as usual (exit 0).
Order matters: the hook fires AFTER the skill body has been expanded, so any `!` inline
commands in that SKILL.md have already run by the time this executes. A skill with a
local.py must therefore not also apply its action via `!` -- it would happen twice.
Input (stdin JSON): command_name, command_args (list), expanded_prompt, cwd, ...
Fails open: any error here means exit 0 and the normal expansion goes ahead.
"""
import json
import os
import subprocess
import sys
def main():
try:
data = json.load(sys.stdin)
name = data.get("command_name") or ""
args = data.get("command_args") or []
if isinstance(args, str):
args = args.split()
if not name or "/" in name or name.startswith("."):
return
script = os.path.expanduser(f"~/.claude/skills/{name}/local.py")
if not os.path.isfile(script):
return
r = subprocess.run(
[sys.executable, script, *[str(a) for a in args]],
capture_output=True, text=True, timeout=20, cwd=data.get("cwd") or None,
)
except Exception:
return # fail open: let the skill expand normally
out = (r.stdout or "") + (r.stderr or "")
sys.stderr.write(out.rstrip("\n") + f"\n[/{name}: handled TUI-side by skills/{name}/local.py, no model turn]\n")
sys.exit(2)
if __name__ == "__main__":
main()
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Notification hook: a desktop notification when Claude is waiting on you.
settings.json wires it to `idle_prompt|permission_prompt` (the Notification matcher is the
`notification_type`). Push notifications are off in this setup, so this is the local
counterpart of pi's notify.ts. Uses notify-send where present (the Wayland/GUI hosts) and
silently no-ops on a headless box or without a session bus. Payload fields are read
defensively -- the docs do not pin the Notification input schema: `message`, `title`,
`notification_type`, `cwd`.
"""
import json
import os
import shutil
import subprocess
import sys
TITLES = {
"idle_prompt": "Claude Code is waiting for you",
"permission_prompt": "Claude Code needs a permission",
}
def main():
try:
data = json.load(sys.stdin)
except Exception:
return
exe = shutil.which("notify-send")
if not exe:
return
kind = data.get("notification_type") or "notification"
title = data.get("title") or TITLES.get(kind, "Claude Code")
body = (data.get("message") or "").strip() or kind
cwd = data.get("cwd") or ""
if cwd:
home = os.path.expanduser("~")
body += "\n" + (("~" + cwd[len(home):]) if cwd.startswith(home) else cwd)
try:
subprocess.run(
[exe, "--app-name=Claude Code", "--urgency=normal", "--expire-time=8000",
# same tag -> a newer notification replaces the previous one instead of stacking
f"--hint=string:x-canonical-private-synchronous:claude-code-{kind}",
title, body],
timeout=5, capture_output=True,
)
except Exception:
pass
if __name__ == "__main__":
main()
+49
View File
@@ -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"
}
}
]
}
+114
View File
@@ -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
+274
View File
@@ -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
View File
@@ -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()
+930
View File
@@ -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()
+108
View File
@@ -0,0 +1,108 @@
{
"$schema": "https://github.com/fastfetch-cli/fastfetch/raw/dev/doc/json_schema.json",
"logo": {
"source": "$(find \"${XDG_CONFIG_HOME:-$HOME/.config}/fastfetch/pngs/\" -name \"*.png\" -xtype f | shuf -n 1)",
"height": 18
},
"display": {
"separator": " : "
},
"modules": [
{
"type": "custom",
"format": "\u001b[36m "
},
{
"type": "custom",
"format": "┌──────────────────────────────────────────┐"
},
{
"type": "os",
"key": "  OS",
"keyColor": "red"
},
{
"type": "kernel",
"key": "  Kernel",
"keyColor": "red"
},
{
"type": "packages",
"key": "  Packages",
"keyColor": "green"
},
{
"type": "display",
"key": "  Display",
"keyColor": "green"
},
{
"type": "wm",
"key": "  WM",
"keyColor": "yellow"
},
{
"type": "terminal",
"key": "  Terminal",
"keyColor": "yellow"
},
{
"type": "custom",
"format": "└──────────────────────────────────────────┘"
},
"break",
{
"type": "title",
"key": " "
},
{
"type": "custom",
"format": "┌──────────────────────────────────────────┐"
},
{
"type": "cpu",
"format": "{1}",
"key": "  CPU",
"keyColor": "blue"
},
{
"type": "gpu",
"format": "{2}",
"key": "  GPU",
"keyColor": "blue"
},
{
"type": "gpu",
"format": "{3}",
"key": "  GPU Driver",
"keyColor": "magenta"
},
{
"type": "memory",
"key": " ﬙ Memory",
"keyColor": "magenta"
},
{
"type": "command",
"key": " 󱦟 OS Age ",
"keyColor": "31",
"text": "birth_install=$(stat -c %W /); current=$(date +%s); time_progression=$((current - birth_install)); days_difference=$((time_progression / 86400)); echo $days_difference days"
},
{
"type": "uptime",
"key": " 󱫐 Uptime ",
"keyColor": "red"
},
{
"type": "custom",
"format": "└──────────────────────────────────────────┘"
},
{
"type": "colors",
"paddingLeft": 2,
"symbol": "circle"
},
"break"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

@@ -0,0 +1,5 @@
# Single positional arg: a branch name. It runs `git checkout -b`, so the new
# branch is typically a fresh name -- but offer existing branch names as a base
# to type from. Only suggest inside a git repo.
complete -c c2-worktree -x -n 'git rev-parse --is-inside-work-tree 2>/dev/null' \
-a '(git for-each-ref --format="%(refname:short)" refs/heads refs/remotes 2>/dev/null | string replace -r "^origin/" "")'
+3
View File
@@ -0,0 +1,3 @@
# `h <cmd> ...` shows a command's --help via bat, so complete it like a
# command line: first token = a command, rest = that command's own args.
complete -c h -x -a '(__fish_complete_subcommand)'
+16
View File
@@ -0,0 +1,16 @@
function __fish_pipx_complete
set -x _ARGCOMPLETE 1
set -x _ARGCOMPLETE_DFS \t
set -x _ARGCOMPLETE_IFS \n
set -x _ARGCOMPLETE_SUPPRESS_SPACE 1
set -x _ARGCOMPLETE_SHELL fish
set -x COMP_LINE (commandline -p)
set -x COMP_POINT (string length (commandline -cp))
set -x COMP_TYPE
if set -q _ARC_DEBUG
pipx 8>&1 9>&2 1>&9 2>&1
else
pipx 8>&1 9>&2 1>/dev/null 2>&1
end
end
complete --command pipx -f -a '(__fish_pipx_complete)'
@@ -0,0 +1,27 @@
# Mark the tmux window when a long shell command finishes, through the same
# ~/.config/tmux/scripts/agent-state.sh the coding agents use (tool tag "sh"):
# ✓ on exit 0, ! on failure — coloured when it happened while you were elsewhere, grey once
# visited, gone at the next command. Only commands longer than $agent_state_min_ms
# (default 30 s) count, and interactive programs are skipped: the agents mark themselves,
# and quitting a long nvim or lazygit session is not news. No-op outside tmux.
set -q agent_state_min_ms; or set -g agent_state_min_ms 30000
function __agent_state_preexec --on-event fish_preexec
set -q TMUX_PANE; or return
~/.config/tmux/scripts/agent-state.sh sh busy
end
function __agent_state_postexec --on-event fish_postexec
set -l st $status # first statement: anything before it would clobber the command's status
set -q TMUX_PANE; or return
test "$CMD_DURATION" -gt "$agent_state_min_ms"; or return
switch (string split -m1 ' ' -- $argv[1])[1]
case nvim vim vi less man lazygit ssh mosh tmux claude claudes pi opencode opencodes codex aichat htop btop top journalctl tail watch
return
end
if test $st -eq 0
~/.config/tmux/scripts/agent-state.sh sh done
else
~/.config/tmux/scripts/agent-state.sh sh error
end
end
@@ -0,0 +1,7 @@
if test -z "$SSH_ENV"
set -xg SSH_ENV $HOME/.ssh/environment
end
if not __ssh_agent_is_started
__ssh_agent_start
end
@@ -0,0 +1,3 @@
set --global fish_key_bindings fish_vi_key_bindings
set --erase --universal fish_key_bindings
@@ -0,0 +1,38 @@
set --global fish_color_autosuggestion 4D5566
set --global fish_color_cancel -r
set --global fish_color_command 39BAE6
set --global fish_color_comment 626A73
set --global fish_color_cwd 59C2FF
set --global fish_color_cwd_root red
set --global fish_color_end F29668
set --global fish_color_error FF3333
set --global fish_color_escape 95E6CB
set --global fish_color_history_current --bold
set --global fish_color_host normal
set --global fish_color_host_remote yellow
set --global fish_color_keyword 39BAE6
set --global fish_color_match F07178
set --global fish_color_normal B3B1AD
set --global fish_color_operator E6B450
set --global fish_color_option B3B1AD
set --global fish_color_param B3B1AD
set --global fish_color_quote C2D94C
set --global fish_color_redirection FFEE99
set --global fish_color_search_match --background=E6B450
set --global fish_color_selection --background=E6B450
set --global fish_color_status red
set --global fish_color_user brgreen
set --global fish_color_valid_path --underline
set --global fish_pager_color_background
set --global fish_pager_color_completion normal
set --global fish_pager_color_description B3A06D yellow
set --global fish_pager_color_prefix normal --bold --underline
set --global fish_pager_color_progress brwhite --background=cyan
set --global fish_pager_color_secondary_background
set --global fish_pager_color_secondary_completion
set --global fish_pager_color_secondary_description
set --global fish_pager_color_secondary_prefix
set --global fish_pager_color_selected_background --background=E6B450
set --global fish_pager_color_selected_completion
set --global fish_pager_color_selected_description
set --global fish_pager_color_selected_prefix
+7
View File
@@ -0,0 +1,7 @@
# fnm — single init for all hosts (config.fish must NOT source fnm again:
# every `fnm env | source` mints a fresh multishell dir onto PATH).
# fnm may be pacman-installed (on PATH) or self-installed under ~/.local/share/fnm.
test -d "$HOME/.local/share/fnm"; and fish_add_path -g "$HOME/.local/share/fnm"
if command -q fnm
fnm env --use-on-cd --version-file-strategy local --shell fish | source
end
@@ -0,0 +1,20 @@
# Drop kitty's KITTY_PUBLIC_KEY from the shell environment.
#
# kitty generates a random 40-char base85 public key per instance and exports it
# to every child (kitty/child.py). It is only read on the password path of kitty
# remote control (kitty/remote_control.py: "Password usage requested but
# KITTY_PUBLIC_KEY environment variable is not available"), which needs
# allow_remote_control — not enabled here. `kitten ssh`, icat, clipboard and
# shell integration never touch it.
#
# Why bother: tools that inline the environment into generated code get corrupted
# when a value contains a String.replace replacement sequence. prettier's
# --experimental-cli inlines JSON.stringify(process.env) into its parallel worker
# and splices it with .replace(placeholder, bootloader); a `$` + backtick in the
# key expands to "everything before the match", injecting the worker's own source
# mid-string. Every file then fails with a bogus
# "SyntaxError: Unexpected identifier 'string'". Roughly a 1-in-185 chance per
# kitty launch, which is exactly as fun to debug as it sounds.
if set -q KITTY_PUBLIC_KEY
set -e KITTY_PUBLIC_KEY
end
+135
View File
@@ -0,0 +1,135 @@
## Shared fish config (all hosts). Host-specific bits live in host.fish (sourced at the end).
## Secrets (e.g. DUSKADIY_API_KEY) go in conf.d/secrets.fish, which is gitignored.
set -gx EDITOR nvim
set -gx PAGER less
set -gx QT_FONT_DPI 96
set -gx PI_SKIP_VERSION_CHECK 1
# opencode GPT/Codex OAuth overlay (~/.config/opencode/openai-gpt.jsonc). opencode 2.x ignores
# OPENCODE_CONFIG / OPENCODE_CONFIG_CONTENT, but it merges a second global file, opencode.jsonc.
# Link the overlay under that name only where `opencode auth login` stored an OpenAI credential,
# so other hosts don't get an unusable provider; drop our link again if the login goes away.
# (Alternative: ship the link from the host's dots overlay instead of this startup check.)
set -l _oc_auth ~/.local/share/opencode/auth.json
set -l _oc_link ~/.config/opencode/opencode.jsonc
if test -r $_oc_auth; and grep -q '"openai"' $_oc_auth
test -e $_oc_link; or ln -s openai-gpt.jsonc $_oc_link
else if test -L $_oc_link; and test (readlink $_oc_link) = openai-gpt.jsonc
rm $_oc_link
end
set -gx MANPAGER "nvim +Man!"
# fzf's built-in walker is the one search tool that ignores .ignore files, so point it at
# fd, which honours them. fd still hides dotfiles by default everywhere else — this only
# changes what fzf sees inside trees that opt in (e.g. ~/.dots/.ignore).
set -gx FZF_DEFAULT_COMMAND 'fd --type f --strip-cwd-prefix'
set -gx NEWT_COLORS 'root=black,black;window=black,black;border=white,black;listbox=white,black;label=blue,black;checkbox=red,black;title=green,black;button=white,red;actsellistbox=white,red;actlistbox=white,gray;compactbutton=white,gray;actcheckbox=white,blue;entry=lightgray,black;textbox=blue,black' # themes nmtui
# set -gx BAT_THEME "Catppuccin Mocha"
# PATH additions — global on purpose: scripts need these tools too.
# (fnm is initialized once in conf.d/fnm.fish — don't source it again here)
fish_add_path $HOME/.cargo/bin $HOME/.local/bin
# pnpm
set -gx PNPM_HOME "$HOME/.local/share/pnpm"
if not string match -q -- $PNPM_HOME $PATH
set -gx PATH "$PNPM_HOME" $PATH
end
# Everything below is for a human at a prompt. config.fish is sourced by EVERY fish —
# scripts and `fish -c` included — and zoxide's `--cmd cd` alias is unconditional: in a
# script, a failed `cd` would silently land in zoxide's best database match (exit 0)
# instead of erroring, and every script `cd` would pollute the database. Aliases/abbrs
# leak into scripts the same way (`ls` → eza, `mkdir` → `mkdir -p`, fzf previews …).
if status is-interactive
# Cursor / greeting
set -g fish_greeting
set -g fish_cursor_insert line
set -g fish_cursor_default block
set -g fish_cursor_visual underscore
# Misc
alias exti=exit
alias dmz="cat ~/.config/fish/dmz.txt"
alias nmatrix="neo-matrix -DS 3"
alias grep="grep --color=auto"
alias fzf="fzf --preview 'bat --color=always {}'"
alias fzff="fzf --multi --preview 'bat --style=numbers --color=always {}' | xargs -n 1 nvim"
abbr scrcpyz 'scrcpy -wSK -m 1920 --window-borderless --always-on-top --power-off-on-close --no-audio'
# Git
alias gti="git"
alias gs="git status -s"
alias gp="git pull"
alias gca="git add -p . && git commit"
alias gd="git diff --word-diff"
alias gl="git log --graph --show-signature"
alias glog="git log --all --decorate --oneline --color --graph"
alias gla="git log --all --decorate --oneline"
alias gls="serie"
alias gm="git merge"
# List directory
alias ls='eza --icons --group-directories-first'
alias l="ls -l"
alias la="ls -a"
alias lla="ls -la"
alias lt="ls --tree"
# Dotfiles + notes
alias cdots="cd ~/.dots/"
alias cpnotes="cd ~/sync/PersonalNotes/"
alias cnotes="cd ~/sync/CojaDuska/Notes/"
abbr notes "cnotes && nvim"
abbr dots "cdots && nvim"
abbr dotsync "cdots && ./bin/dotsync"
abbr pnotes "cpnotes && nvim"
abbr todo "cpnotes && nvim ToDoNext.md"
abbr aliases "bat ~/.config/fish/config.fish"
# Handy
abbr cat "bat -p"
abbr untar "tar -xf"
abbr unarchive "atool -x"
abbr copy wl-copy
abbr img "kitten icat"
abbr fm yazi
abbr lg lazygit
abbr gcommit "git diff HEAD | aichat -r commit"
abbr aichatdel "rm ~/.config/aichat/sessions/*.yaml"
abbr mkdir "mkdir -p"
abbr faillock "sudo faillock --reset"
abbr xremaps "sudo xremap ~/.config/xremap/config.yml"
abbr pacs "sudo pacman -Syu --noconfirm"
abbr yays "yay --noconfirm --sudoloop"
abbr nmaps "sudo nmap -sn 192.168.0.0/24"
abbr scrcpyc 'scrcpy -wSK -m 1920 --window-borderless --always-on-top --power-off-on-close'
abbr scrcpys 'scrcpy -wS --power-off-on-close'
abbr tts "tt -notheme -bold -showwpm -json"
abbr tuioss "tuios --show-clock --show-keys --show-cpu --show-ram --confirm-quit"
abbr keybinds "cd ~/.dots/ && nvim gui/.config/hypr/dots_binds.lua"
abbr vpnhome "sudo wg-quick up wg0"
abbr vpnkralizec "sudo wg-quick up kralizec-wg0"
abbr vpnsumadija "sudo wg-quick up sumadija-wg0"
abbr ipadd "sudo ip route add 192.168.0.234 dev wg0"
abbr aria2cs "aria2c -x 16 -k 1M"
# Change-dir shortcuts
abbr .. "cd .."
abbr ... "cd ../.."
abbr .3 "cd ../../.."
abbr .4 "cd ../../../.."
abbr .5 "cd ../../../../.."
# Tool init
zoxide init --cmd cd fish | source
# thefuck, lazy-loaded on first use (its --alias eval costs ~170ms of shell startup)
function fuck
functions -e fuck
thefuck --alias | source
fuck $argv
end
end
# Per-host extras
test -f ~/.config/fish/host.fish; and source ~/.config/fish/host.fish
+30
View File
@@ -0,0 +1,30 @@
                          .dO00Od'                          
                         d00000000d.                        
                        d0000000000k                        
                        x0000000000O                        
                         k000000000                         
                           ;0000: Okc                       
                                    kkc                     
                                      kkc                   
                                        dkl                 
                                          okl               
                                            lOl             
                                              cOo.          
 .lxkOOkxl.              .lxkOOkxl.             ;OoxkOOkxl. 
'O00000000O,            'O00000000O,            '000000000O,
O0000000000OddddddddddddO00000000000ddddddddddddO00000000000
c0000000000c            :0000000000l            :0000000000l
 .00000000.              .00000000'             '000000000' 
                             00               'd0.          
                             00             ,d0.            
                             00           ,x0               
                             00         :x0                 
                             00       cxO                   
                             00     ckO                     
                           .c00l' ckk                       
                         ck000000O0                         
                        c0000000000o                        
                        O00000000000                        
                        .0000000000.                        
                          ,000000:                          
                             :c                             
+1
View File
@@ -0,0 +1 @@
danhper/fish-ssh-agent
@@ -0,0 +1,25 @@
function __ssh_agent_is_started -d "check if ssh agent is already started"
if test -n "$SSH_CONNECTION"
# This is an SSH session
ssh-add -l >/dev/null 2>&1
if test $status -eq 0 -o $status -eq 1
# An SSH agent was forwarded
return 0
end
end
if begin
test -f "$SSH_ENV"; and test -z "$SSH_AGENT_PID"
end
source $SSH_ENV >/dev/null
end
if test -z "$SSH_AGENT_PID"
return 1
end
ssh-add -l >/dev/null 2>&1
if test $status -eq 2
return 1
end
end
@@ -0,0 +1,5 @@
function __ssh_agent_start -d "start a new ssh agent"
ssh-agent -c | sed 's/^echo/#echo/' >$SSH_ENV
chmod 600 $SSH_ENV
source $SSH_ENV >/dev/null
end
+3
View File
@@ -0,0 +1,3 @@
function ask --description 'answer from cht.sh'
curl -s https://cht.sh/$(string join '+' $argv[1..])
end
+3
View File
@@ -0,0 +1,3 @@
function bashs --description 'raw bash command'
bash -c "$argv"
end
@@ -0,0 +1,17 @@
function bind_M_n_history
for i in (seq 9)
set -l command
if test (count $history) -ge $i
set command "commandline -r \$history[$i]"
else
set command "echo \"No history found for number $i\""
end
if contains fish_vi_key_bindings $fish_key_bindings
bind -M default \e$i "$command"
bind -M insert \e$i "$command"
else
bind \e$i "$command"
end
end
end
@@ -0,0 +1,30 @@
function c2-worktree
if test (count $argv) -ne 1
echo "Usage: c2-worktree <branch-name>"
echo "Example: c2-worktree package/package-update"
return 1
end
set branch $argv[1]
set root (git rev-parse --show-toplevel)
or return 1
set dir $root/.worktrees/(basename $branch)
mkdir -p $root/.worktrees
or return 1
git checkout -b $branch
or return 1
git checkout master
or return 1
git worktree add $dir $branch
or return 1
cd $dir
or return 1
pnpm i
end
+7
View File
@@ -0,0 +1,7 @@
function clis --description 'fzf select cli'
# one eval per selection — a single eval of the joined lines would run the
# first command with the other selections as its arguments
for cmd in (cat $HOME/.config/misc/clis.txt | command fzf --multi)
eval $cmd
end
end
@@ -0,0 +1,18 @@
function copy-commandline
set -l cmd (commandline)
if test -n "$cmd"
if type -q pbcopy
echo -n "$cmd" | pbcopy
else if type -q xclip
echo -n "$cmd" | xclip -selection clipboard
else if type -q wl-copy
echo -n "$cmd" | wl-copy
end
# Provide brief visual feedback in the prompt
set -l original_cmd (commandline)
commandline -r "Copied!"
sleep 0.4
commandline -r "$original_cmd"
end
end
@@ -0,0 +1,23 @@
function extract --description 'Extract any archive'
switch $argv[1]
case '*.tar' '*.tar.*' '*.tgz' '*.tbz2' '*.txz' # tar autodetects compression
tar xf $argv[1]
case '*.zip'
unzip $argv[1]
case '*.rar'
unrar x $argv[1]
case '*.7z'
7z x $argv[1]
case '*.gz'
gunzip -k $argv[1]
case '*.xz'
unxz -k $argv[1]
case '*.zst'
unzstd $argv[1]
case '*.bz2'
bunzip2 -k $argv[1]
case '*'
echo "Unknown extension: $argv[1]"
return 1
end
end
@@ -0,0 +1,5 @@
function fish_greeting
#curl "wttr.in/Belgrade?format=%l:+%c+%t+|+%h+|+%w+|+(%%M+%m)\n"
test -r ~/.config/fish/greet.txt; and cat ~/.config/fish/greet.txt ## populated by cronjob
date +"📅 %d. %b 🕗 %H:%M - %A"
end
@@ -0,0 +1,14 @@
function fish_prompt
if test -n "$SSH_TTY"
echo -n (set_color brred)"$USER"(set_color white)'@'(set_color yellow)(prompt_hostname)' '
end
echo -n (set_color blue)(prompt_pwd)' '
set_color -o
if fish_is_root_user
echo -n (set_color red)'# '
end
echo -n (set_color red)'❯'(set_color yellow)'❯'(set_color green)'❯ '
set_color normal
end
@@ -0,0 +1,161 @@
function fish_right_prompt
set -l cmd_status $status
if test $cmd_status -ne 0
echo -n (set_color red)"$cmd_status"
end
if not command -sq git
set_color normal
return
end
# Get the git directory for later use.
# Return if not inside a Git repository work tree.
if not set -l git_dir (command git rev-parse --git-dir 2>/dev/null)
set_color normal
return
end
# Get the current action ("merge", "rebase", etc.)
# and if there's one get the current commit hash too.
set -l commit ''
if set -l action (fish_print_git_action "$git_dir")
set commit (command git rev-parse HEAD 2> /dev/null | string sub -l 7)
end
# Get either the branch name or a branch descriptor.
set -l branch_detached 0
if not set -l branch (command git symbolic-ref --short HEAD 2>/dev/null)
set branch_detached 1
set branch (command git describe --contains --all HEAD 2>/dev/null)
end
# Get the commit difference counts between local and remote.
command git rev-list --count --left-right 'HEAD...@{upstream}' 2>/dev/null \
| read -d \t -l status_ahead status_behind
if test $status -ne 0
set status_ahead 0
set status_behind 0
end
# Get the stash status.
# (git stash list) is very slow. => Avoid using it.
set -l status_stashed 0
if test -f "$git_dir/refs/stash"
set status_stashed 1
else if test -r "$git_dir/commondir"
read -l commondir <"$git_dir/commondir"
if test -f "$commondir/refs/stash"
set status_stashed 1
end
end
# git-status' porcelain v1 format starts with 2 letters on each line:
# The first letter (X) denotes the index state.
# The second letter (Y) denotes the working directory state.
#
# The following table presents the possible combinations:
# * The underscore character denotes whitespace.
# * The cell values stand for the following file states:
# a: added
# d: deleted
# m: modified
# r: renamed
# u: unmerged
# t: untracked
# * Cells with more than one letter signify that both states
# are simultaneously the case. This is possible since the git index
# and working directory operate independently of each other.
# * Cells which are empty are unhandled by this code.
# * T (= type change) is undocumented.
# See Git v1.7.8.2 release notes for more information.
#
# \ Y→
# X \
# ↓ | A | C | D | M | R | T | U | X | B | ? | _
# ----+----+----+----+----+----+----+----+----+----+----+----
# A | u | | ad | am | r | am | u | | | | a
# C | | | ad | am | r | am | u | | | | a
# D | | | u | am | r | am | u | | | | a
# M | | | ad | am | r | am | u | | | | a
# R | r | r | rd | rm | r | rm | ur | r | r | r | r
# T | | | ad | am | r | am | u | | | | a
# U | u | u | u | um | ur | um | u | u | u | u | u
# X | | | | m | r | m | u | | | |
# B | | | | m | r | m | u | | | |
# ? | | | | m | r | m | u | | | t |
# _ | | | d | m | r | m | u | | | |
set -l porcelain_status (command git status --porcelain 2>/dev/null | string sub -l2)
set -l status_added 0
if string match -qr '[ACDMT][ MT]|[ACMT]D' $porcelain_status
set status_added 1
end
set -l status_deleted 0
if string match -qr '[ ACMRT]D' $porcelain_status
set status_deleted 1
end
set -l status_modified 0
if string match -qr '[MT]$' $porcelain_status
set status_modified 1
end
set -l status_renamed 0
if string match -qe R $porcelain_status
set status_renamed 1
end
set -l status_unmerged 0
if string match -qr 'AA|DD|U' $porcelain_status
set status_unmerged 1
end
set -l status_untracked 0
if string match -qe '\?\?' $porcelain_status
set status_untracked 1
end
set_color -o
if test -n "$branch"
if test $branch_detached -ne 0
set_color brmagenta
else
set_color green
end
echo -n " $branch"
end
if test -n "$commit"
echo -n ' '(set_color yellow)"$commit"
end
if test -n "$action"
set_color normal
echo -n (set_color white)':'(set_color -o brred)"$action"
end
if test $status_ahead -ne 0
echo -n ' '(set_color brmagenta)''
end
if test $status_behind -ne 0
echo -n ' '(set_color brmagenta)''
end
if test $status_stashed -ne 0
echo -n ' '(set_color cyan)''
end
if test $status_added -ne 0
echo -n ' '(set_color green)''
end
if test $status_deleted -ne 0
echo -n ' '(set_color red)''
end
if test $status_modified -ne 0
echo -n ' '(set_color blue)''
end
if test $status_renamed -ne 0
echo -n ' '(set_color magenta)''
end
if test $status_unmerged -ne 0
echo -n ' '(set_color yellow)'═'
end
if test $status_untracked -ne 0
echo -n ' '(set_color white)'◼'
end
set_color normal
end
@@ -0,0 +1,15 @@
function fish_user_key_bindings
# free Ctrl+S from terminal flow control (XOFF) so it can be bound below
stty -ixon
fish_default_key_bindings -M insert
fish_vi_key_bindings --no-erase insert
bind -M default ctrl-a beginning-of-line
bind -M default ctrl-e end-of-line
bind -M insert ctrl-space accept-autosuggestion
bind -M insert ctrl-g 'git diff' repaint
bind -M insert ctrl-o execute yazi
bind -M insert ctrl-l clear-screen ls repaint
bind -M default ctrl-s copy-commandline
bind -M insert ctrl-s copy-commandline
bind -M search ctrl-s copy-commandline
end
+7
View File
@@ -0,0 +1,7 @@
function fzfh --description 'Search history with fzf'
history | fzf --query="$argv" --tac | read cmd
if test -n "$cmd"
echo $cmd
commandline -r $cmd
end
end
+5
View File
@@ -0,0 +1,5 @@
function gcap --description 'Git add, commit with message, and push'
git add .
and git commit -m "$argv"
and git push
end
+6
View File
@@ -0,0 +1,6 @@
function glow --wraps glow --description 'glow wrapped at the current terminal width; an explicit -w still wins'
# glow never sizes itself to the terminal: glow.yml's width (or its built-in 80) applies, and
# `width: 0` in the config means 80 too. Wide tables get squeezed into that, one word per line.
# $COLUMNS tracks window resizes; a later -w/--width in $argv overrides this one.
command glow --width $COLUMNS $argv
end
+3
View File
@@ -0,0 +1,3 @@
function h --description "Colorized --help via bat"
$argv --help 2>&1 | bat --plain --language=help
end
+16
View File
@@ -0,0 +1,16 @@
function kp
if not set -q KP_DB
echo "Error: KP_DB environment variable is not set. Check ~/.config/fish/conf.d/secrets.fish"
return 1
end
read -s -P "Enter db password: " pass
echo ""
# -f flattens to full paths; without it nested entries are printed indented and
# without their group prefix, so `clip` can't find them. Group lines end in "/".
set -l entry (printf '%s\n' $pass | keepassxc-cli ls -q -R -f $KP_DB | string match -v '*/' | fzf | string trim)
if test -n "$entry"
printf '%s\n' $pass | keepassxc-cli clip -q $KP_DB $entry 0
end
end
+18
View File
@@ -0,0 +1,18 @@
function lk --description 'linux knowledge'
set -l DB "$HOME/projects/dmz/soft/lk/db.rec"
set -l passes 0
set -l count 0
set -l query ""
while test $passes -lt 2; and test $count -eq 0
set query (recsel "$DB" -p aim,tag | recsel -iq "$query" -CP aim,tag | sort -u | fzf --preview="recsel \"$DB\" -e \"aim~{}\" | bat")
if test -n "$query"
set count (recsel "$DB" -q "$query" -c)
end
set passes (math $passes + 1)
end
if test $count -eq 1
recsel "$DB" -q "$query" | recfmt -f "$HOME/projects/dmz/soft/lk/lists.fmt" | less
end
end
+11
View File
@@ -0,0 +1,11 @@
function md2pdf --description 'Markdown to PDF next to the source: cmark-gfm renders it, headless chromium prints it'
# Relative image paths don't resolve (the HTML is rendered from /tmp), and chromium
# leaves out backgrounds when printing, so code blocks lose their grey box.
set -l html (mktemp --suffix=.html)
begin
echo '<meta charset="utf-8"><style>body{font-family:sans-serif;max-width:46em;margin:auto;line-height:1.5}table{border-collapse:collapse}td,th{border:1px solid #ccc;padding:.3em .6em}</style>'
cmark-gfm -e table -e strikethrough -e autolink -e tasklist $argv[1]
end >$html
chromium --headless --no-pdf-header-footer --print-to-pdf=(path change-extension pdf $argv[1]) $html 2>/dev/null
rm $html
end
@@ -0,0 +1,45 @@
function opencodes --description 'contained opencode (bwrap); extra args are passed to opencode'
set -l cfg ~/.config/opencode
# ~/.config/opencode is stowed as per-file symlinks into ~/.dots. Bind each link's real parent
# dir read-only too, or the sandbox sees dangling links and opencode starts with NO config.
set -l dirs
for f in $cfg/* $cfg/*/*
test -L $f; or continue
set -l d (path resolve $f | path dirname)
string match -q "$cfg*" $d; and continue
contains -- $d $dirs; or set -a dirs $d
end
set -l binds
for d in $dirs
set -a binds --ro-bind $d $d
end
# --clearenv drops everything; pass through only what the TUI and its tools need.
set -l env --setenv PATH /usr/local/bin:/usr/bin:/bin
for v in HOME TERM COLORTERM LANG LC_ALL EDITOR OPENCODE_CONFIG DUSKADIY_API_KEY
set -l val $$v
test -n "$val"; and set -a env --setenv $v $val
end
mkdir -p ~/.cache/opencode ~/.local/state/opencode ~/.local/share/opencode
bwrap \
--unshare-all \
--new-session \
--clearenv \
--die-with-parent \
--share-net \
--dev /dev \
--proc /proc \
--ro-bind /usr /usr \
--ro-bind /lib /lib \
--ro-bind /lib64 /lib64 \
--ro-bind /bin /bin \
--ro-bind /etc /etc \
--ro-bind $cfg $cfg \
$binds \
--tmpfs /tmp \
--bind ~/.cache/opencode ~/.cache/opencode \
--bind ~/.local/state/opencode ~/.local/state/opencode \
--bind ~/.local/share/opencode ~/.local/share/opencode \
--bind $PWD $PWD \
$env \
opencode $argv
end
+7
View File
@@ -0,0 +1,7 @@
function ssh
if type -q kitten
kitten ssh $argv
else
command ssh $argv
end
end
+6
View File
@@ -0,0 +1,6 @@
function sshf --description 'fzf-pick an ssh host from ~/.ssh/config'
# command fzf: bypass the fzf alias (its bat preview makes no sense for host names);
# skip `Host *` wildcard blocks and take every alias on multi-name Host lines
set -l host (awk '/^Host /{for (i = 2; i <= NF; i++) if ($i != "*") print $i}' ~/.ssh/config | command fzf)
test -n "$host"; and ssh $host
end
+7
View File
@@ -0,0 +1,7 @@
function tuis --description 'fzf select tui'
# one eval per selection — a single eval of the joined lines would run the
# first command with the other selections as its arguments
for cmd in (cat $HOME/.config/misc/tuis.txt | command fzf --multi)
eval $cmd
end
end
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/env python3
"""claude-commit-msg -- hand suggested commit messages from Claude sessions to `git commit`.
Several Claude sessions work on one checkout at once, each staging its own round. The old
handoff was ONE file (`<git-dir>/CLAUDE_COMMIT_MSG`) that the prepare-commit-msg hook pasted
into the editor: the second session silently overwrote the first, and the hook could not
know which message described which files. Now every handoff is its own file under
`<git-dir>/CLAUDE_COMMIT_MSG.d/`, tagged with the paths it describes, and the hook prefills
only the message(s) whose paths are part of the commit being made:
<id>.msg the raw message
<id>.paths one repo-relative path per line (the staged set at save time)
used/ consumed messages, kept for recovery
save [--paths P ...] [--slug S] read the message on stdin; paths default to the index
list pending messages and how they match the current index
show ID | rm ID
prefill MSGFILE [SOURCE] hook entry point (prepare-commit-msg)
Matching in `prefill`: a message whose paths are all in the commit is a FULL match (prefilled,
then consumed); overlapping only partly = PARTIAL (prefilled, kept -- the rest may come in a
later commit); no paths recorded = WILDCARD (prefilled, consumed), which is also how a legacy
single CLAUDE_COMMIT_MSG file is treated. Several matches are all prefilled, separated by a
comment line git strips, so you pick in the editor. Nothing matching = editor untouched.
Everything lives inside the git dir, so it never shows in `git status`; `--git-path` keeps it
per-worktree. Always exits 0 from `prefill`: a hook failure must never abort a commit.
"""
import os
import re
import shutil
import subprocess
import sys
import time
def git(*args, check=True):
r = subprocess.run(["git", *args], capture_output=True, text=True)
if check and r.returncode != 0:
sys.exit(f"claude-commit-msg: git {' '.join(args)} failed: {r.stderr.strip()}")
return r.stdout
def store():
d = git("rev-parse", "--git-path", "CLAUDE_COMMIT_MSG.d").strip()
d = os.path.abspath(d)
os.makedirs(os.path.join(d, "used"), exist_ok=True)
return d
def staged_paths():
out = git("diff", "--cached", "--name-only", "-z", check=False)
return [p for p in out.split("\0") if p]
def comment_char():
c = git("config", "--get", "core.commentchar", check=False).strip()
return "#" if not c or c == "auto" else c[0]
def pending(d):
"""[(id, message, paths|None)] oldest first. paths None = wildcard."""
out = []
for name in sorted(os.listdir(d)):
if not name.endswith(".msg"):
continue
mid = name[:-4]
try:
with open(os.path.join(d, name)) as fh:
msg = fh.read()
except OSError:
continue
paths = None
pf = os.path.join(d, mid + ".paths")
if os.path.exists(pf):
with open(pf) as fh:
paths = [ln.rstrip("\n") for ln in fh if ln.strip()]
out.append((mid, msg, paths))
return out
def slugify(text):
m = re.match(r"\s*\[([^\]]+)\]", text) # this repo's `[Scope] summary` convention
base = m.group(1) if m else " ".join(text.split()[:3])
s = re.sub(r"[^a-z0-9]+", "-", base.lower()).strip("-")
return s[:32] or "msg"
def cmd_save(argv):
paths, slug = None, None
i = 0
while i < len(argv):
if argv[i] == "--paths":
paths = []
i += 1
while i < len(argv) and not argv[i].startswith("--"):
paths.append(argv[i])
i += 1
continue
if argv[i] == "--slug" and i + 1 < len(argv):
slug = argv[i + 1]
i += 2
continue
sys.exit(f"claude-commit-msg save: unknown argument {argv[i]!r}")
msg = sys.stdin.read().rstrip() + "\n"
if not msg.strip():
sys.exit("claude-commit-msg save: empty message on stdin")
if paths is None:
paths = staged_paths()
d = store()
mid = time.strftime("%Y%m%d-%H%M%S") + "-" + (slug or slugify(msg))
n = 1
while os.path.exists(os.path.join(d, f"{mid}.msg")):
n += 1
mid = f"{mid}-{n}"
with open(os.path.join(d, mid + ".msg"), "w") as fh:
fh.write(msg)
with open(os.path.join(d, mid + ".paths"), "w") as fh:
fh.write("".join(p + "\n" for p in paths))
print(f"saved {mid} ({len(paths)} path{'s' if len(paths) != 1 else ''}) -> {os.path.join(d, mid + '.msg')}")
if not paths:
print("warning: no paths recorded (nothing staged?) -- it will prefill on ANY commit", file=sys.stderr)
warn_if_hook_is_old()
def warn_if_hook_is_old():
"""A clone still running the legacy hook (or none) reads only the single file this tool
never writes -- the editor would come up empty with no error. Say so at save time."""
hook = git("rev-parse", "--git-path", "hooks/prepare-commit-msg", check=False).strip()
try:
with open(hook, errors="ignore") as fh:
ok = "claude-commit-msg" in fh.read()
except OSError:
ok = False
if not ok:
print(
"warning: this repo's prepare-commit-msg hook is missing or predates claude-commit-msg, so this\n"
" message will NOT be prefilled here. Install the tracked hook once per repo:\n"
" ln -sf ~/.config/git/hooks/prepare-commit-msg (git rev-parse --git-path hooks)/prepare-commit-msg",
file=sys.stderr,
)
def classify(paths, staged):
if paths is None or not paths:
return "wildcard"
ps = set(paths)
if ps <= staged:
return "full"
if ps & staged:
return "partial"
return "none"
def cmd_list(_argv):
d = store()
staged = set(staged_paths())
items = pending(d)
legacy = git("rev-parse", "--git-path", "CLAUDE_COMMIT_MSG").strip()
if not items and not os.path.exists(legacy):
print("no pending messages")
return
for mid, msg, paths in items:
n = len(paths) if paths else 0
print(f"{mid} [{classify(paths, staged):8}] {n} path{'s' if n != 1 else ''} {msg.splitlines()[0][:70]}")
if os.path.exists(legacy) and os.path.getsize(legacy) > 0:
with open(legacy) as fh:
first = fh.readline().rstrip()
print(f"(legacy CLAUDE_COMMIT_MSG) [wildcard] {first[:70]}")
def cmd_show(argv):
d = store()
for mid in argv:
with open(os.path.join(d, mid + ".msg")) as fh:
sys.stdout.write(fh.read())
def cmd_rm(argv):
d = store()
for mid in argv:
hit = False
for ext in (".msg", ".paths"):
p = os.path.join(d, mid + ext)
if os.path.exists(p):
os.remove(p)
hit = True
if hit:
print(f"removed {mid}")
elif os.path.exists(os.path.join(d, "used", mid + ".msg")):
print(f"{mid} was already consumed by a commit (see used/)")
else:
print(f"{mid}: no such pending message")
def consume(d, mid):
for ext in (".msg", ".paths"):
p = os.path.join(d, mid + ext)
if os.path.exists(p):
shutil.move(p, os.path.join(d, "used", mid + ext))
def cmd_prefill(argv):
if not argv:
return
msg_file = argv[0]
source = argv[1] if len(argv) > 1 else ""
if source not in ("", "template"): # -m/-F, merge, squash, amend: leave alone
return
d = store()
staged = set(staged_paths())
order = {"full": 0, "partial": 1, "wildcard": 2}
picked = []
for mid, msg, paths in pending(d):
kind = classify(paths, staged)
if kind != "none":
picked.append((order[kind], mid, msg, kind))
legacy = git("rev-parse", "--git-path", "CLAUDE_COMMIT_MSG").strip()
legacy_msg = None
if os.path.isfile(legacy) and os.path.getsize(legacy) > 0:
with open(legacy) as fh:
legacy_msg = fh.read()
picked.append((3, "legacy", legacy_msg, "wildcard"))
if not picked:
return
picked.sort(key=lambda t: (t[0], t[1]))
cc = comment_char()
sep = f"\n{cc} ---- another pending Claude message matched this commit; keep the right one ----\n\n"
body = sep.join(m.rstrip("\n") + "\n" for _, _, m, _ in picked)
with open(msg_file) as fh:
existing = fh.read()
tmp = msg_file + ".claude-tmp"
with open(tmp, "w") as fh:
fh.write(body + "\n" + existing)
os.replace(tmp, msg_file)
for _, mid, _, kind in picked:
if mid == "legacy":
os.replace(legacy, legacy + ".last")
elif kind in ("full", "wildcard"):
consume(d, mid)
def main():
cmds = {"save": cmd_save, "list": cmd_list, "show": cmd_show, "rm": cmd_rm, "prefill": cmd_prefill}
if len(sys.argv) < 2 or sys.argv[1] not in cmds:
sys.exit("usage: claude-commit-msg save [--paths P ...] [--slug S] < message | list | show ID | rm ID | prefill MSGFILE [SOURCE]")
if sys.argv[1] == "prefill":
try:
cmd_prefill(sys.argv[2:])
except Exception as e: # never abort a commit because of the helper
print(f"claude-commit-msg prefill: {e}", file=sys.stderr)
return
cmds[sys.argv[1]](sys.argv[2:])
if __name__ == "__main__":
main()
+36
View File
@@ -0,0 +1,36 @@
#!/bin/sh
# Prefill the commit editor from pending Claude commit messages (one-shot).
#
# Claude sessions save suggestions with `~/.config/git/claude-commit-msg save` -- one file per
# message under $(git rev-parse --git-path CLAUDE_COMMIT_MSG.d)/, tagged with the paths it
# describes. On the next `git commit` / lazygit `C` this pastes the message(s) whose paths are
# part of the commit above git's comment block, then consumes them (moved to used/). Several
# sessions can hand off in parallel without overwriting each other.
#
# Falls back to the legacy single file $(git rev-parse --git-path CLAUDE_COMMIT_MSG) when the
# CLI is not deployed on this host (not re-stowed yet). Never exits non-zero: a helper problem
# must not abort a commit.
msg_file=$1
source=$2
# Only prefill a fresh editor session -- skip -m/-F (message), merge, squash, amend (commit).
case "$source" in
""|template) ;;
*) exit 0 ;;
esac
cli="$HOME/.config/git/claude-commit-msg"
if [ -f "$cli" ] && command -v python3 >/dev/null 2>&1; then
python3 "$cli" prefill "$msg_file" "$source"
exit 0
fi
# --- legacy fallback: the single one-shot file ---
suggestion=$(git rev-parse --git-path CLAUDE_COMMIT_MSG)
[ -s "$suggestion" ] || exit 0
tmp=$(mktemp) || exit 0
{ cat "$suggestion"; printf '\n'; cat "$msg_file"; } > "$tmp" &&
mv "$tmp" "$msg_file" &&
mv "$suggestion" "$suggestion.last"
exit 0
+483
View File
@@ -0,0 +1,483 @@
# Config relating to the Lazygit UI
gui:
# The number of lines you scroll by when scrolling the main window
scrollHeight: 2
# If true, allow scrolling past the bottom of the content in the main window
scrollPastBottom: true
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#scroll-off-margin
scrollOffMargin: 2
# One of: 'margin' (default) | 'jump'
scrollOffBehavior: margin
# If true, capture mouse events.
# When mouse events are captured, it's a little harder to select text: e.g. requiring you to hold the option key when on macOS.
mouseEvents: true
# If true, do not show a warning when discarding changes in the staging view.
skipDiscardChangeWarning: false
# If true, do not show warning when applying/popping the stash
skipStashWarning: false
# If true, do not show a warning when attempting to commit without any staged files; instead stage all unstaged files.
skipNoStagedFilesWarning: false
# If true, do not show a warning when rewording a commit via an external editor
skipRewordInEditorWarning: false
# Fraction of the total screen width to use for the left side section. You may want to pick a small number (e.g. 0.2) if you're using a narrow screen, so that you can see more of the main section.
# Number from 0 to 1.0.
sidePanelWidth: 0.3333
# If true, increase the height of the focused side window; creating an accordion effect.
expandFocusedSidePanel: true
# The weight of the expanded side panel, relative to the other panels. 2 means
# twice as tall as the other panels. Only relevant if `expandFocusedSidePanel` is true.
expandedSidePanelWeight: 3
# Sometimes the main window is split in two (e.g. when the selected file has both staged and unstaged changes). This setting controls how the two sections are split.
# Options are:
# - 'horizontal': split the window horizontally
# - 'vertical': split the window vertically
# - 'flexible': (default) split the window horizontally if the window is wide enough, otherwise split vertically
mainPanelSplitMode: flexible
# How the window is split when in half screen mode (i.e. after hitting '+' once).
# Possible values:
# - 'left': split the window horizontally (side panel on the left, main view on the right)
# - 'top': split the window vertically (side panel on top, main view below)
enlargedSideViewLocation: left
# If true, wrap lines in the staging view to the width of the view. This
# makes it much easier to work with diffs that have long lines, e.g.
# paragraphs of markdown text.
wrapLinesInDiffView: true
# One of 'auto' (default) | 'en' | 'zh-CN' | 'zh-TW' | 'pl' | 'nl' | 'ja' | 'ko' | 'ru'
language: auto
# Format used when displaying time e.g. commit time.
# Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format
timeFormat: 02 Jan 06
# Format used when displaying time if the time is less than 24 hours ago.
# Uses Go's time format syntax: https://pkg.go.dev/time#Time.Format
shortTimeFormat: 3:04PM
# Config relating to colors and styles.
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#color-attributes
theme:
# Border color of focused window
activeBorderColor:
- green
- bold
# Border color of non-focused windows
inactiveBorderColor:
- default
# Border color of focused window when searching in that window
searchingActiveBorderColor:
- cyan
- bold
# Color of keybindings help text in the bottom line
optionsTextColor:
- blue
# Background color of selected line.
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#highlighting-the-selected-line
selectedRangeBgColor:
- "#444444"
selectedLineBgColor:
- "#444444"
# Background color of selected line when view doesn't have focus.
inactiveViewSelectedLineBgColor:
- bold
# Foreground color of copied commit
cherryPickedCommitFgColor:
- blue
# Background color of copied commit
cherryPickedCommitBgColor:
- cyan
# Foreground color of marked base commit (for rebase)
markedBaseCommitFgColor:
- blue
# Background color of marked base commit (for rebase)
markedBaseCommitBgColor:
- yellow
# Color for file with unstaged changes
unstagedChangesColor:
- red
# Default text color
defaultFgColor:
- default
# Config relating to the commit length indicator
commitLength:
# If true, show an indicator of commit message length
show: true
# If true, show the '5 of 20' footer at the bottom of list views
showListFooter: true
# If true, display the files in the file views as a tree. If false, display the files as a flat list.
# This can be toggled from within Lazygit with the '~' key, but that will not change the default.
showFileTree: true
# If true, show the number of lines changed per file in the Files view
showNumstatInFilesView: false
# If true, show a random tip in the command log when Lazygit starts
showRandomTip: true
# If true, show the command log
showCommandLog: true
# If true, show the bottom line that contains keybinding info and useful buttons. If false, this line will be hidden except to display a loader for an in-progress action.
showBottomLine: true
# If true, show jump-to-window keybindings in window titles.
showPanelJumps: true
# Deprecated: use nerdFontsVersion instead
showIcons: false
# Nerd fonts version to use.
# One of: '2' | '3' | empty string (default)
# If empty, do not show icons.
nerdFontsVersion: ""
# If true (default), file icons are shown in the file views. Only relevant if NerdFontsVersion is not empty.
showFileIcons: true
# Length of author name in (non-expanded) commits view. 2 means show initials only.
commitAuthorShortLength: 2
# Length of author name in expanded commits view. 2 means show initials only.
commitAuthorLongLength: 17
# Length of commit hash in commits view. 0 shows '*' if NF icons aren't on.
commitHashLength: 8
# If true, show commit hashes alongside branch names in the branches view.
showBranchCommitHash: false
# Whether to show the divergence from the base branch in the branches view.
# One of: 'none' | 'onlyArrow' | 'arrowAndNumber'
showDivergenceFromBaseBranch: none
# Height of the command log view
commandLogSize: 8
# Whether to split the main window when viewing file changes.
# One of: 'auto' | 'always'
# If 'auto', only split the main window when a file has both staged and unstaged changes
splitDiff: auto
# Default size for focused window. Window size can be changed from within Lazygit with '+' and '_' (but this won't change the default).
# One of: 'normal' (default) | 'half' | 'full'
screenMode: normal
# Window border style.
# One of 'rounded' (default) | 'single' | 'double' | 'hidden'
border: rounded
# If true, show a seriously epic explosion animation when nuking the working tree.
animateExplosion: true
# Whether to stack UI components on top of each other.
# One of 'auto' (default) | 'always' | 'never'
portraitMode: auto
# How things are filtered when typing '/'.
# One of 'substring' (default) | 'fuzzy'
filterMode: substring
# Config relating to the spinner.
spinner:
# The frames of the spinner animation.
frames:
- '|'
- /
- '-'
- \
# The "speed" of the spinner in milliseconds.
rate: 50
# Status panel view.
# One of 'dashboard' (default) | 'allBranchesLog'
statusPanelView: dashboard
# If true, jump to the Files panel after popping a stash
switchToFilesAfterStashPop: true
# If true, jump to the Files panel after applying a stash
switchToFilesAfterStashApply: true
# If true, when using the panel jump keys (default 1 through 5) and target panel is already active, go to next tab instead
switchTabsWithPanelJumpKeys: false
# Config relating to git
git:
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Custom_Pagers.md
diffRenderers:
- # Value of the --color arg in the git diff command. Some pagers want this to be set to 'always' and some want it set to 'never'
colorArg: always
# If true, Lazygit will use whatever pager is specified in `$GIT_PAGER`, `$PAGER`, or your *git config*. If the pager ends with something like ` | less` we will strip that part out, because less doesn't play nice with our rendering approach. If the custom pager uses less under the hood, that will also break rendering (hence the `--paging=never` flag for the `delta` pager).
useConfig: false
type: rawGit
# Config relating to committing
commit:
# If true, pass '--signoff' flag when committing
signOff: false
# Automatic WYSIWYG wrapping of the commit message as you type
autoWrapCommitMessage: true
# If autoWrapCommitMessage is true, the width to wrap to
autoWrapWidth: 72
# Config relating to merging
merging:
# If true, run merges in a subprocess so that if a commit message is required, Lazygit will not hang
# Only applicable to unix users.
manualCommit: false
# Extra args passed to `git merge`, e.g. --no-ff
args: ""
# The commit message to use for a squash merge commit. Can contain "{{selectedRef}}" and "{{currentBranch}}" placeholders.
squashMergeMessage: Squash merge {{selectedRef}} into {{currentBranch}}
# list of branches that are considered 'main' branches, used when displaying commits
mainBranches:
- master
- main
# Prefix to use when skipping hooks. E.g. if set to 'WIP', then pre-commit hooks will be skipped when the commit message starts with 'WIP'
skipHookPrefix: WIP
# If true, periodically fetch from remote
autoFetch: true
# If true, periodically refresh files and submodules
autoRefresh: true
# If true, pass the --all arg to git fetch
fetchAll: true
# If true, lazygit will automatically stage files that used to have merge
# conflicts but no longer do; and it will also ask you if you want to
# continue a merge or rebase if you've resolved all conflicts. If false, it
# won't do either of these things.
autoStageResolvedConflicts: true
# Command used when displaying the current branch git log in the main window
branchLogCmd: git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium {{branchName}} --
# If true, do not spawn a separate process when using GPG
overrideGpg: false
# If true, do not allow force pushes
disableForcePushing: false
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-commit-message-prefix
commitPrefix:
- # pattern to match on. E.g. for 'feature/AB-123' to match on the AB-123 use "^\\w+\\/(\\w+-\\w+).*"
pattern: ""
# Replace directive. E.g. for 'feature/AB-123' to start the commit message with 'AB-123 ' use "[$1] "
replace: ""
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#predefined-branch-name-prefix
branchPrefix: ""
# If true, parse emoji strings in commit messages e.g. render :rocket: as 🚀
# (This should really be under 'gui', not 'git')
parseEmoji: false
# Config for showing the log in the commits view
log:
# One of: 'date-order' | 'author-date-order' | 'topo-order' | 'default'
# 'topo-order' makes it easier to read the git log graph, but commits may not
# appear chronologically. See https://git-scm.com/docs/
#
# Deprecated: Configure this with `Log menu -> Commit sort order` (<c-l> in the commits window by default).
order: topo-order
# This determines whether the git graph is rendered in the commits panel
# One of 'always' | 'never' | 'when-maximised'
#
# Deprecated: Configure this with `Log menu -> Show git graph` (<c-l> in the commits window by default).
showGraph: always
# displays the whole git graph by default in the commits view (equivalent to passing the `--all` argument to `git log`)
showWholeGraph: false
# When copying commit hashes to the clipboard, truncate them to this
# length. Set to 40 to disable truncation.
truncateCopiedCommitHashesTo: 12
allBranchesLogCmds:
- git log --graph --all --color=always --abbrev-commit --decorate --date=relative --pretty=medium
# Periodic update checks
update:
# One of: 'prompt' (default) | 'background' | 'never'
method: prompt
# Period in days between update checks
days: 14
# Background refreshes
refresher:
# File/submodule refresh interval in seconds.
# Auto-refresh can be disabled via option 'git.autoRefresh'.
refreshInterval: 10
# Re-fetch interval in seconds.
# Auto-fetch can be disabled via option 'git.autoFetch'.
fetchInterval: 60
# If true, show a confirmation popup before quitting Lazygit
confirmOnQuit: false
# If true, exit Lazygit when the user presses escape in a context where there is nothing to cancel/close
quitOnTopLevelReturn: false
# Config relating to things outside of Lazygit like how files are opened, copying to clipboard, etc
os:
# Command for editing a file. Should contain "{{filename}}".
edit: ""
# Command for editing a file at a given line number. Should contain
# "{{filename}}", and may optionally contain "{{line}}".
editAtLine: ""
# Same as EditAtLine, except that the command needs to wait until the
# window is closed.
editAtLineAndWait: ""
# For opening a directory in an editor
openDirInEditor: ""
# A built-in preset that sets all of the above settings. Supported presets
# are defined in the getPreset function in editor_presets.go.
editPreset: ""
# Command for opening a file, as if the file is double-clicked. Should
# contain "{{filename}}", but doesn't support "{{line}}".
open: ""
# Command for opening a link. Should contain "{{link}}".
openLink: ""
# EditCommand is the command for editing a file.
# Deprecated: use Edit instead. Note that semantics are different:
# EditCommand is just the command itself, whereas Edit contains a
# "{{filename}}" variable.
editCommand: ""
# EditCommandTemplate is the command template for editing a file
# Deprecated: use EditAtLine instead.
editCommandTemplate: ""
# OpenCommand is the command for opening a file
# Deprecated: use Open instead.
openCommand: ""
# OpenLinkCommand is the command for opening a link
# Deprecated: use OpenLink instead.
openLinkCommand: ""
# CopyToClipboardCmd is the command for copying to clipboard.
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-command-for-copying-to-and-pasting-from-clipboard
copyToClipboardCmd: ""
# ReadFromClipboardCmd is the command for reading the clipboard.
# See https://github.com/jesseduffield/lazygit/blob/master/docs/Config.md#custom-command-for-copying-to-and-pasting-from-clipboard
readFromClipboardCmd: ""
# If true, don't display introductory popups upon opening Lazygit.
disableStartupPopups: false
# What to do when opening Lazygit outside of a git repo.
# - 'prompt': (default) ask whether to initialize a new repo or open in the most recent repo
# - 'create': initialize a new repo
# - 'skip': open most recent repo
# - 'quit': exit Lazygit
notARepository: prompt
# If true, display a confirmation when subprocess terminates. This allows you to view the output of the subprocess before returning to Lazygit.
promptToReturnFromSubprocess: true
# Keybindings
keybinding:
universal:
quit: q
quit-alt1: <c-c>
return: <esc>
quitWithoutChangingDirectory: Q
togglePanel: <tab>
prevItem: <up>
nextItem: <down>
prevItem-alt: k
nextItem-alt: j
prevPage: ','
nextPage: .
scrollLeft: H
scrollRight: L
gotoTop: <
gotoBottom: '>'
toggleRangeSelect: v
rangeSelectDown: <s-down>
rangeSelectUp: <s-up>
prevBlock: <left>
nextBlock: <right>
prevBlock-alt: h
nextBlock-alt: l
nextBlock-alt2: <tab>
prevBlock-alt2: <backtab>
jumpToBlock:
- "1"
- "2"
- "3"
- "4"
- "5"
nextMatch: "n"
prevMatch: "N"
startSearch: /
optionMenu: '?'
optionMenu-alt1: <disabled>
select: <space>
goInto: <enter>
confirm: <enter>
confirmInEditor: <a-enter>
remove: d
new: "n"
edit: e
openFile: o
scrollUpMain: <pgup>
scrollDownMain: <pgdown>
scrollUpMain-alt1: K
scrollDownMain-alt1: J
scrollUpMain-alt2: <c-u>
scrollDownMain-alt2: <c-d>
executeShellCommand: ':'
createRebaseOptionsMenu: m
# 'Files' appended for legacy reasons
pushFiles: P
# 'Files' appended for legacy reasons
pullFiles: p
refresh: R
createPatchOptionsMenu: <c-p>
nextTab: ']'
prevTab: '['
nextScreenMode: +
prevScreenMode: _
undo: z
redo: <c-z>
filteringMenu: <c-s>
diffingMenu: W
diffingMenu-alt: <c-e>
copyToClipboard: <c-o>
openRecentRepos: <c-r>
submitEditorText: <enter>
extrasMenu: '@'
toggleWhitespaceInDiffView: <c-w>
increaseContextInDiffView: '}'
decreaseContextInDiffView: '{'
increaseRenameSimilarityThreshold: )
decreaseRenameSimilarityThreshold: (
openDiffTool: <c-t>
newWorktree: w
status:
checkForUpdate: u
recentRepos: <enter>
allBranchesLogGraph: a
files:
commitChanges: c
commitChangesWithoutHook: w
amendLastCommit: A
commitChangesWithEditor: C
findBaseCommitForFixup: <c-f>
confirmDiscard: x
ignoreFile: i
refreshFiles: r
stashAllChanges: s
viewStashOptions: S
toggleStagedAll: a
viewResetOptions: D
fetch: f
toggleTreeView: '`'
openMergeOptions: M
openStatusFilter: <c-b>
copyFileInfoToClipboard: "y"
branches:
createPullRequest: o
viewPullRequestOptions: O
copyPullRequestURL: <c-y>
checkoutBranchByName: c
forceCheckoutBranch: F
rebaseBranch: r
renameBranch: R
mergeIntoCurrentBranch: M
viewGitFlowOptions: i
fastForward: f
createTag: T
pushTag: P
setUpstream: u
fetchRemote: f
sortOrder: s
commits:
squashDown: s
renameCommit: r
renameCommitWithEditor: R
viewResetOptions: g
markCommitAsFixup: f
createFixupCommit: F
squashAboveCommits: S
moveDownCommit: <c-j>
moveUpCommit: <c-k>
amendToCommit: A
resetCommitAuthor: a
pickCommit: p
revertCommit: t
cherryPickCopy: C
pasteCommits: V
markCommitAsBaseForRebase: B
tagCommit: T
checkoutCommit: <space>
# resetCherryPick: <c-R>
copyCommitAttributeToClipboard: "y"
openLogMenu: <c-l>
openInBrowser: o
viewBisectOptions: b
startInteractiveRebase: i
amendAttribute:
resetAuthor: a
setAuthor: A
addCoAuthor: c
stash:
popStash: g
renameStash: r
commitFiles:
checkoutCommitFile: c
main:
toggleSelectHunk: a
pickBothHunks: b
editSelectHunk: E
submodules:
init: i
update: u
bulkMenu: b
commitMessage:
commitMenu: <c-o>
+3
View File
@@ -0,0 +1,3 @@
om
openWebUI
itTools
+38
View File
@@ -0,0 +1,38 @@
jq
fq
rg
fd
fzf
lsd
bat
zoxide
resvg
mosh
tennis
dysk
dust
scrcpy
adb
gpg
fnm
recfmt
recsel
pass
xxd
voxcii
tldr
rsync
cowsay
fortune
lolcat
glow
pake
bwrap
dog
nmap
rustscan
traceroute
fuck
atool
aria2c
cmark-gfm
+77
View File
@@ -0,0 +1,77 @@
browsh
wiki-tui
wikiman
yazi
tdf
dysk
dust
ncdu
duf
systemctl-tui
btop
bandwhich
mtr
gping
flow
bmon
profanity
nmtui
impala
bluetui
sshm
aichat
tt
gittype
toofan
pastel
hexyl
binsider
tmux
zellij
nvim
vim
tetrigo
pyradio
cliamp
px7-radio
kew
cmatrix
neo-matrix
cava
pipes-rs
asciiquarium
cbonsai
tclock
hunk
tuicr
gittop
lazygit
lazyjournal
lazydocker
lazyrsync
ctop
colima
dive
asciinema
posting
serie
clx
whosthere
voxcii
bookokrat
tennis
llmfit
termdraw
torlnk
riptide
quien
eilmeldung
calcure
weathr
hyprmon
hulak
netwatch
gpk
circumflex
darya
usbtree
+6
View File
@@ -0,0 +1,6 @@
column_width = 120
line_endings = "Unix"
indent_type = "Spaces"
indent_width = 2
quote_style = "AutoPreferDouble"
call_parentheses = "None"
+98
View File
@@ -0,0 +1,98 @@
# Neovim Configuration Setup
This Neovim configuration is built on top of [NvChad](https://nvchad.com/), a popular Neovim framework designed for speed and aesthetics. It uses [lazy.nvim](https://github.com/folke/lazy.nvim) as the plugin manager.
## Core Components
- **Framework**: [NvChad](https://nvchad.com/) (v2.5)
- **Plugin Manager**: `lazy.nvim`
- **Theme Engine**: `base46` (integrated with NvChad)
- **Keybindings**: Custom mappings are defined in `lua/mappings.lua`.
- **Options**: Base options are inherited from NvChad, with customizations in `lua/options.lua`.
## Installed Plugins & Features
The configuration includes several key plugins and features:
### Development Tools
- **LSP (Language Server Protocol)**: Configured via `nvim-lspconfig`. Note that you must install the actual language servers using [Mason.nvim](https://github.com/williamboman/mason.nvim).
- **Formatting**: Uses `conform.nvim` for code formatting (configured in `lua/configs/conform.lua`).
- **Treesitter**: Provides advanced syntax highlighting and code folding (configured in `lua/plugins/init.lua`).
- **Telescope**: Powerful fuzzy finder for files, text, and LSP symbols.
### UI & Productivity
- **Snacks.nvim**: A collection of useful utilities including:
- `explorer`: File explorer.
- `indent`: Indent guides (replaces `indent-blankline.nvim` to avoid duplication).
- `picker`: Fast picker for various tasks.
- `notifier`: Improved notification system.
- `words`: Word count and related features.
- **Render Markdown**: Enhances the appearance of Markdown files in the buffer (`lua/configs/render-markdown.lua`).
## Maintenance & Package Management
### Managing Plugins (lazy.nvim)
To update your installed Neovim plugins:
1. Open Neovim.
2. Run `:Lazy` to open the plugin manager UI.
3. Press `U` to check for updates and `u` to update everything.
### Managing LSPs & Tools (Mason.nvim)
While plugins are managed by `lazy.nvim`, the actual language servers, debuggers, and formatters are managed by **Mason**.
1. Open Neovim.
2. Run `:Mason` to open the Mason UI.
3. Use the UI to install or update your desired LSPs (e.g., `ts_ls`, `html`, `cssls`), linters, or formatters.
### Managing Syntax Highlighting (Treesitter)
To ensure all language parsers are installed for proper syntax highlighting:
1. Open Neovim.
2. Run `:TSUpdate` (or `:TSInstall <language>` for a specific one).
## Custom Keybindings
Some notable custom mappings (defined in `lua/mappings.lua`):
| Mapping | Action | Description |
|---------|--------|-------------|
| `gd` | `vim.lsp.buf.definition` | Go to definition |
| `gD` | `Telescope lsp_definitions` | Go to definitions (Telescope) |
| `grr` | `Telescope lsp_references` | Go to references (Telescope) |
| `<leader>da` | `vim.lsp.buf.code_action()` | Code actions |
| `<leader>dh` | `vim.diagnostic.open_float()` | Show diagnostics in float |
| `<leader>dj` | `vim.diagnostic.jump` | Go to next diagnostic |
| `<leader>dk` | `vim.diagnostic.jump` | Go to previous diagnostic |
| `<leader>fr` | `Telescope resume` | Resume last Telescope search |
| `<leader>fs` | `Telescope grep_string` | Find selected string |
| `<leader>fk` | `Telescope keymaps` | Find keymaps |
| `<leader>fd` | `Telescope diagnostics` | Search diagnostics |
**Improved Deletion/Change:**
- `x` (in Normal/Visual mode): Deletes a character without yanking it to the register.
- `c` (in Normal/Visual mode): Changes text without yanking it to the register.
## Directory Structure
```text
.
├── init.lua # Entry point: bootstraps lazy.nvim and loads config
├── lazy-lock.json # Lockfile for lazy.nvim
└── lua/
├── chadrc.lua # NvChad configuration
├── configs/ # Plugin-specific configurations
│ ├── conform.lua
│ ├── lazy.lua
│ ├── lspconfig.lua
│ └── render-markdown.lua
├── mappings.lua # Custom keybindings
├── options.lua # Custom Neovim options
└── plugins/
└── init.lua # Plugin definitions and setup
```
## Installation
1. Ensure you have [Neovim](https://neovim.io/) (latest stable or nightly) installed.
2. Clone this repository to your Neovim configuration directory (usually `~/.config/nvim`).
3. Open Neovim. `lazy.nvim` will automatically bootstrap and install all required plugins.
4. **Important**: After the initial plugin installation, run `:MasonInstall <server_name>` (or use the `:Mason` UI) to install the language servers required for your workflow.
5. Restart Neovim after the initial installation completes.
+38
View File
@@ -0,0 +1,38 @@
vim.g.base46_cache = vim.fn.stdpath "data" .. "/base46/"
vim.g.mapleader = " "
vim.opt.relativenumber = true
-- bootstrap lazy and all plugins
local lazypath = vim.fn.stdpath "data" .. "/lazy/lazy.nvim"
if not vim.uv.fs_stat(lazypath) then
local repo = "https://github.com/folke/lazy.nvim.git"
vim.fn.system { "git", "clone", "--filter=blob:none", repo, "--branch=stable", lazypath }
end
vim.opt.rtp:prepend(lazypath)
local lazy_config = require "configs.lazy"
-- load plugins
require("lazy").setup({
{
"NvChad/NvChad",
lazy = false,
branch = "v2.5",
import = "nvchad.plugins",
},
{ import = "plugins" },
}, lazy_config)
-- load theme
dofile(vim.g.base46_cache .. "defaults")
dofile(vim.g.base46_cache .. "statusline")
require "options"
require "nvchad.autocmds"
vim.schedule(function()
require "mappings"
end)
+31
View File
@@ -0,0 +1,31 @@
{
"LuaSnip": { "branch": "master", "commit": "0abc8f390b278c3b4aabc4c004ac8a088b65cf24" },
"NvChad": { "branch": "v2.5", "commit": "87d6a41ec07ab995de912a892749b6b4805ad2b3" },
"base46": { "branch": "v3.0", "commit": "d870ec89a7b2f28c4accce515f97b7bcc5b9d200" },
"cmp-async-path": { "branch": "main", "commit": "98185a91d49ff5dd249aebf2f7456e18063fa2a0" },
"cmp-buffer": { "branch": "main", "commit": "b74fab3656eea9de20a9b8116afa3cfc4ec09657" },
"cmp-nvim-lsp": { "branch": "main", "commit": "cbc7b02bb99fae35cb42f514762b89b5126651ef" },
"cmp-nvim-lua": { "branch": "main", "commit": "e3a22cb071eb9d6508a156306b102c45cd2d573d" },
"cmp_luasnip": { "branch": "master", "commit": "98d9cb5c2c38532bd9bdb481067b20fea8f32e90" },
"conform.nvim": { "branch": "master", "commit": "016802de402556da54c36bd7359b441266b01cdd" },
"friendly-snippets": { "branch": "main", "commit": "b2ea5c41a150ba72fb656eedb4ed0a86d138d945" },
"gitsigns.nvim": { "branch": "main", "commit": "4bcd99167c265f135886b282baad77afe06206b2" },
"indent-blankline.nvim": { "branch": "master", "commit": "d28a3f70721c79e3c5f6693057ae929f3d9c0a03" },
"lazy.nvim": { "branch": "main", "commit": "306a05526ada86a7b30af95c5cc81ffba93fef97" },
"mason.nvim": { "branch": "main", "commit": "2a6940af80375532e5e9e7c1f2fc6319a1b7a69d" },
"menu": { "branch": "main", "commit": "7a0a4a2896b715c066cfbe320bdc048091874cc6" },
"minty": { "branch": "main", "commit": "aafc9e8e0afe6bf57580858a2849578d8d8db9e0" },
"nvim-autopairs": { "branch": "master", "commit": "3172f40c16563db871a58f20d205c710ad782311" },
"nvim-cmp": { "branch": "main", "commit": "e04302f1fefcb5653848346eb3723b39b82c549b" },
"nvim-lspconfig": { "branch": "master", "commit": "cc404d425c7752f56b8eaa269107be44d888ea51" },
"nvim-tree.lua": { "branch": "master", "commit": "69eb0c34ed3d836d5a0d92d913b77dd73b054f2f" },
"nvim-treesitter": { "branch": "main", "commit": "610734c5d3e59761d5f79318d120633374537fa5" },
"nvim-web-devicons": { "branch": "master", "commit": "ec309a0eaff6ea967e58c275996155ab5c16938d" },
"plenary.nvim": { "branch": "master", "commit": "74b06c6c75e4eeb3108ec01852001636d85a932b" },
"render-markdown.nvim": { "branch": "main", "commit": "8e8795368391036643b622875a6da6a51bcd33f4" },
"snacks.nvim": { "branch": "main", "commit": "882c996cf28183f4d63640de0b4c02ec886d01f2" },
"telescope.nvim": { "branch": "master", "commit": "40aedd8a68c78a656a10a8d62d80c54af59420fb" },
"ui": { "branch": "v3.0", "commit": "8cbf0dc1883b20a1df114149c187d250f0af0853" },
"volt": { "branch": "main", "commit": "4351c5cd790a0d39491c4d5c75dd62d7db3d3414" },
"which-key.nvim": { "branch": "main", "commit": "3aab2147e74890957785941f0c1ad87d0a44c15a" }
}
+57
View File
@@ -0,0 +1,57 @@
-- This file needs to have same structure as nvconfig.lua
-- https://github.com/NvChad/ui/blob/v3.0/lua/nvconfig.lua
-- Please read that file to know all available options :(
---@type ChadrcConfig
local M = {
lsp = { signature = true },
base46 = {
theme = "onedark",
transparency = true,
hl_override = {
NvimTreeGitDirty = {
fg = "#DBA55D",
},
},
-- Comment = { italic = true },
-- ["@comment"] = { italic = true },
},
nvdash = {
load_on_startup = true,
-- buttons = {
-- { txt = " Find File", keys = "Spc f f", cmd = "Telescope find_files custom" },
-- { txt = " Recent Files", keys = "Spc f o", cmd = "Telescope oldfiles" },
-- -- more... check nvconfig.lua file for full list of buttons
-- },
},
ui = {
-- lazyload it when there are 1+ buffers
tabufline = {
enabled = true,
lazyload = true,
order = { "treeOffset", "buffers", "tabs", "btns" },
modules = nil,
bufwidth = 21,
},
},
term = {
base46_colors = true,
winopts = { number = false },
sizes = { sp = 0.5, vsp = 0.2, ["bo sp"] = 0.3, ["bo vsp"] = 0.2 },
float = {
relative = "editor",
row = 0.05,
col = 0.05,
width = 0.9,
height = 0.8,
border = "single",
},
},
}
return M
@@ -0,0 +1,17 @@
local options = {
formatters_by_ft = {
lua = { "stylua" },
css = { "prettier" },
html = { "prettier" },
typescript = { "prettier" },
javascript = { "prettier" },
},
format_on_save = {
-- These options will be passed to conform.format()
timeout_ms = 500,
lsp_format = "fallback",
},
}
return options
+47
View File
@@ -0,0 +1,47 @@
return {
defaults = { lazy = true },
install = { colorscheme = { "nvchad" } },
ui = {
icons = {
ft = "",
lazy = "󰂠 ",
loaded = "",
not_loaded = "",
},
},
performance = {
rtp = {
disabled_plugins = {
"2html_plugin",
"tohtml",
"getscript",
"getscriptPlugin",
"gzip",
"logipat",
"netrw",
"netrwPlugin",
"netrwSettings",
"netrwFileHandlers",
"matchit",
"tar",
"tarPlugin",
"rrhelper",
"spellfile_plugin",
"vimball",
"vimballPlugin",
"zip",
"zipPlugin",
"tutor",
"rplugin",
"syntax",
"synmenu",
"optwin",
"compiler",
"bugreport",
"ftplugin",
},
},
},
}
@@ -0,0 +1,47 @@
require("nvchad.configs.lspconfig").defaults()
local servers = { "html", "cssls", "ts_ls", "eslint" }
vim.lsp.enable(servers)
-- Waybar/GTK stylesheets are GTK CSS, a different dialect: `@name` references
-- @define-color colors (waybar's theme.css) and functions like alpha() are
-- valid there but not in web CSS, so cssls floods "property value expected" /
-- "{ expected" false errors. No LSP speaks the GTK dialect, so keep cssls
-- attached (standard-property completion still useful) and mute diagnostics
-- on those buffers only.
vim.api.nvim_create_autocmd("LspAttach", {
callback = function(args)
local client = vim.lsp.get_client_by_id(args.data.client_id)
if not client or client.name ~= "cssls" then
return
end
local path = vim.api.nvim_buf_get_name(args.buf)
if path:match "/waybar/" or path:match "/gtk%-%d" then
vim.diagnostic.enable(false, { bufnr = args.buf })
end
end,
})
-- local lspconfig = require "lspconfig"
-- local nvlsp = require "nvchad.configs.lspconfig"
--
-- -- lsps with default config
-- for _, lsp in ipairs(servers) do
-- lspconfig[lsp].setup {
-- on_attach = nvlsp.on_attach,
-- on_init = nvlsp.on_init,
-- capabilities = nvlsp.capabilities,
-- }
-- end
--
-- -- configuring single server, example: typescript
-- lspconfig.ts_ls.setup {
-- filetypes = { 'typescript', 'javascript', 'javascriptreact', 'typescriptreact', 'vue', 'markdown' },
-- }
--
-- -- configuring single server, example: typescript
-- -- lspconfig.ts_ls.setup {
-- -- on_attach = nvlsp.on_attach,
-- -- on_init = nvlsp.on_init,
-- -- capabilities = nvlsp.capabilities,
-- -- }
@@ -0,0 +1,851 @@
return {
-- Whether markdown should be rendered by default.
enabled = true,
-- Vim modes that will show a rendered view of the markdown file, :h mode(), for all enabled
-- components. Individual components can be enabled for other modes. Remaining modes will be
-- unaffected by this plugin.
render_modes = { "i", "n", "c", "t" },
-- Maximum file size (in MB) that this plugin will attempt to render.
-- Any file larger than this will effectively be ignored.
max_file_size = 10.0,
-- Milliseconds that must pass before updating marks, updates occur.
-- within the context of the visible window, not the entire buffer.
debounce = 100,
-- Pre configured settings that will attempt to mimic various target user experiences.
-- Any user provided settings will take precedence.
-- | obsidian | mimic Obsidian UI |
-- | lazy | will attempt to stay up to date with LazyVim configuration |
-- | none | does nothing |
preset = "none",
-- The level of logs to write to file: vim.fn.stdpath('state') .. '/render-markdown.log'.
-- Only intended to be used for plugin development / debugging.
log_level = "error",
-- Print runtime of main update method.
-- Only intended to be used for plugin development / debugging.
log_runtime = false,
-- Filetypes this plugin will run on.
file_types = { "markdown", "gitcommit" },
-- Takes buffer as input, if it returns true this plugin will not attach to the buffer
ignore = function()
return false
end,
-- Additional events that will trigger this plugin's render loop.
change_events = {},
injections = {
-- Out of the box language injections for known filetypes that allow markdown to be interpreted
-- in specified locations, see :h treesitter-language-injections.
-- Set enabled to false in order to disable.
gitcommit = {
enabled = true,
query = [[
((message) @injection.content
(#set! injection.combined)
(#set! injection.include-children)
(#set! injection.language "markdown"))
]],
},
},
patterns = {
-- Highlight patterns to disable for filetypes, i.e. lines concealed around code blocks
markdown = {
disable = true,
directives = {
{ id = 17, name = "conceal_lines" },
{ id = 18, name = "conceal_lines" },
},
},
},
anti_conceal = {
-- This enables hiding any added text on the line the cursor is on.
enabled = true,
-- Modes to disable anti conceal feature.
disabled_modes = false,
-- Number of lines above cursor to show.
above = 0,
-- Number of lines below cursor to show.
below = 0,
-- Which elements to always show, ignoring anti conceal behavior. Values can either be
-- booleans to fix the behavior or string lists representing modes where anti conceal
-- behavior will be ignored. Valid values are:
-- bullet
-- callout
-- check_icon, check_scope
-- code_background, code_border, code_language
-- dash
-- head_background, head_border, head_icon
-- indent
-- link
-- quote
-- sign
-- table_border
-- virtual_lines
ignore = {
code_background = true,
indent = true,
sign = true,
virtual_lines = true,
},
},
padding = {
-- Highlight to use when adding whitespace, should match background.
highlight = "Normal",
},
latex = {
-- Turn on / off latex rendering.
enabled = true,
-- Additional modes to render latex.
render_modes = false,
-- Executable used to convert latex formula to rendered unicode.
converter = "latex2text",
-- Highlight for latex blocks.
highlight = "RenderMarkdownMath",
-- Determines where latex formula is rendered relative to block.
-- | above | above latex block |
-- | below | below latex block |
position = "above",
-- Number of empty lines above latex blocks.
top_pad = 0,
-- Number of empty lines below latex blocks.
bottom_pad = 0,
},
on = {
-- Called when plugin initially attaches to a buffer.
attach = function() end,
-- Called before adding marks to the buffer for the first time.
initial = function() end,
-- Called after plugin renders a buffer.
render = function() end,
-- Called after plugin clears a buffer.
clear = function() end,
},
completions = {
-- Settings for blink.cmp completions source
blink = { enabled = false },
-- Settings for coq_nvim completions source
coq = { enabled = false },
-- Settings for in-process language server completions
lsp = { enabled = false },
filter = {
callout = function()
-- example to exclude obsidian callouts
-- return value.category ~= 'obsidian'
return true
end,
checkbox = function()
return true
end,
},
},
heading = {
-- Useful context to have when evaluating values.
-- | level | the number of '#' in the heading marker |
-- | sections | for each level how deeply nested the heading is |
-- Turn on / off heading icon & background rendering.
enabled = true,
-- Additional modes to render headings.
render_modes = false,
-- Turn on / off atx heading rendering.
atx = true,
-- Turn on / off setext heading rendering.
setext = true,
-- Turn on / off any sign column related rendering.
sign = true,
-- Replaces '#+' of 'atx_h._marker'.
-- Output is evaluated depending on the type.
-- | function | `value(context)` |
-- | string[] | `cycle(value, context.level)` |
icons = { "󰲡 ", "󰲣 ", "󰲥 ", "󰲧 ", "󰲩 ", "󰲫 " },
-- Determines how icons fill the available space.
-- | right | '#'s are concealed and icon is appended to right side |
-- | inline | '#'s are concealed and icon is inlined on left side |
-- | overlay | icon is left padded with spaces and inserted on left hiding any additional '#' |
position = "overlay",
-- Added to the sign column if enabled.
-- Output is evaluated by `cycle(value, context.level)`.
signs = { "󰫎 " },
-- Width of the heading background.
-- | block | width of the heading text |
-- | full | full width of the window |
-- Can also be a list of the above values evaluated by `clamp(value, context.level)`.
width = "full",
-- Amount of margin to add to the left of headings.
-- Margin available space is computed after accounting for padding.
-- If a float < 1 is provided it is treated as a percentage of available window space.
-- Can also be a list of numbers evaluated by `clamp(value, context.level)`.
left_margin = 0,
-- Amount of padding to add to the left of headings.
-- Output is evaluated using the same logic as 'left_margin'.
left_pad = 0,
-- Amount of padding to add to the right of headings when width is 'block'.
-- Output is evaluated using the same logic as 'left_margin'.
right_pad = 0,
-- Minimum width to use for headings when width is 'block'.
-- Can also be a list of integers evaluated by `clamp(value, context.level)`.
min_width = 0,
-- Determines if a border is added above and below headings.
-- Can also be a list of booleans evaluated by `clamp(value, context.level)`.
border = false,
-- Always use virtual lines for heading borders instead of attempting to use empty lines.
border_virtual = false,
-- Highlight the start of the border using the foreground highlight.
border_prefix = false,
-- Used above heading for border.
above = "▄",
-- Used below heading for border.
below = "▀",
-- Highlight for the heading icon and extends through the entire line.
-- Output is evaluated by `clamp(value, context.level)`.
backgrounds = {
"RenderMarkdownH1Bg",
"RenderMarkdownH2Bg",
"RenderMarkdownH3Bg",
"RenderMarkdownH4Bg",
"RenderMarkdownH5Bg",
"RenderMarkdownH6Bg",
},
-- Highlight for the heading and sign icons.
-- Output is evaluated using the same logic as 'backgrounds'.
foregrounds = {
"RenderMarkdownH1",
"RenderMarkdownH2",
"RenderMarkdownH3",
"RenderMarkdownH4",
"RenderMarkdownH5",
"RenderMarkdownH6",
},
-- Define custom heading patterns which allow you to override various properties based on
-- the contents of a heading.
-- The key is for healthcheck and to allow users to change its values, value type below.
-- | pattern | matched against the heading text @see :h lua-patterns |
-- | icon | optional override for the icon |
-- | background | optional override for the background |
-- | foreground | optional override for the foreground |
custom = {},
},
paragraph = {
-- Useful context to have when evaluating values.
-- | text | text value of the node |
-- Turn on / off paragraph rendering.
enabled = true,
-- Additional modes to render paragraphs.
render_modes = false,
-- Amount of margin to add to the left of paragraphs.
-- If a float < 1 is provided it is treated as a percentage of available window space.
-- Output is evaluated depending on the type.
-- | function | `value(context)` |
-- | number | `value` |
left_margin = 0,
-- Amount of padding to add to the first line of each paragraph.
-- Output is evaluated using the same logic as 'left_margin'.
indent = 0,
-- Minimum width to use for paragraphs.
min_width = 0,
},
code = {
-- Turn on / off code block & inline code rendering.
enabled = true,
-- Additional modes to render code blocks.
render_modes = false,
-- Turn on / off any sign column related rendering.
sign = true,
-- Determines how code blocks & inline code are rendered.
-- | none | disables all rendering |
-- | normal | background highlighting + padding |
-- | language | language heading with icon + sign column |
-- | full | normal + language |
style = "full",
-- Whether to conceal nodes at the top and bottom of code blocks.
conceal_delimiters = true,
-- Turn on / off any language heading related rendering.
language = true,
-- Determines where language icon is rendered.
-- | right | right side of code block |
-- | left | left side of code block |
position = "left",
-- Whether to include the language icon above code blocks.
language_icon = true,
-- Whether to include the language name above code blocks.
language_name = true,
-- Whether to include the language info above code blocks.
language_info = true,
-- Amount of padding to add around the language.
-- If a float < 1 is provided it is treated as a percentage of available window space.
language_pad = 0,
-- A list of language names for which background highlighting will be disabled.
-- Likely because that language has background highlights itself.
-- Use a boolean to make behavior apply to all languages.
-- Borders above & below blocks will continue to be rendered.
disable_background = { "diff" },
-- Width of the code block background.
-- | block | width of the code block |
-- | full | full width of the window |
width = "full",
-- Amount of margin to add to the left of code blocks.
-- If a float < 1 is provided it is treated as a percentage of available window space.
-- Margin available space is computed after accounting for padding.
left_margin = 0,
-- Amount of padding to add to the left of code blocks.
-- If a float < 1 is provided it is treated as a percentage of available window space.
left_pad = 0,
-- Amount of padding to add to the right of code blocks when width is 'block'.
-- If a float < 1 is provided it is treated as a percentage of available window space.
right_pad = 0,
-- Minimum width to use for code blocks when width is 'block'.
min_width = 0,
-- Determines how the top / bottom of code block are rendered.
-- | none | do not render a border |
-- | thick | use the same highlight as the code body |
-- | thin | when lines are empty overlay the above & below icons |
-- | hide | conceal lines unless language name or icon is added |
border = "hide",
-- Used above code blocks to fill remaining space around language.
language_border = "█",
-- Added to the left of language.
language_left = "",
-- Added to the right of language.
language_right = "",
-- Used above code blocks for thin border.
above = "▄",
-- Used below code blocks for thin border.
below = "▀",
-- Icon to add to the left of inline code.
inline_left = "",
-- Icon to add to the right of inline code.
inline_right = "",
-- Padding to add to the left & right of inline code.
inline_pad = 0,
-- Highlight for code blocks.
highlight = "RenderMarkdownCode",
-- Highlight for code info section, after the language.
highlight_info = "RenderMarkdownCodeInfo",
-- Highlight for language, overrides icon provider value.
highlight_language = nil,
-- Highlight for border, use false to add no highlight.
highlight_border = "RenderMarkdownCodeBorder",
-- Highlight for language, used if icon provider does not have a value.
highlight_fallback = "RenderMarkdownCodeFallback",
-- Highlight for inline code.
highlight_inline = "RenderMarkdownCodeInline",
},
dash = {
-- Turn on / off thematic break rendering.
enabled = true,
-- Additional modes to render dash.
render_modes = false,
-- Replaces '---'|'***'|'___'|'* * *' of 'thematic_break'.
-- The icon gets repeated across the window's width.
icon = "─",
-- Width of the generated line.
-- | <number> | a hard coded width value |
-- | full | full width of the window |
-- If a float < 1 is provided it is treated as a percentage of available window space.
width = "full",
-- Amount of margin to add to the left of dash.
-- If a float < 1 is provided it is treated as a percentage of available window space.
left_margin = 0,
-- Highlight for the whole line generated from the icon.
highlight = "RenderMarkdownDash",
},
document = {
-- Turn on / off document rendering.
enabled = true,
-- Additional modes to render document.
render_modes = false,
-- Ability to conceal arbitrary ranges of text based on lua patterns, @see :h lua-patterns.
-- Relies entirely on user to set patterns that handle their edge cases.
conceal = {
-- Matched ranges will be concealed using character level conceal.
char_patterns = {},
-- Matched ranges will be concealed using line level conceal.
line_patterns = {},
},
},
bullet = {
-- Useful context to have when evaluating values.
-- | level | how deeply nested the list is, 1-indexed |
-- | index | how far down the item is at that level, 1-indexed |
-- | value | text value of the marker node |
-- Turn on / off list bullet rendering
enabled = true,
-- Additional modes to render list bullets
render_modes = false,
-- Replaces '-'|'+'|'*' of 'list_item'.
-- If the item is a 'checkbox' a conceal is used to hide the bullet instead.
-- Output is evaluated depending on the type.
-- | function | `value(context)` |
-- | string | `value` |
-- | string[] | `cycle(value, context.level)` |
-- | string[][] | `clamp(cycle(value, context.level), context.index)` |
icons = { "●", "○", "◆", "◇" },
-- Replaces 'n.'|'n)' of 'list_item'.
-- Output is evaluated using the same logic as 'icons'.
ordered_icons = function(ctx)
local value = vim.trim(ctx.value)
local index = tonumber(value:sub(1, #value - 1))
return ("%d."):format(index > 1 and index or ctx.index)
end,
-- Padding to add to the left of bullet point.
-- Output is evaluated depending on the type.
-- | function | `value(context)` |
-- | integer | `value` |
left_pad = 0,
-- Padding to add to the right of bullet point.
-- Output is evaluated using the same logic as 'left_pad'.
right_pad = 0,
-- Highlight for the bullet icon.
-- Output is evaluated using the same logic as 'icons'.
highlight = "RenderMarkdownBullet",
-- Highlight for item associated with the bullet point.
-- Output is evaluated using the same logic as 'icons'.
scope_highlight = {},
},
checkbox = {
-- Checkboxes are a special instance of a 'list_item' that start with a 'shortcut_link'.
-- There are two special states for unchecked & checked defined in the markdown grammar.
-- Turn on / off checkbox state rendering.
enabled = true,
-- Additional modes to render checkboxes.
render_modes = false,
-- Render the bullet point before the checkbox.
bullet = false,
-- Padding to add to the right of checkboxes.
right_pad = 1,
unchecked = {
-- Replaces '[ ]' of 'task_list_marker_unchecked'.
icon = "󰄱 ",
-- Highlight for the unchecked icon.
highlight = "RenderMarkdownUnchecked",
-- Highlight for item associated with unchecked checkbox.
scope_highlight = nil,
},
checked = {
-- Replaces '[x]' of 'task_list_marker_checked'.
icon = "󰱒 ",
-- Highlight for the checked icon.
highlight = "RenderMarkdownChecked",
-- Highlight for item associated with checked checkbox.
scope_highlight = nil,
},
-- Define custom checkbox states, more involved, not part of the markdown grammar.
-- As a result this requires neovim >= 0.10.0 since it relies on 'inline' extmarks.
-- The key is for healthcheck and to allow users to change its values, value type below.
-- | raw | matched against the raw text of a 'shortcut_link' |
-- | rendered | replaces the 'raw' value when rendering |
-- | highlight | highlight for the 'rendered' icon |
-- | scope_highlight | optional highlight for item associated with custom checkbox |
-- stylua: ignore
custom = {
todo = { raw = '[-]', rendered = '󰥔 ', highlight = 'RenderMarkdownTodo', scope_highlight = nil },
},
},
quote = {
-- Turn on / off block quote & callout rendering.
enabled = true,
-- Additional modes to render quotes.
render_modes = false,
-- Replaces '>' of 'block_quote'.
icon = "▋",
-- Whether to repeat icon on wrapped lines. Requires neovim >= 0.10. This will obscure text
-- if incorrectly configured with :h 'showbreak', :h 'breakindent' and :h 'breakindentopt'.
-- A combination of these that is likely to work follows.
-- | showbreak | ' ' (2 spaces) |
-- | breakindent | true |
-- | breakindentopt | '' (empty string) |
-- These are not validated by this plugin. If you want to avoid adding these to your main
-- configuration then set them in win_options for this plugin.
repeat_linebreak = false,
-- Highlight for the quote icon.
-- If a list is provided output is evaluated by `cycle(value, level)`.
highlight = {
"RenderMarkdownQuote1",
"RenderMarkdownQuote2",
"RenderMarkdownQuote3",
"RenderMarkdownQuote4",
"RenderMarkdownQuote5",
"RenderMarkdownQuote6",
},
},
pipe_table = {
-- Turn on / off pipe table rendering.
enabled = true,
-- Additional modes to render pipe tables.
render_modes = false,
-- Pre configured settings largely for setting table border easier.
-- | heavy | use thicker border characters |
-- | double | use double line border characters |
-- | round | use round border corners |
-- | none | does nothing |
preset = "none",
-- Determines how the table as a whole is rendered.
-- | none | disables all rendering |
-- | normal | applies the 'cell' style rendering to each row of the table |
-- | full | normal + a top & bottom line that fill out the table when lengths match |
style = "full",
-- Determines how individual cells of a table are rendered.
-- | overlay | writes completely over the table, removing conceal behavior and highlights |
-- | raw | replaces only the '|' characters in each row, leaving the cells unmodified |
-- | padded | raw + cells are padded to maximum visual width for each column |
-- | trimmed | padded except empty space is subtracted from visual width calculation |
cell = "padded",
-- Amount of space to put between cell contents and border.
padding = 1,
-- Minimum column width to use for padded or trimmed cell.
min_width = 0,
-- Characters used to replace table border.
-- Correspond to top(3), delimiter(3), bottom(3), vertical, & horizontal.
-- stylua: ignore
border = {
'┌', '┬', '┐',
'├', '┼', '┤',
'└', '┴', '┘',
'│', '─',
},
-- Always use virtual lines for table borders instead of attempting to use empty lines.
-- Will be automatically enabled if indentation module is enabled.
border_virtual = false,
-- Gets placed in delimiter row for each column, position is based on alignment.
alignment_indicator = "━",
-- Highlight for table heading, delimiter, and the line above.
head = "RenderMarkdownTableHead",
-- Highlight for everything else, main table rows and the line below.
row = "RenderMarkdownTableRow",
-- Highlight for inline padding used to add back concealed space.
filler = "RenderMarkdownTableFill",
},
callout = {
-- Callouts are a special instance of a 'block_quote' that start with a 'shortcut_link'.
-- The key is for healthcheck and to allow users to change its values, value type below.
-- | raw | matched against the raw text of a 'shortcut_link', case insensitive |
-- | rendered | replaces the 'raw' value when rendering |
-- | highlight | highlight for the 'rendered' text and quote markers |
-- | quote_icon | optional override for quote.icon value for individual callout |
-- | category | optional metadata useful for filtering |
note = {
raw = "[!NOTE]",
rendered = "󰋽 Note",
highlight = "RenderMarkdownInfo",
category = "github",
},
tip = {
raw = "[!TIP]",
rendered = "󰌶 Tip",
highlight = "RenderMarkdownSuccess",
category = "github",
},
important = {
raw = "[!IMPORTANT]",
rendered = "󰅾 Important",
highlight = "RenderMarkdownHint",
category = "github",
},
warning = {
raw = "[!WARNING]",
rendered = "󰀪 Warning",
highlight = "RenderMarkdownWarn",
category = "github",
},
caution = {
raw = "[!CAUTION]",
rendered = "󰳦 Caution",
highlight = "RenderMarkdownError",
category = "github",
},
-- Obsidian: https://help.obsidian.md/Editing+and+formatting/Callouts
abstract = {
raw = "[!ABSTRACT]",
rendered = "󰨸 Abstract",
highlight = "RenderMarkdownInfo",
category = "obsidian",
},
summary = {
raw = "[!SUMMARY]",
rendered = "󰨸 Summary",
highlight = "RenderMarkdownInfo",
category = "obsidian",
},
tldr = {
raw = "[!TLDR]",
rendered = "󰨸 Tldr",
highlight = "RenderMarkdownInfo",
category = "obsidian",
},
info = {
raw = "[!INFO]",
rendered = "󰋽 Info",
highlight = "RenderMarkdownInfo",
category = "obsidian",
},
todo = {
raw = "[!TODO]",
rendered = "󰗡 Todo",
highlight = "RenderMarkdownInfo",
category = "obsidian",
},
hint = {
raw = "[!HINT]",
rendered = "󰌶 Hint",
highlight = "RenderMarkdownSuccess",
category = "obsidian",
},
success = {
raw = "[!SUCCESS]",
rendered = "󰄬 Success",
highlight = "RenderMarkdownSuccess",
category = "obsidian",
},
check = {
raw = "[!CHECK]",
rendered = "󰄬 Check",
highlight = "RenderMarkdownSuccess",
category = "obsidian",
},
done = {
raw = "[!DONE]",
rendered = "󰄬 Done",
highlight = "RenderMarkdownSuccess",
category = "obsidian",
},
question = {
raw = "[!QUESTION]",
rendered = "󰘥 Question",
highlight = "RenderMarkdownWarn",
category = "obsidian",
},
help = {
raw = "[!HELP]",
rendered = "󰘥 Help",
highlight = "RenderMarkdownWarn",
category = "obsidian",
},
faq = {
raw = "[!FAQ]",
rendered = "󰘥 Faq",
highlight = "RenderMarkdownWarn",
category = "obsidian",
},
attention = {
raw = "[!ATTENTION]",
rendered = "󰀪 Attention",
highlight = "RenderMarkdownWarn",
category = "obsidian",
},
failure = {
raw = "[!FAILURE]",
rendered = "󰅖 Failure",
highlight = "RenderMarkdownError",
category = "obsidian",
},
fail = {
raw = "[!FAIL]",
rendered = "󰅖 Fail",
highlight = "RenderMarkdownError",
category = "obsidian",
},
missing = {
raw = "[!MISSING]",
rendered = "󰅖 Missing",
highlight = "RenderMarkdownError",
category = "obsidian",
},
danger = {
raw = "[!DANGER]",
rendered = "󱐌 Danger",
highlight = "RenderMarkdownError",
category = "obsidian",
},
error = {
raw = "[!ERROR]",
rendered = "󱐌 Error",
highlight = "RenderMarkdownError",
category = "obsidian",
},
bug = {
raw = "[!BUG]",
rendered = "󰨰 Bug",
highlight = "RenderMarkdownError",
category = "obsidian",
},
example = {
raw = "[!EXAMPLE]",
rendered = "󰉹 Example",
highlight = "RenderMarkdownHint",
category = "obsidian",
},
quote = {
raw = "[!QUOTE]",
rendered = "󱆨 Quote",
highlight = "RenderMarkdownQuote",
category = "obsidian",
},
cite = {
raw = "[!CITE]",
rendered = "󱆨 Cite",
highlight = "RenderMarkdownQuote",
category = "obsidian",
},
},
link = {
-- Turn on / off inline link icon rendering.
enabled = true,
-- Additional modes to render links.
render_modes = false,
-- How to handle footnote links, start with a '^'.
footnote = {
-- Turn on / off footnote rendering.
enabled = true,
-- Replace value with superscript equivalent.
superscript = true,
-- Added before link content.
prefix = "",
-- Added after link content.
suffix = "",
},
-- Inlined with 'image' elements.
image = "󰥶 ",
-- Inlined with 'email_autolink' elements.
email = "󰀓 ",
-- Fallback icon for 'inline_link' and 'uri_autolink' elements.
hyperlink = "󰌹 ",
-- Applies to the inlined icon as a fallback.
highlight = "RenderMarkdownLink",
-- Applies to WikiLink elements.
wiki = {
icon = "󱗖 ",
body = function()
return nil
end,
highlight = "RenderMarkdownWikiLink",
},
-- Define custom destination patterns so icons can quickly inform you of what a link
-- contains. Applies to 'inline_link', 'uri_autolink', and wikilink nodes. When multiple
-- patterns match a link the one with the longer pattern is used.
-- The key is for healthcheck and to allow users to change its values, value type below.
-- | pattern | matched against the destination text |
-- | icon | gets inlined before the link text |
-- | kind | optional determines how pattern is checked |
-- | | pattern | @see :h lua-patterns, is the default if not set |
-- | | suffix | @see :h vim.endswith() |
-- | priority | optional used when multiple match, uses pattern length if empty |
-- | highlight | optional highlight for 'icon', uses fallback highlight if empty |
custom = {
web = { pattern = "^http", icon = "󰖟 " },
discord = { pattern = "discord%.com", icon = "󰙯 " },
github = { pattern = "github%.com", icon = "󰊤 " },
gitlab = { pattern = "gitlab%.com", icon = "󰮠 " },
google = { pattern = "google%.com", icon = "󰊭 " },
neovim = { pattern = "neovim%.io", icon = "" },
reddit = { pattern = "reddit%.com", icon = "󰑍 " },
stackoverflow = { pattern = "stackoverflow%.com", icon = "󰓌 " },
wikipedia = { pattern = "wikipedia%.org", icon = "󰖬 " },
youtube = { pattern = "youtube%.com", icon = "󰗃 " },
},
},
sign = {
-- Turn on / off sign rendering.
enabled = true,
-- Applies to background of sign text.
highlight = "RenderMarkdownSign",
},
inline_highlight = {
-- Mimics Obsidian inline highlights when content is surrounded by double equals.
-- The equals on both ends are concealed and the inner content is highlighted.
-- Turn on / off inline highlight rendering.
enabled = true,
-- Additional modes to render inline highlights.
render_modes = false,
-- Applies to background of surrounded text.
highlight = "RenderMarkdownInlineHighlight",
},
indent = {
-- Mimic org-indent-mode behavior by indenting everything under a heading based on the
-- level of the heading. Indenting starts from level 2 headings onward by default.
-- Turn on / off org-indent-mode.
enabled = false,
-- Additional modes to render indents.
render_modes = false,
-- Amount of additional padding added for each heading level.
per_level = 2,
-- Heading levels <= this value will not be indented.
-- Use 0 to begin indenting from the very first level.
skip_level = 1,
-- Do not indent heading titles, only the body.
skip_heading = false,
-- Prefix added when indenting, one per level.
icon = "▎",
-- Priority to assign to extmarks.
priority = 0,
-- Applied to icon.
highlight = "RenderMarkdownIndent",
},
html = {
-- Turn on / off all HTML rendering.
enabled = true,
-- Additional modes to render HTML.
render_modes = false,
comment = {
-- Turn on / off HTML comment concealing.
conceal = true,
-- Optional text to inline before the concealed comment.
text = nil,
-- Highlight for the inlined text.
highlight = "RenderMarkdownHtmlComment",
},
-- HTML tags whose start and end will be hidden and icon shown.
-- The key is matched against the tag name, value type below.
-- | icon | gets inlined at the start |
-- | highlight | highlight for the icon |
tag = {},
},
win_options = {
-- Window options to use that change between rendered and raw view.
-- @see :h 'conceallevel'
conceallevel = {
-- Used when not being rendered, get user setting.
default = vim.o.conceallevel,
-- Used when being rendered, concealed text is completely hidden.
rendered = 3,
},
-- @see :h 'concealcursor'
concealcursor = {
-- Used when not being rendered, get user setting.
default = vim.o.concealcursor,
-- Used when being rendered, show concealed text in all modes.
rendered = "",
},
},
overrides = {
-- More granular configuration mechanism, allows different aspects of buffers to have their own
-- behavior. Values default to the top level configuration if no override is provided. Supports
-- the following fields:
-- enabled, max_file_size, debounce, render_modes, anti_conceal, padding, heading, paragraph,
-- code, dash, bullet, checkbox, quote, pipe_table, callout, link, sign, indent, latex, html,
-- win_options
-- Override for different buflisted values, @see :h 'buflisted'.
buflisted = {},
-- Override for different buftype values, @see :h 'buftype'.
buftype = {
nofile = {
render_modes = true,
padding = { highlight = "NormalFloat" },
sign = { enabled = false },
},
},
-- Override for different filetype values, @see :h 'filetype'.
filetype = {},
},
custom_handlers = {
-- Mapping from treesitter language to user defined handlers.
-- @see [Custom Handlers](doc/custom-handlers.md)
},
}
+25
View File
@@ -0,0 +1,25 @@
require "nvchad.mappings"
-- add yours here
local map = vim.keymap.set
map("n", "gd", vim.lsp.buf.definition, { desc = "Go to definition" })
map("n", "gD", "<cmd>Telescope lsp_definitions<CR>", { desc = "Go to Definitions" })
map("n", "grr", "<cmd>Telescope lsp_references<CR>", { desc = "Go to references" })
map("n", "<leader>da", ":lua vim.lsp.buf.code_action()<cr>", { desc = "Code actions", noremap = true, silent = true })
map("n", "<leader>dh", ":lua vim.diagnostic.open_float()<CR>", { desc = "Show diagnostics" })
map("n", "<leader>dj", function()
vim.diagnostic.jump { count = 1, float = true }
end, { desc = "Go to next" })
map("n", "<leader>dk", function()
vim.diagnostic.jump { count = -1, float = true }
end, { desc = "Go to previous" })
-- Telescope
map("n", "<leader>fr", ":Telescope resume<CR>", { desc = "Resume last search" })
map("n", "<leader>fs", ":Telescope grep_string<CR>", { desc = "Find selected string" })
map("n", "<leader>fk", ":Telescope keymaps<CR>", { desc = "Find keymaps" })
map("n", "<leader>fd", ":Telescope diagnostics<CR>", { desc = "Diagnostics" })
-- Remaps
map({ "n", "v" }, "x", '"_x', { desc = "Delete char without yanking" })
map({ "n", "v" }, "c", '"_c', { desc = "Change without yanking" })
+6
View File
@@ -0,0 +1,6 @@
require "nvchad.options"
-- add yours here!
-- local o = vim.o
-- o.cursorlineopt ='both' -- to enable cursorline!
+107
View File
@@ -0,0 +1,107 @@
return {
{
"stevearc/conform.nvim",
event = "BufWritePre", -- uncomment for format on save
opts = require "configs.conform",
},
{
"neovim/nvim-lspconfig",
config = function()
require "configs.lspconfig"
end,
},
{
"nvim-treesitter/nvim-treesitter",
branch = "main",
opts = {
ensure_installed = {
"vim",
"vimdoc",
"lua",
"luadoc",
"printf",
"html",
"css",
"typescript",
"javascript",
"markdown",
"scss",
"svelte",
"typst",
"vue",
"regex",
},
},
-- On the main branch nothing acts on `ensure_installed` at startup: setup() takes only
-- install_dir, and NvChad's :TSInstallAll (which does read this list off the lazy spec)
-- only runs from `build`, i.e. when the plugin is installed or updated. So a language
-- added here stayed uninstalled until the next rebuild — 9 of these 15 were missing,
-- silently falling back to regex highlighting. Install whatever is absent, once, here.
config = function(_, opts)
local ts = require "nvim-treesitter"
ts.setup()
local have = {}
for _, lang in ipairs(ts.get_installed()) do
have[lang] = true
end
local missing = vim.tbl_filter(function(lang)
return not have[lang]
end, opts.ensure_installed or {})
if #missing > 0 then
ts.install(missing) -- async; highlighting picks each up as it lands
end
end,
},
{
"MeanderingProgrammer/render-markdown.nvim",
ft = { "markdown", "gitcommit" },
opts = function()
return require "configs.render-markdown"
end,
},
-- snacks.indent (below) draws the indent guides — disable NvChad's indent-blankline
-- so they don't render doubled
{ "lukas-reineke/indent-blankline.nvim", enabled = false },
{
"folke/snacks.nvim",
priority = 1000,
lazy = false,
---@type snacks.Config
opts = {
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
bigfile = { enabled = false },
dashboard = { enabled = false },
explorer = { enabled = true },
indent = { enabled = true },
input = { enabled = true },
picker = { enabled = true },
notifier = { enabled = true },
quickfile = { enabled = true },
scope = { enabled = true },
scroll = { enabled = true },
statuscolumn = { enabled = true },
words = { enabled = true },
},
},
-- These are some examples, uncomment them if you want to see them work!
--
-- {
-- "nvim-treesitter/nvim-treesitter",
-- opts = {
-- ensure_installed = {
-- "vim", "lua", "vimdoc",
-- "html", "css"
-- },
-- },
-- },
--
}
+74
View File
@@ -0,0 +1,74 @@
# opencode config
Config tree for [opencode](https://opencode.ai) (2.x), tuned for **small local models** behind a
llama.cpp router. Stowed into `~/.config/opencode/` as per-file symlinks; editing here edits the live
config (restart opencode, or `opencode service restart`, to pick changes up — the 2.x background
service caches config).
## Layout
| Path | What |
|---|---|
| `opencode.json` | Providers, permissions, primary agents, defaults. Written in the v1 schema, which 2.x still accepts. |
| `openai-gpt.jsonc` | Optional GPT/Codex OAuth overlay (OpenAI provider + `opencode-openai-codex-auth` plugin). Not loaded by itself — see *GPT overlay*. |
| `AGENTS.md` | Global rules prepended to every session. Same text as the pi config's `AGENTS.md`: terse, verify-before-asserting, small-model friendly. |
| `agents/*.md` | Four subagents with real prompts and scoped permissions: `code-reviewer`, `test-runner` (hidden), `doc-writer` (edits docs only), `security-auditor` (hidden). |
| `commands/*.md` | `/commit` (Conventional Commits message, never commits) and `/review` (read-only diff review), both on the `plan` agent. |
| `plugins/verbose/` | 2.x TUI plugin: `<leader>v`, `/verbose`, or the palette entry toggles the *verbose view* — thinking blocks expanded and tool calls ungrouped — reading the live state from the built-in toggles so a mixed state converges. `server.ts` is a no-op half required by the loader. |
| `plugins/agent-state.ts` | Server-side plugin: mirrors the session state (`message.updated` user → busy, `permission.asked` → input, `session.idle` → done, `session.error` → error) into the tmux pane opencode runs in via `~/.config/tmux/scripts/agent-state.sh`, for the status-bar agent badges. Skips child sessions; only right when the TUI in the pane spawned the server (not `serve`/`attach`); under `opencodes` (bwrap) the tmux socket dir must be bound in. |
| `themes/catppuccin-mocha.json` | Catppuccin Mocha (dark) / Latte (light) theme following the pi theme's semantic mapping. Built-in `catppuccin` exists too; this one matches pi. |
| `tui.json` | TUI settings in the v1 schema (2.x compat): theme, leader timeout, stacked diffs, block cursor, attention notifications, a few extra keybinds. |
The sandbox wrapper lives in `../fish/functions/opencodes.fish`: `opencodes` runs opencode under
bwrap with the stowed config dirs, `~/.cache/opencode`, state and data bound, and only the needed
environment passed through. Extra arguments go to opencode.
## Providers and models
Two OpenAI-compatible providers point at the same llama.cpp router: `llama.cpp` on the LAN and
`duskadiy` through the public hostname (`apiKey` from `$DUSKADIY_API_KEY`). Model ids are the preset
section names in `fl/.config/llamacpp/config.ini`; keep the lists in sync with it and with the pi and
aichat configs. Both providers use a one-hour request timeout — the default five minutes cut off
long local replies.
Decisions that look odd but are deliberate:
- **No `small_model`.** The router runs `--models-max 1`; any second model id evicts the resident one.
With `small_model` unset, title generation falls back to the session's model. Subagents carry no
pinned model for the same reason — the task tool uses the caller's model.
- **No `temperature` / `top_p` from opencode.** Verified by capturing request bodies: only
`max_tokens` is sent, so the router presets own sampling.
- **`reasoning: true`** only on the presets that actually think (no `reasoning-budget = 0`);
GLM also replays `reasoning_content` in history because its preset sets `reasoning-preserve`.
- **`snapshot: false`** — file-change undo is not used. **`tool_output`** capped at 200 lines /
16 KiB for 24k-context models. **`compaction.reserved`/`prune`** are inert at this context size.
- **`question: allow`** everywhere so agents ask instead of guessing.
## Agents
`auto` is the default agent and cycles with `build` and `plan` on Tab. It runs without prompts except
for the serious set — git history rewriting and pushing, `rm`, killing processes, `systemctl`,
network transfers, package installs — which ask, and `sudo`/`dd`/`mkfs`/secret-file reads, which are
denied. Colors: build primary, plan info, auto yellow. All three cap agentic iterations at 30.
Permission rules resolve **global first, agent rules appended, last match wins**, so an agent that
wants a blanket rule must restate its own denies after it (the `auto` block does).
## GPT overlay
`openai-gpt.jsonc` is a template. opencode 2.x ignores `OPENCODE_CONFIG`, but it merges a second
global file named `opencode.jsonc`. `fish/config.fish` links `opencode.jsonc → openai-gpt.jsonc`
only on a host whose `~/.local/share/opencode/auth.json` holds an OpenAI credential (from
`opencode auth login`), and removes the link again when the login is gone.
## Host overlays
`lw/.config/opencode/opencode.json` is a fork of the common file that adds the laptop's local CPU
llama.cpp provider (`lwcpp`). Mirror every edit between the two.
## Lifting pieces into a stock opencode
Everything is plain files: copy `agents/`, `commands/`, `plugins/verbose/` or the theme into your own
`~/.config/opencode/`. The plugin needs 2.x (it uses the `keymap.layer` / `dispatch` API and is
discovered as a directory under `plugins/`). The permission blocks in `opencode.json` are independent
of the providers and can be pasted as-is.
@@ -0,0 +1,11 @@
---
description: Write a Conventional Commits message for the staged changes (does not commit)
agent: plan
---
Inspect the staged changes with `git diff --cached` (and `git status` for context). Then write a single Conventional Commits message:
- A `<type>(<scope>): <subject>` summary line, imperative mood, ≤72 chars (types: feat, fix, refactor, docs, chore, test, perf, build).
- An optional short body explaining the *why* only when it isn't obvious from the diff.
- Do NOT run `git commit`. Output only the message inside a code block so I can review it.
Extra context from me, if any: $ARGUMENTS
@@ -0,0 +1,14 @@
---
description: Review the current diff (staged + unstaged) for bugs and issues, read-only
agent: plan
---
Review the current changes. Check both `git diff` (unstaged) and `git diff --cached` (staged). Focus on:
- Correctness and logic bugs
- Error handling and missing edge cases
- Security issues (injection, secrets, unsafe input)
- Anything that doesn't match the surrounding code's conventions
List concrete findings as `file:line — issue — suggested fix`, ordered by severity. Be concise; skip praise. If nothing is wrong, say so.
Extra focus this round, if any (default: general correctness): $ARGUMENTS
+247
View File
@@ -0,0 +1,247 @@
{
"$schema": "https://opencode.ai/config.json",
"plugin": [
"opencode-openai-codex-auth"
],
"provider": {
"openai": {
"options": {
"reasoningEffort": "medium",
"reasoningSummary": "auto",
"textVerbosity": "medium",
"include": [
"reasoning.encrypted_content"
],
"store": false
},
"whitelist": [
"gpt-5.2",
"gpt-5.2-codex",
"gpt-5.1-codex-max",
"gpt-5.1-codex",
"gpt-5.1-codex-mini",
"gpt-5.1"
],
"models": {
"gpt-5.2": {
"name": "GPT 5.2 (OAuth)",
"limit": {
"context": 272000,
"output": 128000
},
"modalities": {
"input": [
"text",
"image"
],
"output": [
"text"
]
},
"variants": {
"none": {
"reasoningEffort": "none",
"reasoningSummary": "auto",
"textVerbosity": "medium"
},
"low": {
"reasoningEffort": "low",
"reasoningSummary": "auto",
"textVerbosity": "medium"
},
"medium": {
"reasoningEffort": "medium",
"reasoningSummary": "auto",
"textVerbosity": "medium"
},
"high": {
"reasoningEffort": "high",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
},
"xhigh": {
"reasoningEffort": "xhigh",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
}
}
},
"gpt-5.2-codex": {
"name": "GPT 5.2 Codex (OAuth)",
"limit": {
"context": 272000,
"output": 128000
},
"modalities": {
"input": [
"text",
"image"
],
"output": [
"text"
]
},
"variants": {
"low": {
"reasoningEffort": "low",
"reasoningSummary": "auto",
"textVerbosity": "medium"
},
"medium": {
"reasoningEffort": "medium",
"reasoningSummary": "auto",
"textVerbosity": "medium"
},
"high": {
"reasoningEffort": "high",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
},
"xhigh": {
"reasoningEffort": "xhigh",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
}
}
},
"gpt-5.1-codex-max": {
"name": "GPT 5.1 Codex Max (OAuth)",
"limit": {
"context": 272000,
"output": 128000
},
"modalities": {
"input": [
"text",
"image"
],
"output": [
"text"
]
},
"variants": {
"low": {
"reasoningEffort": "low",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
},
"medium": {
"reasoningEffort": "medium",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
},
"high": {
"reasoningEffort": "high",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
},
"xhigh": {
"reasoningEffort": "xhigh",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
}
}
},
"gpt-5.1-codex": {
"name": "GPT 5.1 Codex (OAuth)",
"limit": {
"context": 272000,
"output": 128000
},
"modalities": {
"input": [
"text",
"image"
],
"output": [
"text"
]
},
"variants": {
"low": {
"reasoningEffort": "low",
"reasoningSummary": "auto",
"textVerbosity": "medium"
},
"medium": {
"reasoningEffort": "medium",
"reasoningSummary": "auto",
"textVerbosity": "medium"
},
"high": {
"reasoningEffort": "high",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
}
}
},
"gpt-5.1-codex-mini": {
"name": "GPT 5.1 Codex Mini (OAuth)",
"limit": {
"context": 272000,
"output": 128000
},
"modalities": {
"input": [
"text",
"image"
],
"output": [
"text"
]
},
"variants": {
"medium": {
"reasoningEffort": "medium",
"reasoningSummary": "auto",
"textVerbosity": "medium"
},
"high": {
"reasoningEffort": "high",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
}
}
},
"gpt-5.1": {
"name": "GPT 5.1 (OAuth)",
"limit": {
"context": 272000,
"output": 128000
},
"modalities": {
"input": [
"text",
"image"
],
"output": [
"text"
]
},
"variants": {
"none": {
"reasoningEffort": "none",
"reasoningSummary": "auto",
"textVerbosity": "medium"
},
"low": {
"reasoningEffort": "low",
"reasoningSummary": "auto",
"textVerbosity": "low"
},
"medium": {
"reasoningEffort": "medium",
"reasoningSummary": "auto",
"textVerbosity": "medium"
},
"high": {
"reasoningEffort": "high",
"reasoningSummary": "detailed",
"textVerbosity": "high"
}
}
}
}
}
}
}
+313
View File
@@ -0,0 +1,313 @@
{
"$schema": "https://opencode.ai/config.json",
"model": "llama.cpp/Qwen3.6-35B-A3B-Thinking",
"default_agent": "auto",
"instructions": ["CLAUDE.md", "AGENTS.md"],
"share": "disabled",
"autoupdate": "notify",
"tool_output": { "max_lines": 200, "max_bytes": 16384 },
"snapshot": false,
"disabled_providers": [
"gemini",
"anthropic",
"groq",
"openrouter",
"opencode"
],
"permission": {
"edit": "deny",
"webfetch": "ask",
"websearch": "ask",
"external_directory": "ask",
"question": "allow",
"read": {
"*": "allow",
"**/.env*": "deny",
"**/*.env": "deny",
"**/*.pem": "deny",
"**/*.key": "deny",
"**/*.p12": "deny",
"**/*.pfx": "deny",
"**/*.keystore": "deny",
"**/id_rsa*": "deny",
"**/.ssh/**": "deny",
"**/.aws/**": "deny",
"**/.npmrc": "deny",
"**/.netrc": "deny"
},
"bash": {
"*": "ask",
"ls *": "allow",
"cat *": "allow",
"grep *": "allow",
"rg *": "allow",
"find *": "allow",
"fd *": "allow",
"which *": "allow",
"file *": "allow",
"stat *": "allow",
"wc *": "allow",
"tree *": "allow",
"diff *": "allow",
"sort *": "allow",
"uniq *": "allow",
"echo *": "ask",
"pwd": "allow",
"date": "allow",
"whoami": "allow",
"jq *": "allow",
"tsc *": "allow",
"mkdir *": "ask",
"touch *": "ask",
"git *": "ask",
"git status": "allow",
"git status *": "allow",
"git diff": "allow",
"git diff *": "allow",
"git log": "allow",
"git log *": "allow",
"git show *": "allow",
"git branch": "allow",
"git remote -v": "allow",
"npm *": "ask",
"pnpm *": "ask",
"npx *": "ask",
"npm list": "allow",
"npm help": "allow",
"npm version": "allow",
"pnpm list": "allow",
"pnpm help": "allow",
"npx --version": "allow",
"curl *": "ask",
"wget *": "ask",
"rm *": "deny",
"rmdir *": "deny",
"dd *": "deny",
"mkfs*": "deny",
"shred *": "deny",
"chmod -R *": "deny",
"sudo *": "deny",
"doas *": "deny",
"npm install*": "deny",
"npm i": "deny",
"npm i *": "deny",
"npm ci*": "deny",
"pnpm install*": "deny",
"pnpm i": "deny",
"pnpm i *": "deny",
"pnpm add*": "deny",
"yarn add*": "deny",
"yarn install*": "deny",
"pip install*": "deny",
"pip3 install*": "deny",
"pipx install*": "deny",
"cargo install*": "deny",
"go install*": "deny",
"gem install*": "deny",
"brew install*": "deny",
"pacman *": "deny",
"yay *": "deny",
"apt *": "deny",
"apt-get *": "deny",
"dnf *": "deny",
"cat .env*": "deny",
"cat *.env": "deny",
"cat *.pem": "deny",
"cat *.key": "deny",
"cat *id_rsa*": "deny",
"cat *secret*": "deny",
"cat *credential*": "deny",
"cat ~/.ssh/*": "deny",
"cat ~/.aws/*": "deny",
"grep .env*": "deny",
"grep * .env*": "deny"
}
},
"provider": {
"duskadiy": {
"npm": "@ai-sdk/openai-compatible",
"name": "DuskaDIY",
"options": {
"baseURL": "https://llm.duskadiy.com/api/v1",
"apiKey": "{env:DUSKADIY_API_KEY}",
"timeout": 3600000
},
"models": {
"Qwen3-Coder-30B-Instruct-UD-Q3_K_XL": { "name": "Qwen3 Coder 30B · 32k — main agent coder (~30 t/s, remote)", "limit": { "context": 32768, "output": 4096 } },
"Qwen3-Coder-Next-UD-IQ3_XXS": { "name": "Qwen3 Coder Next 80B · 128k — long sessions (~16 t/s, remote)", "limit": { "context": 131072, "output": 16384 } },
"Qwen3.6-35B-A3B-MTP-UD-IQ3_XXS": { "name": "Qwen3.6 35B · 24k · vision — daily driver (~36 t/s, remote)", "attachment": true, "limit": { "context": 24576, "output": 8192 } },
"Qwen3.6-35B-A3B-Thinking": { "reasoning": true, "name": "Qwen3.6 35B Thinking · 24k · vision — hard problems (~39 t/s, remote)", "attachment": true, "limit": { "context": 24576, "output": 8192 } },
"Qwen3.5-9B-UD-Q6_K_XL": { "reasoning": true, "name": "Qwen3.5 9B · 32k · vision — quick tasks (~32 t/s, remote)", "attachment": true, "limit": { "context": 32768, "output": 8192 } },
"Qwen3.8-27B-UD-IQ3_XXS": { "reasoning": true, "name": "Qwen3.8 27B · 24k · vision — hybrid reasoner, quiet desktop only (~15 t/s, remote)", "attachment": true, "limit": { "context": 24576, "output": 8192 } },
"gemma-4-26B-A4B-it-UD-IQ4_XS": { "name": "Gemma 4 26B · 24k · vision — quality generalist (~34 t/s, remote)", "attachment": true, "limit": { "context": 24576, "output": 4096 } },
"gemma-4-E4B-it-UD-Q8_K_XL": { "name": "Gemma 4 E4B · 64k · vision — fast generalist, long docs (~57 t/s, remote)", "attachment": true, "limit": { "context": 65536, "output": 16384 } },
"GLM-4.7-Flash-UD-Q4_K_XL": { "reasoning": true, "interleaved": "reasoning_content", "name": "GLM-4.7 Flash · 24k — quality coder (~21 t/s, remote)", "limit": { "context": 24576, "output": 8192 } },
"GLM-4.7-Flash-UD-Q3_K_XL": { "reasoning": true, "interleaved": "reasoning_content", "name": "GLM-4.7 Flash Q3 · 24k — fast coder (~28 t/s, remote)", "limit": { "context": 24576, "output": 8192 } },
"Ornith-1.5-35B-A3B-IQ3_XXS": { "reasoning": true, "name": "Ornith 1.5 35B · 32k · vision — agentic coder, thinking (~32 t/s, remote)", "attachment": true, "limit": { "context": 32768, "output": 8192 } },
"gpt-oss-20b": { "reasoning": true, "name": "gpt-oss 20B · 64k — fast reasoning + tools (~38 t/s, remote)", "limit": { "context": 65536, "output": 8192 } },
"gpt-oss-20b-low": { "reasoning": true, "name": "gpt-oss 20B low · 64k — snappy answers (~37 t/s, remote)", "limit": { "context": 65536, "output": 8192 } }
}
},
"llama.cpp": {
"npm": "@ai-sdk/openai-compatible",
"name": "llamacpp",
"options": {
"baseURL": "http://192.168.0.204:11343/v1",
"timeout": 3600000
},
"models": {
"Qwen3-Coder-Next-UD-IQ3_XXS": { "name": "Qwen3 Coder Next 80B · 128k — long sessions (~16 t/s)", "limit": { "context": 131072, "output": 16384 } },
"Qwen3-Coder-30B-Instruct-UD-Q3_K_XL": { "name": "Qwen3 Coder 30B · 32k — main agent coder (~30 t/s)", "limit": { "context": 32768, "output": 4096 } },
"Qwen3.6-35B-A3B-MTP-UD-IQ3_XXS": { "name": "Qwen3.6 35B · 24k · vision — daily driver (~36 t/s)", "attachment": true, "limit": { "context": 24576, "output": 8192 } },
"Qwen3.6-35B-A3B-Thinking": { "reasoning": true, "name": "Qwen3.6 35B Thinking · 24k · vision — hard problems (~39 t/s)", "attachment": true, "limit": { "context": 24576, "output": 8192 } },
"Qwen3.5-9B-UD-Q6_K_XL": { "reasoning": true, "name": "Qwen3.5 9B · 32k · vision — quick tasks (~32 t/s)", "attachment": true, "limit": { "context": 32768, "output": 8192 } },
"Qwen3.8-27B-UD-IQ3_XXS": { "reasoning": true, "name": "Qwen3.8 27B · 24k · vision — hybrid reasoner, quiet desktop only (~15 t/s)", "attachment": true, "limit": { "context": 24576, "output": 8192 } },
"gemma-4-26B-A4B-it-UD-IQ4_XS": { "name": "Gemma 4 26B · 24k · vision — quality generalist (~34 t/s)", "attachment": true, "limit": { "context": 24576, "output": 4096 } },
"gemma-4-E4B-it-UD-Q8_K_XL": { "name": "Gemma 4 E4B · 64k · vision — fast generalist, long docs (~57 t/s)", "attachment": true, "limit": { "context": 65536, "output": 16384 } },
"GLM-4.7-Flash-UD-Q4_K_XL": { "reasoning": true, "interleaved": "reasoning_content", "name": "GLM-4.7 Flash · 24k — quality coder (~21 t/s)", "limit": { "context": 24576, "output": 8192 } },
"GLM-4.7-Flash-UD-Q3_K_XL": { "reasoning": true, "interleaved": "reasoning_content", "name": "GLM-4.7 Flash Q3 · 24k — fast coder (~28 t/s)", "limit": { "context": 24576, "output": 8192 } },
"Ornith-1.5-35B-A3B-IQ3_XXS": { "reasoning": true, "name": "Ornith 1.5 35B · 32k · vision — agentic coder, thinking (~32 t/s)", "attachment": true, "limit": { "context": 32768, "output": 8192 } },
"gpt-oss-20b": { "reasoning": true, "name": "gpt-oss 20B · 64k — fast reasoning + tools (~38 t/s)", "limit": { "context": 65536, "output": 8192 } },
"gpt-oss-20b-low": { "reasoning": true, "name": "gpt-oss 20B low · 64k — snappy answers (~37 t/s)", "limit": { "context": 65536, "output": 8192 } }
}
}
},
"agent": {
"plan": {
"mode": "primary",
"color": "info",
"steps": 30,
"model": "llama.cpp/Qwen3.6-35B-A3B-Thinking",
"permission": {
"edit": "deny"
}
},
"build": {
"mode": "primary",
"color": "primary",
"steps": 30,
"model": "llama.cpp/Qwen3.6-35B-A3B-Thinking",
"permission": {
"edit": {
"*": "allow",
"**/.env*": "deny",
"**/*.env": "deny",
"**/*.pem": "deny",
"**/*.key": "deny",
"**/id_rsa*": "deny",
"**/.ssh/**": "deny",
"**/.aws/**": "deny",
"**/.git/**": "deny",
"**/.npmrc": "deny",
"**/.netrc": "deny"
}
}
},
"auto": {
"description": "Auto mode: acts without asking; only irreversible or outward-facing actions ask",
"mode": "primary",
"color": "#f9e2af",
"steps": 30,
"model": "llama.cpp/Qwen3.6-35B-A3B-Thinking",
"permission": {
"edit": {
"*": "allow",
"**/.env*": "deny",
"**/*.env": "deny",
"**/*.pem": "deny",
"**/*.key": "deny",
"**/id_rsa*": "deny",
"**/.ssh/**": "deny",
"**/.aws/**": "deny",
"**/.git/**": "deny",
"**/.npmrc": "deny",
"**/.netrc": "deny"
},
"webfetch": "allow",
"websearch": "allow",
"external_directory": "ask",
"question": "allow",
"bash": {
"*": "allow",
"git *": "allow",
"git commit*": "ask",
"git push*": "ask",
"git reset*": "ask",
"git checkout*": "ask",
"git switch*": "ask",
"git restore*": "ask",
"git rebase*": "ask",
"git merge*": "ask",
"git cherry-pick*": "ask",
"git stash*": "ask",
"git clean*": "ask",
"git branch -*": "ask",
"git tag*": "ask",
"git remote add*": "ask",
"git remote remove*": "ask",
"git remote set-url*": "ask",
"rm *": "ask",
"rmdir *": "ask",
"kill *": "ask",
"pkill *": "ask",
"killall *": "ask",
"systemctl *": "ask",
"curl *": "ask",
"wget *": "ask",
"ssh *": "ask",
"scp *": "ask",
"rsync *": "ask",
"npm install*": "ask",
"npm i": "ask",
"npm i *": "ask",
"npm ci*": "ask",
"pnpm install*": "ask",
"pnpm i": "ask",
"pnpm i *": "ask",
"pnpm add*": "ask",
"yarn add*": "ask",
"yarn install*": "ask",
"pip install*": "ask",
"pip3 install*": "ask",
"pipx install*": "ask",
"cargo install*": "ask",
"go install*": "ask",
"gem install*": "ask",
"yay *": "ask",
"sudo *": "deny",
"doas *": "deny",
"dd *": "deny",
"mkfs*": "deny",
"shred *": "deny",
"chmod -R *": "deny",
"rm -rf /*": "deny",
"rm -rf ~*": "deny",
"cat .env*": "deny",
"cat *.env": "deny",
"cat *.pem": "deny",
"cat *.key": "deny",
"cat *id_rsa*": "deny",
"cat *secret*": "deny",
"cat *credential*": "deny",
"cat ~/.ssh/*": "deny",
"cat ~/.aws/*": "deny",
"grep .env*": "deny",
"grep * .env*": "deny"
}
}
}
}
}
@@ -0,0 +1,53 @@
// opencode agent-state plugin: mirrors the session state into the tmux pane opencode runs in via
// ~/.config/tmux/scripts/agent-state.sh (oc busy|done|input|error). No-op outside tmux.
//
// Runs in the SERVER process, so TMUX_PANE is only right when the TUI in the pane spawned the
// server (plain `opencode`), not for `opencode serve` / `opencode attach`. Under the bwrap
// `opencodes` wrapper the tmux socket dir must be bound in, or the script gives up quietly.
// Child (subagent) sessions are skipped so a subagent finishing does not flag "done".
import type { Plugin } from "@opencode-ai/plugin"
export const AgentState: Plugin = async ({ client, $ }) => {
const script = `${process.env.HOME}/.config/tmux/scripts/agent-state.sh`
const set = async (state: string) => {
if (!process.env.TMUX_PANE) return
try {
await $`${script} oc ${state}`.quiet().nothrow()
} catch {}
}
const childCache = new Map<string, boolean>()
const isChild = async (sessionID?: string) => {
if (!sessionID) return false
if (!childCache.has(sessionID)) {
try {
const r = await client.session.get({ path: { id: sessionID } })
childCache.set(sessionID, Boolean(r.data?.parentID))
} catch {
childCache.set(sessionID, false)
}
}
return childCache.get(sessionID) ?? false
}
return {
event: async ({ event }) => {
const p = (event as { properties?: Record<string, any> }).properties ?? {}
switch (event.type) {
case "message.updated": // a new user message = a prompt went in
if (p.info?.role === "user" && !(await isChild(p.info?.sessionID))) await set("busy")
break
case "permission.asked":
if (!(await isChild(p.sessionID))) await set("input")
break
case "permission.replied":
if (!(await isChild(p.sessionID))) await set("busy")
break
case "session.idle":
if (!(await isChild(p.sessionID))) await set("done")
break
case "session.error":
if (!(await isChild(p.sessionID))) await set("error")
break
}
},
}
}
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff. Show more