|
| 1 | +"""HUD state helper functions for consistent updates across hooks (#1324). |
| 2 | +
|
| 3 | +Provides high-level helpers that multiple hooks can call to update the |
| 4 | +HUD state file with standard field semantics. All functions silently |
| 5 | +no-op on any error so they never block Claude Code. |
| 6 | +
|
| 7 | +Field ownership: |
| 8 | + SessionStart -> init_baseline() |
| 9 | + UserPromptSubmit -> on_mode_entry() |
| 10 | + PreToolUse -> on_tool_start() |
| 11 | + PostToolUse -> on_tool_end() |
| 12 | + Stop -> on_session_stop() |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import os |
| 18 | +from typing import Optional |
| 19 | + |
| 20 | +from hud_state import update_hud_state |
| 21 | + |
| 22 | +# Map mode -> initial phase value |
| 23 | +_MODE_PHASE_MAP = { |
| 24 | + "PLAN": "planning", |
| 25 | + "ACT": "executing", |
| 26 | + "EVAL": "evaluating", |
| 27 | + "AUTO": "cycling", |
| 28 | +} |
| 29 | + |
| 30 | + |
| 31 | +def on_mode_entry( |
| 32 | + mode: str, |
| 33 | + *, |
| 34 | + state_file: Optional[str] = None, |
| 35 | +) -> None: |
| 36 | + """Reset workflow fields when a new mode is entered. |
| 37 | +
|
| 38 | + Called from UserPromptSubmit after mode keyword detection. |
| 39 | +
|
| 40 | + Args: |
| 41 | + mode: The detected mode (PLAN, ACT, EVAL, AUTO). |
| 42 | + state_file: Optional explicit path; uses default when None. |
| 43 | + """ |
| 44 | + try: |
| 45 | + phase = _MODE_PHASE_MAP.get(mode, "ready") |
| 46 | + kwargs = { |
| 47 | + "currentMode": mode, |
| 48 | + "phase": phase, |
| 49 | + "focus": None, |
| 50 | + "blockerCount": 0, |
| 51 | + } |
| 52 | + if state_file: |
| 53 | + update_hud_state(state_file=state_file, **kwargs) |
| 54 | + else: |
| 55 | + update_hud_state(**kwargs) |
| 56 | + except Exception: |
| 57 | + pass |
| 58 | + |
| 59 | + |
| 60 | +def on_tool_start( |
| 61 | + tool_name: str, |
| 62 | + tool_input: dict, |
| 63 | + *, |
| 64 | + state_file: Optional[str] = None, |
| 65 | +) -> None: |
| 66 | + """Update HUD when a tool invocation begins. |
| 67 | +
|
| 68 | + Called from PreToolUse. Only updates when the information is |
| 69 | + meaningfully stable (e.g. active agent change, MCP parse_mode). |
| 70 | +
|
| 71 | + Args: |
| 72 | + tool_name: Name of the tool being invoked. |
| 73 | + tool_input: The tool_input dict from the hook payload. |
| 74 | + state_file: Optional explicit path; uses default when None. |
| 75 | + """ |
| 76 | + try: |
| 77 | + updates: dict = {} |
| 78 | + |
| 79 | + # Detect active agent from environment (set by parse_mode MCP) |
| 80 | + agent = os.environ.get("CODINGBUDDY_ACTIVE_AGENT", "") |
| 81 | + if agent: |
| 82 | + updates["activeAgent"] = agent |
| 83 | + |
| 84 | + # Detect focus from meaningful tool patterns |
| 85 | + focus = _detect_focus(tool_name, tool_input) |
| 86 | + if focus is not None: |
| 87 | + updates["focus"] = focus |
| 88 | + |
| 89 | + # Detect execution strategy from Agent/Task tool use |
| 90 | + strategy = _detect_strategy(tool_name, tool_input) |
| 91 | + if strategy is not None: |
| 92 | + updates["executionStrategy"] = strategy |
| 93 | + |
| 94 | + if updates: |
| 95 | + if state_file: |
| 96 | + update_hud_state(state_file=state_file, **updates) |
| 97 | + else: |
| 98 | + update_hud_state(**updates) |
| 99 | + except Exception: |
| 100 | + pass |
| 101 | + |
| 102 | + |
| 103 | +def on_tool_end( |
| 104 | + tool_name: str, |
| 105 | + tool_input: dict, |
| 106 | + tool_output: str, |
| 107 | + *, |
| 108 | + state_file: Optional[str] = None, |
| 109 | +) -> None: |
| 110 | + """Record stable post-action state after a tool completes. |
| 111 | +
|
| 112 | + Called from PostToolUse. Captures agent handoffs and phase |
| 113 | + transitions that are evident from tool outputs. |
| 114 | +
|
| 115 | + Args: |
| 116 | + tool_name: Name of the completed tool. |
| 117 | + tool_input: The tool_input dict from the hook payload. |
| 118 | + tool_output: The tool_output string from the hook payload. |
| 119 | + state_file: Optional explicit path; uses default when None. |
| 120 | + """ |
| 121 | + try: |
| 122 | + updates: dict = {} |
| 123 | + |
| 124 | + # Track agent handoffs via environment changes |
| 125 | + agent = os.environ.get("CODINGBUDDY_ACTIVE_AGENT", "") |
| 126 | + if agent: |
| 127 | + updates["activeAgent"] = agent |
| 128 | + updates["lastHandoff"] = agent |
| 129 | + |
| 130 | + # Detect phase changes from parse_mode MCP calls |
| 131 | + if tool_name == "mcp__codingbuddy__parse_mode": |
| 132 | + mode = _extract_mode_from_parse_mode(tool_input) |
| 133 | + if mode: |
| 134 | + phase = _MODE_PHASE_MAP.get(mode, "ready") |
| 135 | + updates["currentMode"] = mode |
| 136 | + updates["phase"] = phase |
| 137 | + |
| 138 | + if updates: |
| 139 | + if state_file: |
| 140 | + update_hud_state(state_file=state_file, **updates) |
| 141 | + else: |
| 142 | + update_hud_state(**updates) |
| 143 | + except Exception: |
| 144 | + pass |
| 145 | + |
| 146 | + |
| 147 | +def on_session_stop( |
| 148 | + *, |
| 149 | + state_file: Optional[str] = None, |
| 150 | +) -> None: |
| 151 | + """Clear active workflow state when the session ends. |
| 152 | +
|
| 153 | + Called from Stop hook. |
| 154 | +
|
| 155 | + Args: |
| 156 | + state_file: Optional explicit path; uses default when None. |
| 157 | + """ |
| 158 | + try: |
| 159 | + kwargs = { |
| 160 | + "activeAgent": None, |
| 161 | + "phase": "completed", |
| 162 | + "focus": None, |
| 163 | + "executionStrategy": None, |
| 164 | + "councilStatus": None, |
| 165 | + "blockerCount": 0, |
| 166 | + } |
| 167 | + if state_file: |
| 168 | + update_hud_state(state_file=state_file, **kwargs) |
| 169 | + else: |
| 170 | + update_hud_state(**kwargs) |
| 171 | + except Exception: |
| 172 | + pass |
| 173 | + |
| 174 | + |
| 175 | +def init_baseline( |
| 176 | + pending_context: Optional[dict] = None, |
| 177 | + *, |
| 178 | + state_file: Optional[str] = None, |
| 179 | +) -> None: |
| 180 | + """Enrich the freshly-initialised HUD state with baseline context. |
| 181 | +
|
| 182 | + Called from SessionStart *after* ``init_hud_state()``. If a pending |
| 183 | + context.md was detected, seeds currentMode and phase so the status |
| 184 | + bar immediately reflects the resuming session. |
| 185 | +
|
| 186 | + Args: |
| 187 | + pending_context: Dict with optional ``mode``/``status`` keys |
| 188 | + from ``_read_pending_context()``. |
| 189 | + state_file: Optional explicit path; uses default when None. |
| 190 | + """ |
| 191 | + if not pending_context: |
| 192 | + return |
| 193 | + |
| 194 | + try: |
| 195 | + mode = pending_context.get("mode") |
| 196 | + if not mode: |
| 197 | + return |
| 198 | + |
| 199 | + updates: dict = {"currentMode": mode} |
| 200 | + phase = _MODE_PHASE_MAP.get(mode) |
| 201 | + if phase: |
| 202 | + updates["phase"] = phase |
| 203 | + |
| 204 | + if state_file: |
| 205 | + update_hud_state(state_file=state_file, **updates) |
| 206 | + else: |
| 207 | + update_hud_state(**updates) |
| 208 | + except Exception: |
| 209 | + pass |
| 210 | + |
| 211 | + |
| 212 | +# ---- private helpers ---- |
| 213 | + |
| 214 | + |
| 215 | +def _detect_focus(tool_name: str, tool_input: dict) -> Optional[str]: |
| 216 | + """Infer a human-readable focus label from the current tool call.""" |
| 217 | + if tool_name == "Edit" or tool_name == "Write": |
| 218 | + path = tool_input.get("file_path", "") |
| 219 | + if path: |
| 220 | + # Return just the filename for brevity |
| 221 | + return os.path.basename(path) |
| 222 | + |
| 223 | + if tool_name == "Bash": |
| 224 | + cmd = tool_input.get("command", "") |
| 225 | + if cmd.startswith("git commit"): |
| 226 | + return "committing" |
| 227 | + if cmd.startswith("git push"): |
| 228 | + return "pushing" |
| 229 | + if "pytest" in cmd or "vitest" in cmd or "jest" in cmd: |
| 230 | + return "testing" |
| 231 | + if "yarn build" in cmd or "npm run build" in cmd: |
| 232 | + return "building" |
| 233 | + |
| 234 | + if tool_name == "mcp__codingbuddy__parse_mode": |
| 235 | + prompt = tool_input.get("prompt", "") |
| 236 | + if prompt: |
| 237 | + # First 40 chars of the prompt as focus |
| 238 | + return prompt[:40].strip() |
| 239 | + |
| 240 | + return None |
| 241 | + |
| 242 | + |
| 243 | +def _detect_strategy(tool_name: str, tool_input: dict) -> Optional[str]: |
| 244 | + """Detect execution strategy from Agent/Task tool patterns.""" |
| 245 | + if tool_name == "Agent": |
| 246 | + return "subagent" |
| 247 | + if tool_name == "Bash": |
| 248 | + cmd = tool_input.get("command", "") |
| 249 | + if "tmux" in cmd: |
| 250 | + return "taskmaestro" |
| 251 | + return None |
| 252 | + |
| 253 | + |
| 254 | +def _extract_mode_from_parse_mode(tool_input: dict) -> Optional[str]: |
| 255 | + """Extract the mode keyword from a parse_mode tool_input.""" |
| 256 | + prompt = tool_input.get("prompt", "") |
| 257 | + if not prompt: |
| 258 | + return None |
| 259 | + first_word = prompt.strip().split()[0].upper().rstrip(":") |
| 260 | + valid_modes = {"PLAN", "ACT", "EVAL", "AUTO"} |
| 261 | + return first_word if first_word in valid_modes else None |
0 commit comments