@torka/claude-qol 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "@torka/claude-qol",
3
+ "version": "0.1.0",
4
+ "description": "Claude Code quality-of-life improvements: auto-approve hooks and context monitoring",
5
+ "type": "hooks"
6
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Varun Torka
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,266 @@
1
+ # @torka/claude-qol
2
+
3
+ Claude Code quality-of-life improvements: auto-approve hooks, context monitoring, and workflow optimization.
4
+
5
+ ## Features
6
+
7
+ | Feature | Description |
8
+ |---------|-------------|
9
+ | **Auto-Approve Hook** | Intelligent command auto-approval for solo dev workflows |
10
+ | **Context Monitor** | Real-time context usage status line with visual indicators |
11
+ | **Auto-Format Hook** | Run linters/formatters automatically after file edits |
12
+ | **Completion Notifications** | Desktop notifications + sound when tasks complete |
13
+ | **Optimize Command** | Analyze auto-approve decisions and refine rules |
14
+
15
+ ## Installation
16
+
17
+ ### Project-level (recommended)
18
+
19
+ ```bash
20
+ npm install --save-dev @torka/claude-qol
21
+ ```
22
+
23
+ ### Global
24
+
25
+ ```bash
26
+ npm install -g @torka/claude-qol
27
+ ```
28
+
29
+ The installer automatically copies files to your `.claude/` directory:
30
+ - **Project-level**: Files go to `<project>/.claude/`
31
+ - **Global**: Files go to `~/.claude/`
32
+
33
+ ## Post-Installation Setup
34
+
35
+ ### 1. Configure Auto-Approve Hook (recommended)
36
+
37
+ Add to your `.claude/settings.local.json`:
38
+
39
+ ```json
40
+ {
41
+ "hooks": {
42
+ "PreToolUse": [
43
+ {
44
+ "matcher": "Bash|Read|Grep|Glob|Write|Edit|MultiEdit",
45
+ "hooks": [
46
+ {
47
+ "type": "command",
48
+ "command": "python3 .claude/scripts/auto_approve_safe.py"
49
+ }
50
+ ]
51
+ }
52
+ ]
53
+ }
54
+ }
55
+ ```
56
+
57
+ ### 2. Configure Status Line (optional)
58
+
59
+ Add to your `.claude/settings.local.json`:
60
+
61
+ ```json
62
+ {
63
+ "statusLine": {
64
+ "type": "command",
65
+ "command": "python3 .claude/scripts/context-monitor.py"
66
+ }
67
+ }
68
+ ```
69
+
70
+ This shows a real-time context usage bar with percentage and warnings.
71
+
72
+ ### 3. Auto-Format on Edit (optional)
73
+
74
+ Auto-run linters and formatters after file edits:
75
+
76
+ ```json
77
+ {
78
+ "hooks": {
79
+ "PostToolUse": [
80
+ {
81
+ "matcher": "Edit|MultiEdit",
82
+ "hooks": [
83
+ {
84
+ "type": "command",
85
+ "command": "if [[ \"$CLAUDE_TOOL_FILE_PATH\" == *.js || \"$CLAUDE_TOOL_FILE_PATH\" == *.ts || \"$CLAUDE_TOOL_FILE_PATH\" == *.jsx || \"$CLAUDE_TOOL_FILE_PATH\" == *.tsx ]]; then npx eslint \"$CLAUDE_TOOL_FILE_PATH\" --fix 2>/dev/null || true; elif [[ \"$CLAUDE_TOOL_FILE_PATH\" == *.py ]]; then pylint \"$CLAUDE_TOOL_FILE_PATH\" 2>/dev/null || true; fi"
86
+ },
87
+ {
88
+ "type": "command",
89
+ "command": "if [[ \"$CLAUDE_TOOL_FILE_PATH\" == *.js || \"$CLAUDE_TOOL_FILE_PATH\" == *.ts || \"$CLAUDE_TOOL_FILE_PATH\" == *.jsx || \"$CLAUDE_TOOL_FILE_PATH\" == *.tsx || \"$CLAUDE_TOOL_FILE_PATH\" == *.json || \"$CLAUDE_TOOL_FILE_PATH\" == *.css || \"$CLAUDE_TOOL_FILE_PATH\" == *.html ]]; then npx prettier --write \"$CLAUDE_TOOL_FILE_PATH\" 2>/dev/null || true; elif [[ \"$CLAUDE_TOOL_FILE_PATH\" == *.py ]]; then black \"$CLAUDE_TOOL_FILE_PATH\" 2>/dev/null || true; elif [[ \"$CLAUDE_TOOL_FILE_PATH\" == *.go ]]; then gofmt -w \"$CLAUDE_TOOL_FILE_PATH\" 2>/dev/null || true; fi"
90
+ }
91
+ ]
92
+ }
93
+ ]
94
+ }
95
+ }
96
+ ```
97
+
98
+ **Supported languages:**
99
+ - JavaScript/TypeScript: ESLint + Prettier
100
+ - Python: Pylint + Black
101
+ - Go: gofmt
102
+ - Rust: rustfmt
103
+ - PHP: php-cs-fixer
104
+
105
+ ### 4. Completion Notifications (optional)
106
+
107
+ Get notified when Claude Code finishes a task:
108
+
109
+ ```json
110
+ {
111
+ "hooks": {
112
+ "Stop": [
113
+ {
114
+ "matcher": "*",
115
+ "hooks": [
116
+ {
117
+ "type": "command",
118
+ "command": "if command -v osascript >/dev/null 2>&1; then osascript -e 'display notification \"Tool: Operation completed\" with title \"Claude Code\"'; elif command -v notify-send >/dev/null 2>&1; then notify-send 'Claude Code' \"Tool: $CLAUDE_TOOL_NAME completed\"; fi"
119
+ },
120
+ {
121
+ "type": "command",
122
+ "command": "afplay /System/Library/Sounds/Glass.aiff"
123
+ }
124
+ ]
125
+ }
126
+ ]
127
+ }
128
+ }
129
+ ```
130
+
131
+ **Platform support:**
132
+ - macOS: Native notifications via `osascript` + sound via `afplay`
133
+ - Linux: Desktop notifications via `notify-send`
134
+
135
+ ## Components
136
+
137
+ ### Auto-Approve Hook
138
+
139
+ PreToolUse hook that intelligently auto-approves safe commands:
140
+
141
+ **Allowed by default:**
142
+ - Read-only commands (`ls`, `cat`, `head`, `tail`, `tree`)
143
+ - Git read operations (`git status`, `git diff`, `git log`, `git branch`)
144
+ - Development commands (`npm test`, `npm run build`, `pnpm test`, `pytest`)
145
+ - Search tools (`grep`, `rg`, `find`, `fd`, `jq`)
146
+ - File system operations (`mkdir`, `touch`, `cp`, `mv`)
147
+ - Git write operations (`git add`, `git commit`, `git push`)
148
+ - GitHub CLI (`gh pr`, `gh issue`, `gh repo`)
149
+
150
+ **Denied automatically:**
151
+ - Dangerous commands (`sudo`, `rm -rf`, `mkfs`, `shutdown`)
152
+ - System modifications (`chmod 777`, `chown :* /`)
153
+ - Pipe to shell (`curl | bash`, `wget | sh`)
154
+ - Fork bombs and kill commands
155
+
156
+ **Prompted (normal permission system):**
157
+ - Everything else defers to Claude Code's built-in permissions
158
+
159
+ #### Customizing Rules
160
+
161
+ Edit `.claude/scripts/auto_approve_safe.rules.json`:
162
+
163
+ ```json
164
+ {
165
+ "allow_patterns": [
166
+ "^your-custom-safe-command"
167
+ ],
168
+ "deny_patterns": [
169
+ "^your-dangerous-command"
170
+ ],
171
+ "sensitive_paths": [
172
+ "\\.secret$"
173
+ ]
174
+ }
175
+ ```
176
+
177
+ ### Context Monitor
178
+
179
+ Status line script showing:
180
+ - Current model name (e.g., `[Claude Opus 4]`)
181
+ - Working directory
182
+ - Git branch with visual indicator
183
+ - Context usage bar with percentage
184
+ - Color-coded warnings:
185
+ - 🟢 Green: < 50% usage
186
+ - 🟡 Yellow: 50-75% usage
187
+ - 🟠 Light red: 75-90% usage
188
+ - 🔴 Red: 90-95% usage
189
+ - 🔴 Blinking: > 95% usage (CRITICAL)
190
+
191
+ ### Optimize Command
192
+
193
+ Run `/optimize-auto-approve-hook` to:
194
+ 1. Analyze the decision log (`.claude/auto_approve_safe.decisions.jsonl`)
195
+ 2. Validate existing ALLOW rules aren't too permissive
196
+ 3. Identify frequently-asked commands that could be safely auto-allowed
197
+ 4. Check for overly broad DENY patterns causing false positives
198
+ 5. Generate new regex patterns for safe commands
199
+ 6. Clean up and archive the decision log
200
+
201
+ ## Decision Logging
202
+
203
+ When `ENABLE_DECISION_LOG = True` (default), the hook logs all decisions to:
204
+ ```
205
+ .claude/auto_approve_safe.decisions.jsonl
206
+ ```
207
+
208
+ Each entry includes:
209
+ - Timestamp
210
+ - Tool name
211
+ - Decision (allow/deny/ask)
212
+ - Reason for decision
213
+ - Input summary
214
+
215
+ Use `/optimize-auto-approve-hook` to analyze this log and improve your rules.
216
+
217
+ ## File Structure
218
+
219
+ After installation, files are placed in:
220
+
221
+ ```
222
+ .claude/
223
+ ├── scripts/
224
+ │ ├── auto_approve_safe.py
225
+ │ ├── auto_approve_safe.rules.json
226
+ │ └── context-monitor.py
227
+ └── commands/
228
+ └── optimize-auto-approve-hook.md
229
+ ```
230
+
231
+ ## Uninstallation
232
+
233
+ ```bash
234
+ npm uninstall @torka/claude-qol
235
+ ```
236
+
237
+ **Manual cleanup** (if files remain after uninstall):
238
+
239
+ ```bash
240
+ rm -f .claude/scripts/auto_approve_safe.py \
241
+ .claude/scripts/auto_approve_safe.rules.json \
242
+ .claude/scripts/context-monitor.py \
243
+ .claude/commands/optimize-auto-approve-hook.md
244
+ ```
245
+
246
+ **Note**: Your `settings.local.json` is not modified—you may want to manually remove hook/statusLine configurations.
247
+
248
+ ## Contributing
249
+
250
+ 1. Fork the repository
251
+ 2. Create a feature branch
252
+ 3. Make your changes
253
+ 4. Submit a pull request
254
+
255
+ ## License
256
+
257
+ MIT License - see [LICENSE](LICENSE) for details.
258
+
259
+ ## Author
260
+
261
+ Varun Torka
262
+
263
+ ## Links
264
+
265
+ - [Claude Code Documentation](https://code.claude.com/docs)
266
+ - [npm Package](https://www.npmjs.com/package/@torka/claude-qol)
@@ -0,0 +1,406 @@
1
+ ---
2
+ description: 'Analyze auto-approve decisions to identify safe patterns for auto-allowing and validate existing rules'
3
+ ---
4
+
5
+ # Auto-Approve Hook Optimizer
6
+
7
+ You are a security-conscious CLI analyst. Analyze the auto-approve decision log to identify patterns that can be safely auto-allowed, validate existing rules, and maintain the log file.
8
+
9
+ ## Overview
10
+
11
+ This command performs a comprehensive analysis of the auto-approve hook's decision log to:
12
+ 1. Validate that existing ALLOW rules aren't too permissive
13
+ 2. Identify frequently asked commands that could be safely auto-allowed
14
+ 3. Check for overly broad DENY patterns causing false positives
15
+ 4. Clean up the decision log after analysis
16
+
17
+ ## Files Involved
18
+
19
+ | File | Purpose |
20
+ |------|---------|
21
+ | `.claude/auto_approve_safe.decisions.jsonl` | Decision log (read, then archive/clear) |
22
+ | `.claude/scripts/auto_approve_safe.rules.json` | Rules config (read, then edit) |
23
+ | `.claude/auto_approve_safe.decisions.archived.jsonl` | Archive file (create/append) |
24
+
25
+ ---
26
+
27
+ ## Workflow Phases
28
+
29
+ <steps>
30
+
31
+ ### Phase 0: Pre-flight Checks
32
+
33
+ 1. **Read the decision log** at `.claude/auto_approve_safe.decisions.jsonl`
34
+ - If missing or empty: Stop with message "No decision log found. Run some operations first to generate decisions."
35
+
36
+ 2. **Read the rules file** at `.claude/scripts/auto_approve_safe.rules.json`
37
+ - If missing: Warn but continue (will create recommendations only)
38
+
39
+ 3. **Display summary to user:**
40
+ ```
41
+ Decision Log Summary
42
+ ====================
43
+ Total entries: {count}
44
+ Date range: {earliest} to {latest}
45
+
46
+ By decision type:
47
+ - ALLOW: {count} ({percentage}%)
48
+ - DENY: {count} ({percentage}%)
49
+ - ASK: {count} ({percentage}%)
50
+
51
+ By tool:
52
+ - Bash: {count}
53
+ - Read: {count}
54
+ - Write: {count}
55
+ - Edit: {count}
56
+ - Other: {count}
57
+ ```
58
+
59
+ ### Phase 1: Parse and Categorize
60
+
61
+ Parse all JSONL entries and group by decision type:
62
+
63
+ **For Bash commands:**
64
+ - Extract the `command` field from `input`
65
+ - Normalize: collapse whitespace, extract base command and flags
66
+ - Group similar commands (e.g., all `npm run *` together)
67
+
68
+ **For File operations (Read/Write/Edit):**
69
+ - Extract the `file_path` field from `input`
70
+ - Identify path patterns (e.g., `src/**/*.ts`, `docs/*.md`)
71
+ - Group by directory structure
72
+
73
+ **Create internal data structures:**
74
+ ```
75
+ allow_entries: [{ts, tool, input, reason}]
76
+ deny_entries: [{ts, tool, input, reason}]
77
+ ask_entries: [{ts, tool, input, reason}]
78
+ ```
79
+
80
+ ### Phase 2: Analyze ALLOW Decisions (Validate Safety)
81
+
82
+ Review all ALLOW decisions and flag potentially unsafe patterns:
83
+
84
+ | Red Flag | Detection Logic | Severity |
85
+ |----------|-----------------|----------|
86
+ | Outside project dir | Path contains `..` or absolute path not under cwd | HIGH |
87
+ | Arbitrary code exec | `eval`, `exec`, backticks without known safe args | HIGH |
88
+ | Network with dynamic URL | `curl`/`wget` with variable/constructed URLs | MEDIUM |
89
+ | Dangerous flags | `--force`, `-f`, `--no-verify`, `--hard` | MEDIUM |
90
+ | Recursive delete | `rm -r` or `rm -rf` (should be deny) | HIGH |
91
+ | Pipe to shell | `| bash`, `| sh`, `| zsh` | HIGH |
92
+
93
+ **Output format:**
94
+ ```
95
+ POTENTIAL UNSAFE ALLOWS
96
+ =======================
97
+ [HIGH] Command: rm -rf node_modules
98
+ Reason: Matched "Matches safe allowlist" but contains recursive delete
99
+ Recommendation: Add to deny_patterns or remove from allow_patterns
100
+
101
+ [MEDIUM] Command: curl https://example.com/script.sh
102
+ Reason: Network command allowed but URL could vary
103
+ Recommendation: Review if URL should be restricted
104
+ ```
105
+
106
+ ### Phase 3: Analyze DENY Decisions (Check for False Positives)
107
+
108
+ Identify overly broad deny patterns that might block safe operations:
109
+
110
+ **Look for:**
111
+ - Non-recursive `rm` blocked by recursive pattern (e.g., `rm file.txt` blocked by `rm.*-rf`)
112
+ - Safe paths incorrectly matching `sensitive_paths` (e.g., `src/utils/tokenizer.ts` matching `token`)
113
+ - Common dev commands that should be allowed (e.g., `npm run build` blocked)
114
+
115
+ **Output format:**
116
+ ```
117
+ POTENTIAL FALSE POSITIVES
118
+ =========================
119
+ [ ] Pattern: "\\brm\\s+.*(-r|-rf)" may be too broad
120
+ Blocked: rm file.txt (no -r flag)
121
+ Suggestion: Use "\\brm\\s+.*\\s+(-r|-rf|--recursive)\\b" instead
122
+
123
+ [ ] Pattern: "\\btoken" in sensitive_paths
124
+ Blocked: src/utils/tokenizer.ts
125
+ Suggestion: Use "\\btoken(?!izer)" or "\\btokens?\\b"
126
+ ```
127
+
128
+ ### Phase 4: Analyze ASK Decisions (Auto-Allow Candidates)
129
+
130
+ **This is the most valuable optimization phase.**
131
+
132
+ Identify commands that were asked repeatedly and could be safely auto-allowed.
133
+
134
+ **Criteria for safe auto-allow:**
135
+
136
+ | Criterion | Threshold | Rationale |
137
+ |-----------|-----------|-----------|
138
+ | Frequency | 3+ occurrences | Indicates common workflow |
139
+ | Containment | All paths within project | No system-wide impact |
140
+ | Predictable scope | No shell expansion, no `*` in dangerous positions | Bounded behavior |
141
+ | Reversibility | File ops can be undone, commands are read-only or local | Low risk |
142
+ | No dangerous flags | No `--force`, `-f` unless safe context | Explicit caution |
143
+
144
+ **Process each unique ASK pattern:**
145
+ 1. Count occurrences
146
+ 2. Check all criteria
147
+ 3. If all pass, generate a specific regex pattern
148
+ 4. Include sample commands that would match
149
+
150
+ **Pattern Generation Heuristics:**
151
+
152
+ | Observed Pattern | Generated Regex | Notes |
153
+ |-----------------|-----------------|-------|
154
+ | `npx tsx script.ts` | `^npx\\s+tsx\\s+[^\\|;&]+$` | No pipes or chains |
155
+ | `npm run custom-script` | `^npm\\s+run\\s+[\\w-]+$` | Word chars and hyphen only |
156
+ | `cat package.json` | Already covered by existing rules | Skip |
157
+ | `rm file.txt` (non-recursive) | `^rm\\s+(?!.*(-r\\|-rf))\\S+$` | Negative lookahead for -r |
158
+
159
+ **Output format:**
160
+ ```
161
+ AUTO-ALLOW CANDIDATES
162
+ =====================
163
+ [ ] 1. Pattern: "^npx\\s+tsx\\s+[^|;&]+$"
164
+ Matches: npx tsx script.ts, npx tsx src/test.ts
165
+ Occurrences: 4
166
+ Safety: All within project, no shell operators
167
+
168
+ [ ] 2. Pattern: "^python3?\\s+[\\w/.-]+\\.py$"
169
+ Matches: python script.py, python3 src/tools/gen.py
170
+ Occurrences: 3
171
+ Safety: Simple script execution, no args could be dangerous
172
+ ```
173
+
174
+ ### Phase 5: Present Consolidated Recommendations
175
+
176
+ Display a structured summary of all recommendations:
177
+
178
+ ```
179
+ ==============================================
180
+ AUTO-APPROVE HOOK OPTIMIZATION RECOMMENDATIONS
181
+ ==============================================
182
+
183
+ ALLOW PATTERNS TO ADD:
184
+ [ ] 1. "^npx\\s+tsx\\s+[^|;&]+$"
185
+ Sample: npx tsx script.ts (4 occurrences)
186
+
187
+ [ ] 2. "^python3?\\s+[\\w/.-]+\\.py$"
188
+ Sample: python script.py (3 occurrences)
189
+
190
+ DENY PATTERNS TO FIX:
191
+ [ ] 1. Current: "\\brm\\s+.*(-r|-rf)"
192
+ Replace: "\\brm\\s+.*\\s+(-r|-rf|--recursive)\\b"
193
+ Reason: Current pattern matches non-recursive rm
194
+
195
+ SENSITIVE PATHS TO ADD:
196
+ [ ] None identified
197
+
198
+ WARNINGS (Manual Review Needed):
199
+ ! 2 potentially unsafe ALLOW decisions detected
200
+ See Phase 2 output for details
201
+ ```
202
+
203
+ ### Phase 6: User Confirmation
204
+
205
+ Use `AskUserQuestion` tool with `multiSelect: true` to let user select changes:
206
+
207
+ **Question 1: Pattern Selection**
208
+ ```
209
+ header: "Patterns"
210
+ question: "Which patterns would you like to add to the allow list?"
211
+ options:
212
+ - label: "All recommended patterns"
213
+ description: "Add all {N} patterns identified as safe"
214
+ - label: "Select individually"
215
+ description: "Review and select patterns one by one"
216
+ - label: "None"
217
+ description: "Skip pattern changes"
218
+ ```
219
+
220
+ If "Select individually" chosen, ask about each pattern.
221
+
222
+ **Question 2: Log Cleanup**
223
+ ```
224
+ header: "Log cleanup"
225
+ question: "How should the decision log be handled after analysis?"
226
+ options:
227
+ - label: "Archive"
228
+ description: "Move entries to .archived.jsonl file, clear active log"
229
+ - label: "Delete"
230
+ description: "Remove log file entirely (hook will recreate)"
231
+ - label: "Keep"
232
+ description: "Leave log unchanged for future analysis"
233
+ ```
234
+
235
+ ### Phase 7: Apply Changes
236
+
237
+ Based on user selections:
238
+
239
+ 1. **Read current rules JSON** (if it exists)
240
+
241
+ 2. **For each approved pattern to add:**
242
+ - Append to the appropriate array (`allow_patterns`, `deny_patterns`, or `sensitive_paths`)
243
+ - Validate the regex is syntactically correct before adding
244
+
245
+ 3. **For each pattern to fix:**
246
+ - Find and replace the old pattern with the new one
247
+ - Verify the replacement was made
248
+
249
+ 4. **Write the updated JSON file**
250
+ - Use proper JSON formatting (2-space indent)
251
+ - Preserve comments if any (though JSON doesn't support them)
252
+
253
+ 5. **Validate the written file:**
254
+ - Read it back
255
+ - Parse as JSON to ensure validity
256
+ - If invalid, restore from backup and report error
257
+
258
+ ### Phase 8: Decision Log Cleanup
259
+
260
+ Based on user's cleanup selection:
261
+
262
+ **Archive:**
263
+ ```bash
264
+ # Append current entries to archive
265
+ cat .claude/auto_approve_safe.decisions.jsonl >> .claude/auto_approve_safe.decisions.archived.jsonl
266
+ # Clear active log
267
+ echo "" > .claude/auto_approve_safe.decisions.jsonl
268
+ ```
269
+
270
+ **Delete:**
271
+ ```bash
272
+ rm .claude/auto_approve_safe.decisions.jsonl
273
+ # Hook will recreate on next decision
274
+ ```
275
+
276
+ **Keep:**
277
+ - No action taken
278
+ - Log remains for future analysis
279
+
280
+ ### Phase 9: Summary Report
281
+
282
+ Display final summary:
283
+
284
+ ```
285
+ =================================
286
+ AUTO-APPROVE OPTIMIZATION COMPLETE
287
+ =================================
288
+
289
+ Changes Applied:
290
+ - Added {N} new allow patterns
291
+ - Fixed {N} deny patterns
292
+ - Added {N} sensitive paths
293
+
294
+ Log Cleanup:
295
+ - Action: {Archive|Delete|Keep}
296
+ - Entries processed: {count}
297
+ - Archive location: .claude/auto_approve_safe.decisions.archived.jsonl
298
+
299
+ To Revert Changes:
300
+ git checkout .claude/scripts/auto_approve_safe.rules.json
301
+
302
+ Next Steps:
303
+ - Test the new patterns by running common commands
304
+ - Re-run /optimize-auto-approve-hook after more usage data
305
+ ```
306
+
307
+ </steps>
308
+
309
+ ---
310
+
311
+ ## Safety Rules
312
+
313
+ **CRITICAL - These rules must NEVER be violated:**
314
+
315
+ 1. **NEVER auto-apply changes** - Always require explicit user confirmation via AskUserQuestion
316
+ 2. **NEVER remove deny patterns** without explicit warning that this could allow dangerous commands
317
+ 3. **NEVER add patterns that match outside the project directory**
318
+ 4. **Validate all regex patterns** before writing to ensure they're syntactically correct
319
+ 5. **Prefer specific patterns** over broad ones (e.g., `^npm run build$` over `^npm run .*$`)
320
+ 6. **Always provide revert instructions** so user can undo changes easily
321
+ 7. **Back up before modifying** - Read the file content before editing so it can be restored if needed
322
+
323
+ ---
324
+
325
+ ## Regex Pattern Guidelines
326
+
327
+ When generating regex patterns for `allow_patterns`:
328
+
329
+ | Goal | Pattern Technique | Example |
330
+ |------|-------------------|---------|
331
+ | Match exact command | Anchors `^...$` | `^npm run build$` |
332
+ | Allow arguments | Character class `[^|;&]+` | `^npx tsx [^|;&]+$` |
333
+ | Word boundary | `\\b` | `\\bgit\\b` prevents matching `digit` |
334
+ | Exclude dangerous | Negative lookahead `(?!...)` | `^rm (?!.*-rf)` |
335
+ | Optional spaces | `\\s+` or `\\s*` | `^npm\\s+run` |
336
+ | Filename only | `[\\w.-]+` | `^cat [\\w.-]+$` |
337
+ | Path characters | `[\\w/.@-]+` | `^cat [\\w/.@-]+$` |
338
+
339
+ **Escape requirements in JSON:**
340
+ - Single backslash in regex → double backslash in JSON string
341
+ - `\s` → `\\s`
342
+ - `\b` → `\\b`
343
+
344
+ ---
345
+
346
+ ## Error Handling
347
+
348
+ | Scenario | Action |
349
+ |----------|--------|
350
+ | Decision log missing | Stop with helpful message |
351
+ | Rules file missing | Continue with recommendations only |
352
+ | Invalid JSON in rules | Report error, do not modify |
353
+ | Regex syntax error | Skip that pattern, warn user |
354
+ | Write permission denied | Report error with chmod suggestion |
355
+ | Archive file locked | Report error, suggest manual cleanup |
356
+
357
+ ---
358
+
359
+ ## Example Session
360
+
361
+ ```
362
+ User: /optimize-auto-approve-hook
363
+
364
+ Claude: Analyzing auto-approve decision log...
365
+
366
+ Decision Log Summary
367
+ ====================
368
+ Total entries: 153
369
+ Date range: 2026-01-15 to 2026-01-16
370
+
371
+ By decision type:
372
+ - ALLOW: 142 (92.8%)
373
+ - DENY: 3 (2.0%)
374
+ - ASK: 8 (5.2%)
375
+
376
+ [Phase 2-4 analysis output...]
377
+
378
+ AUTO-APPROVE HOOK OPTIMIZATION RECOMMENDATIONS
379
+ ==============================================
380
+
381
+ ALLOW PATTERNS TO ADD:
382
+ [1] "^npx\\s+tsx\\s+[^|;&]+$"
383
+ Sample: npx tsx _bmad-output/tmp/generate-theme.ts (4 occurrences)
384
+
385
+ [Question] Which patterns would you like to add?
386
+ > All recommended patterns
387
+
388
+ [Question] How should the decision log be handled?
389
+ > Archive
390
+
391
+ Applying changes...
392
+
393
+ AUTO-APPROVE OPTIMIZATION COMPLETE
394
+ ==================================
395
+
396
+ Changes Applied:
397
+ - Added 1 new allow pattern
398
+
399
+ Log Cleanup:
400
+ - Action: Archive
401
+ - Entries processed: 153
402
+ - Archive location: .claude/auto_approve_safe.decisions.archived.jsonl
403
+
404
+ To Revert Changes:
405
+ git checkout .claude/scripts/auto_approve_safe.rules.json
406
+ ```