gabriel / muse public
muse.plugin.zsh
293 lines 12.2 KB
13c730d5 fix(zsh-plugin): add unconditional verbose logs at every dirty-check step Gabriel Cardona <gabriel@tellurstori.com> 3d ago
1 # muse.plugin.zsh — Oh My ZSH plugin for Muse version control
2 # ==============================================================================
3 # Minimal, secure shell integration. Shows domain + branch in your prompt.
4 # Nothing else runs automatically; everything else is a muse command away.
5 #
6 # Setup (after running tools/install-omzsh-plugin.sh):
7 # Add $(muse_prompt_info) to your PROMPT in ~/.zshrc, e.g.:
8 # PROMPT='%~ $(muse_prompt_info) %# '
9 #
10 # Configuration (set in ~/.zshrc BEFORE plugins=(… muse …)):
11 # MUSE_PROMPT_ICONS=1 Use emoji icons; set 0 for plain ASCII (default 1)
12 # MUSE_DIRTY_TIMEOUT=1 Seconds before dirty-check gives up (default 1)
13 #
14 # Security notes:
15 # - No eval of any data read from disk or env.
16 # - Branch names are regex-validated and %-escaped before prompt display.
17 # - Domain name is validated as alphanumeric before use.
18 # - All repo paths passed to subprocesses via env vars (not -c strings).
19 # - Dirty check runs only after a muse command, never on every keystroke.
20 # - Zero subprocesses on prompt render; one python3 on directory change.
21 # ==============================================================================
22
23 autoload -Uz is-at-least
24 if ! is-at-least 5.0; then
25 print "[muse] ZSH 5.0+ required. Plugin not loaded." >&2
26 return 1
27 fi
28
29 # ── Configuration ─────────────────────────────────────────────────────────────
30 : ${MUSE_PROMPT_ICONS:=0}
31 : ${MUSE_DIRTY_TIMEOUT:=5}
32 : ${MUSE_DEBUG:=0} # set to 1 to print timestamped trace to stderr
33
34 # Domain icon map. Override individual elements in ~/.zshrc before plugins=().
35 typeset -gA MUSE_DOMAIN_ICONS
36 MUSE_DOMAIN_ICONS=(
37 midi "♪"
38 code "⌥"
39 bitcoin "₿"
40 scaffold "⬡"
41 _default "◈"
42 )
43
44 # ── Internal state ────────────────────────────────────────────────────────────
45 typeset -g MUSE_REPO_ROOT="" # absolute path to repo root, or ""
46 typeset -g MUSE_DOMAIN="midi" # active domain plugin name
47 typeset -g MUSE_BRANCH="" # branch name, 8-char SHA, or "?"
48 typeset -gi MUSE_DIRTY=0 # 1 when working tree has uncommitted changes
49 typeset -gi MUSE_DIRTY_COUNT=0 # number of changed paths
50 typeset -gi _MUSE_CMD_RAN=0 # 1 after any muse command runs
51
52 # ── §1 Core detection (zero subprocesses) ───────────────────────────────────
53
54 # Walk up from $PWD to find a valid Muse repo root. Sets MUSE_REPO_ROOT.
55 # A valid repo requires .muse/repo.json — a bare .muse/ directory is not
56 # enough. This prevents false positives from stray or partial .muse/ dirs
57 # (e.g. a forgotten muse init in a parent directory).
58 function _muse_find_root() {
59 local dir="$PWD"
60 while [[ "$dir" != "/" ]]; do
61 if [[ -f "$dir/.muse/repo.json" ]]; then
62 MUSE_REPO_ROOT="$dir"
63 return 0
64 fi
65 dir="${dir:h}"
66 done
67 MUSE_REPO_ROOT=""
68 return 1
69 }
70
71 # Read branch from .muse/HEAD without forking. Validates before storing.
72 # Branch names are restricted to [a-zA-Z0-9/_.-] to prevent prompt injection.
73 #
74 # Muse HEAD format (canonical, written by muse/core/store.py):
75 # ref: refs/heads/<branch> — on a branch (symbolic ref)
76 # commit: <sha256> — detached HEAD (direct commit reference)
77 function _muse_parse_head() {
78 local head_file="$MUSE_REPO_ROOT/.muse/HEAD"
79 if [[ ! -f "$head_file" ]]; then
80 MUSE_BRANCH=""; return 1
81 fi
82 local raw
83 raw=$(<"$head_file")
84 if [[ "$raw" == "ref: refs/heads/"* ]]; then
85 local branch="${raw#ref: refs/heads/}"
86 # Reject anything that could inject prompt escapes or path components.
87 if [[ "$branch" =~ '^[[:alnum:]/_.-]+$' ]]; then
88 MUSE_BRANCH="$branch"
89 else
90 MUSE_BRANCH="?"
91 fi
92 elif [[ "$raw" == "commit: "* ]]; then
93 local sha="${raw#commit: }"
94 MUSE_BRANCH="${sha:0:8}" # detached HEAD — show short SHA
95 else
96 MUSE_BRANCH="?"
97 fi
98 }
99
100 # Read domain from .muse/repo.json. One python3 call; path via env var only.
101 function _muse_parse_domain() {
102 local repo_json="$MUSE_REPO_ROOT/.muse/repo.json"
103 if [[ ! -f "$repo_json" ]]; then
104 MUSE_DOMAIN="midi"; return
105 fi
106 MUSE_DOMAIN=$(MUSE_REPO_JSON="$repo_json" python3 <<'PYEOF' 2>/dev/null
107 import json, os
108 try:
109 d = json.load(open(os.environ['MUSE_REPO_JSON']))
110 v = str(d.get('domain', 'midi'))
111 # Accept only safe domain names: alphanumeric plus hyphens/underscores,
112 # max 32 chars. Anything else falls back to 'midi'.
113 safe = v.replace('-', '').replace('_', '')
114 print(v if (safe.isalnum() and 1 <= len(v) <= 32) else 'midi')
115 except Exception:
116 print('midi')
117 PYEOF
118 )
119 : ${MUSE_DOMAIN:=midi}
120 }
121
122 # Check dirty state. Runs with timeout; called on cd, shell load, and after
123 # any muse command. MUSE_DIRTY_TIMEOUT (default 5s) caps the wait.
124 typeset -gi _MUSE_LAST_DIRTY_RC=0 # last exit code from the dirty check subprocess
125
126 function _muse_check_dirty() {
127 local output rc count=0
128 print "[dirty:1] called. MUSE_REPO_ROOT=$MUSE_REPO_ROOT MUSE_BRANCH=$MUSE_BRANCH" >&2
129 output=$(cd -- "$MUSE_REPO_ROOT" && \
130 timeout -- "${MUSE_DIRTY_TIMEOUT}" muse status --porcelain 2>/dev/null)
131 rc=$?
132 _MUSE_LAST_DIRTY_RC=$rc
133 print "[dirty:2] rc=$rc output='$output'" >&2
134 if (( rc == 124 )); then
135 print "[dirty:3] TIMEOUT. MUSE_DIRTY unchanged=$MUSE_DIRTY" >&2
136 return
137 fi
138 while IFS= read -r line; do
139 [[ "$line" == "##"* || -z "$line" ]] && continue
140 (( count++ ))
141 done <<< "$output"
142 MUSE_DIRTY=$(( count > 0 ? 1 : 0 ))
143 MUSE_DIRTY_COUNT=$count
144 print "[dirty:4] MUSE_DIRTY=$MUSE_DIRTY count=$count" >&2
145 }
146
147 # ── §2 Cache management ──────────────────────────────────────────────────────
148
149 # Full refresh: head + domain + dirty. Called on directory change and on load.
150 # One muse subprocess (status --porcelain) runs every time — same model as the
151 # git plugin. The timeout in _muse_check_dirty keeps it bounded.
152 function _muse_refresh() {
153 print "[refresh:1] start PWD=$PWD" >&2
154 if ! _muse_find_root; then
155 MUSE_DOMAIN="midi"; MUSE_BRANCH=""; MUSE_DIRTY=0; MUSE_DIRTY_COUNT=0
156 print "[refresh:2] no repo found — cleared state" >&2
157 return 1
158 fi
159 print "[refresh:3] root=$MUSE_REPO_ROOT" >&2
160 _muse_parse_head
161 print "[refresh:4] branch=$MUSE_BRANCH" >&2
162 _muse_parse_domain
163 print "[refresh:5] domain=$MUSE_DOMAIN" >&2
164 _muse_check_dirty
165 print "[refresh:6] done. dirty=$MUSE_DIRTY count=$MUSE_DIRTY_COUNT rc=$_MUSE_LAST_DIRTY_RC" >&2
166 }
167
168 # Post-command refresh: same as _muse_refresh but resets the command flag.
169 function _muse_refresh_full() {
170 (( MUSE_DEBUG )) && print "[muse] _muse_refresh_full (cmd_ran=$_MUSE_CMD_RAN)" >&2
171 _muse_refresh || return
172 _MUSE_CMD_RAN=0
173 }
174
175 # ── §3 ZSH hooks ─────────────────────────────────────────────────────────────
176
177 # On directory change: refresh head and domain; clear dirty (stale after cd).
178 # Pre-clear MUSE_REPO_ROOT so any silent failure in _muse_refresh leaves the
179 # prompt blank rather than showing stale data from the previous directory.
180 function _muse_hook_chpwd() {
181 print "[chpwd:1] cd into $PWD — resetting state" >&2
182 MUSE_REPO_ROOT=""; MUSE_BRANCH=""; MUSE_DIRTY=0; MUSE_DIRTY_COUNT=0
183 _muse_refresh
184 print "[chpwd:2] after refresh: dirty=$MUSE_DIRTY branch=$MUSE_BRANCH" >&2
185 }
186 chpwd_functions+=(_muse_hook_chpwd)
187
188 # Before a command: flag when the user runs muse so we refresh after.
189 function _muse_hook_preexec() {
190 [[ "${${(z)1}[1]}" == "muse" ]] && _MUSE_CMD_RAN=1
191 }
192 preexec_functions+=(_muse_hook_preexec)
193
194 # Before the prompt: full refresh only when a muse command just ran.
195 function _muse_hook_precmd() {
196 print "[precmd:1] _MUSE_CMD_RAN=$_MUSE_CMD_RAN MUSE_DIRTY=$MUSE_DIRTY" >&2
197 (( _MUSE_CMD_RAN )) && _muse_refresh_full
198 print "[precmd:2] after: MUSE_DIRTY=$MUSE_DIRTY" >&2
199 }
200 precmd_functions+=(_muse_hook_precmd)
201
202 # ── §4 Prompt ────────────────────────────────────────────────────────────────
203
204 # Primary prompt segment. Example usage in ~/.zshrc:
205 # PROMPT='%~ $(muse_prompt_info) %# '
206 # Emits nothing when not inside a muse repo.
207 #
208 # Clean: muse:(code:main) — domain:branch in magenta
209 # Dirty: muse:(code:main) — domain:branch in yellow
210 #
211 # The color of the domain:branch text is the only dirty signal — no extra
212 # symbol. Yellow means "uncommitted changes exist"; magenta means clean.
213 function muse_prompt_info() {
214 if [[ -z "$MUSE_REPO_ROOT" ]]; then
215 print "[prompt:1] no repo — returning empty" >&2
216 return
217 fi
218
219 # Escape % so ZSH does not treat branch-name content as prompt directives.
220 local branch="${MUSE_BRANCH//\%/%%}"
221 local domain="${MUSE_DOMAIN//\%/%%}"
222
223 # Branch: magenta when clean, yellow when dirty. Domain is always magenta.
224 local branch_color="%F{magenta}"
225 local color_name="MAGENTA"
226 if (( MUSE_DIRTY )); then
227 branch_color="%F{yellow}"
228 color_name="YELLOW"
229 fi
230
231 print "[prompt:2] MUSE_DIRTY=$MUSE_DIRTY branch=$branch domain=$domain → branch_color=$color_name" >&2
232
233 # Format: %F{cyan}muse:(%F{magenta}<domain>:%F{yellow|magenta}<branch>%F{cyan})%f
234 if [[ "$MUSE_PROMPT_ICONS" == "1" ]]; then
235 local icon="${MUSE_DOMAIN_ICONS[$MUSE_DOMAIN]:-${MUSE_DOMAIN_ICONS[_default]}}"
236 echo -n "%F{cyan}${icon} muse:(%F{magenta}${domain}:${branch_color}${branch}%F{cyan})%f"
237 else
238 echo -n "%F{cyan}muse:(%F{magenta}${domain}:${branch_color}${branch}%F{cyan})%f"
239 fi
240 print "[prompt:3] rendered with $color_name" >&2
241 }
242
243 # ── §5 Debug ─────────────────────────────────────────────────────────────────
244
245 # Print current plugin state. Run when the prompt looks wrong.
246 # muse_debug
247 function muse_debug() {
248 print "MUSE_REPO_ROOT = ${MUSE_REPO_ROOT:-(not set)}"
249 print "MUSE_BRANCH = ${MUSE_BRANCH:-(not set)}"
250 print "MUSE_DOMAIN = ${MUSE_DOMAIN:-(not set)}"
251 print "MUSE_DIRTY = $MUSE_DIRTY (count: $MUSE_DIRTY_COUNT)"
252 print "MUSE_DIRTY_TIMEOUT = ${MUSE_DIRTY_TIMEOUT}s"
253 print "_MUSE_LAST_DIRTY_RC = $_MUSE_LAST_DIRTY_RC (124 = timed out)"
254 print "_MUSE_CMD_RAN = $_MUSE_CMD_RAN"
255 print "PWD = $PWD"
256 if [[ -n "$MUSE_REPO_ROOT" ]]; then
257 print "repo.json = $MUSE_REPO_ROOT/.muse/repo.json"
258 print "HEAD = $(< "$MUSE_REPO_ROOT/.muse/HEAD" 2>/dev/null || print '(missing)')"
259 print "--- muse status --porcelain (live, timed) ---"
260 time (cd -- "$MUSE_REPO_ROOT" && muse status --porcelain 2>&1)
261 print "--------------------------------------------"
262 fi
263 }
264
265 # ── §6 Aliases ───────────────────────────────────────────────────────────────
266 alias mst='muse status'
267 alias msts='muse status --short'
268 alias mcm='muse commit -m'
269 alias mco='muse checkout'
270 alias mlg='muse log'
271 alias mlgo='muse log --oneline'
272 alias mlgg='muse log --graph'
273 alias mdf='muse diff'
274 alias mdfst='muse diff --stat'
275 alias mbr='muse branch'
276 alias mtg='muse tag'
277 alias mfh='muse fetch'
278 alias mpull='muse pull'
279 alias mpush='muse push'
280 alias mrm='muse remote'
281
282 # ── §7 Completion ────────────────────────────────────────────────────────────
283 if [[ -f "${0:A:h}/_muse" ]]; then
284 fpath=("${0:A:h}" $fpath)
285 autoload -Uz compinit
286 compdef _muse muse 2>/dev/null
287 fi
288
289 # ── §8 Init ──────────────────────────────────────────────────────────────────
290 # Warm head + domain on load so the first prompt is not blank.
291 print "[init:1] plugin loading. PWD=$PWD" >&2
292 _muse_refresh
293 print "[init:2] plugin loaded. dirty=$MUSE_DIRTY branch=$MUSE_BRANCH" >&2