specweave 0.24.11 → 0.24.13

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.
Files changed (55) hide show
  1. package/CLAUDE.md +158 -10
  2. package/dist/plugins/specweave-github/lib/github-client-v2.d.ts +28 -0
  3. package/dist/plugins/specweave-github/lib/github-client-v2.d.ts.map +1 -1
  4. package/dist/plugins/specweave-github/lib/github-client-v2.js +47 -0
  5. package/dist/plugins/specweave-github/lib/github-client-v2.js.map +1 -1
  6. package/dist/src/cli/commands/init.d.ts.map +1 -1
  7. package/dist/src/cli/commands/init.js +15 -7
  8. package/dist/src/cli/commands/init.js.map +1 -1
  9. package/dist/src/cli/helpers/issue-tracker/github-multi-repo.d.ts.map +1 -1
  10. package/dist/src/cli/helpers/issue-tracker/github-multi-repo.js +13 -1
  11. package/dist/src/cli/helpers/issue-tracker/github-multi-repo.js.map +1 -1
  12. package/dist/src/cli/helpers/issue-tracker/types.d.ts +1 -1
  13. package/dist/src/cli/helpers/issue-tracker/types.d.ts.map +1 -1
  14. package/dist/src/core/config/types.d.ts +46 -12
  15. package/dist/src/core/config/types.d.ts.map +1 -1
  16. package/dist/src/core/config/types.js +0 -5
  17. package/dist/src/core/config/types.js.map +1 -1
  18. package/dist/src/core/repo-structure/repo-bulk-discovery.d.ts.map +1 -1
  19. package/dist/src/core/repo-structure/repo-bulk-discovery.js +20 -5
  20. package/dist/src/core/repo-structure/repo-bulk-discovery.js.map +1 -1
  21. package/dist/src/core/repo-structure/repo-structure-manager.d.ts.map +1 -1
  22. package/dist/src/core/repo-structure/repo-structure-manager.js +29 -14
  23. package/dist/src/core/repo-structure/repo-structure-manager.js.map +1 -1
  24. package/dist/src/sync/format-preservation-sync.d.ts.map +1 -1
  25. package/dist/src/sync/format-preservation-sync.js +23 -5
  26. package/dist/src/sync/format-preservation-sync.js.map +1 -1
  27. package/dist/src/sync/frontmatter-updater.d.ts +57 -0
  28. package/dist/src/sync/frontmatter-updater.d.ts.map +1 -0
  29. package/dist/src/sync/frontmatter-updater.js +147 -0
  30. package/dist/src/sync/frontmatter-updater.js.map +1 -0
  31. package/dist/src/sync/sync-coordinator.d.ts +22 -1
  32. package/dist/src/sync/sync-coordinator.d.ts.map +1 -1
  33. package/dist/src/sync/sync-coordinator.js +268 -21
  34. package/dist/src/sync/sync-coordinator.js.map +1 -1
  35. package/dist/src/types/living-docs-us-file.d.ts +18 -0
  36. package/dist/src/types/living-docs-us-file.d.ts.map +1 -1
  37. package/dist/src/types/living-docs-us-file.js.map +1 -1
  38. package/package.json +1 -1
  39. package/plugins/specweave/.claude-plugin/plugin.json +17 -11
  40. package/plugins/specweave/agents/architect/AGENT.md +115 -45
  41. package/plugins/specweave/agents/test-aware-planner/AGENT.md +76 -6
  42. package/plugins/specweave/hooks/lib/update-status-line.sh +19 -0
  43. package/plugins/specweave/hooks/post-edit-write-consolidated.sh +335 -0
  44. package/plugins/specweave/hooks/post-metadata-change.sh +40 -6
  45. package/plugins/specweave/hooks/post-task-completion.sh +93 -9
  46. package/plugins/specweave/hooks/pre-edit-spec.sh +0 -11
  47. package/plugins/specweave/hooks/pre-edit-write-consolidated.sh +188 -0
  48. package/plugins/specweave/hooks/pre-task-completion.sh +11 -0
  49. package/plugins/specweave/hooks/pre-write-spec.sh +0 -11
  50. package/plugins/specweave/lib/hooks/consolidated-sync.js +61 -3
  51. package/plugins/specweave-github/hooks/.specweave/logs/hooks-debug.log +294 -0
  52. package/plugins/specweave-github/lib/github-client-v2.js +46 -0
  53. package/plugins/specweave-github/lib/github-client-v2.ts +65 -0
  54. package/plugins/specweave-release/commands/specweave-release-npm.md +130 -2
  55. package/plugins/specweave-release/hooks/.specweave/logs/dora-tracking.log +60 -0
@@ -0,0 +1,335 @@
1
+ #!/bin/bash
2
+ #
3
+ # Post-Edit/Write Consolidated Hook: Update Status Line After spec.md or tasks.md Changes
4
+ #
5
+ # Purpose: Unified hook for both Edit and Write tools
6
+ # Triggers: After Edit/Write modifies spec.md (AC updates) or tasks.md (task completion)
7
+ # Action: Updates status line cache to reflect latest AC/task progress
8
+ #
9
+ # CONSOLIDATION (v0.25.0):
10
+ # - Replaces post-edit-spec.sh and post-write-spec.sh (identical code)
11
+ # - Reduces hook overhead by 50% (2 post-hooks → 1)
12
+ # - Single point of maintenance
13
+ # - Combined with pre-edit-write-consolidated.sh, reduces 4 hooks → 2 hooks
14
+ #
15
+ # This ensures status line stays in sync when ACs are marked complete via Edit tool
16
+ # (not just TodoWrite, which only tracks internal todo lists)
17
+ #
18
+ # EMERGENCY FIXES (v0.24.3):
19
+ # - Kill switch: Set SPECWEAVE_DISABLE_HOOKS=1 to disable ALL hooks
20
+ # - Circuit breaker: Auto-disable after 3 consecutive failures
21
+ # - File locking: Prevent concurrent executions (max 1 at a time)
22
+ # - Aggressive debouncing: Increased from 1s to 5s
23
+ # - Complete error isolation: Never let errors reach Claude Code
24
+ #
25
+ # TIER 1 IMPROVEMENTS (v0.24.2):
26
+ # - Debouncing: Skip if updated less than 5 seconds ago (90% overhead reduction)
27
+ # - File mtime detection: Check recently modified spec.md/tasks.md as fallback
28
+ # - Non-blocking: Run update-status-line.sh in background
29
+ # - Smart detection: Only update if spec/tasks files actually changed
30
+ #
31
+ # Previous fix (v0.24.1): Enhanced file detection for increment completion
32
+ # - Detects changes via TOOL_USE_CONTENT, TOOL_RESULT, and argument parsing
33
+ # - Always updates status line for ANY spec.md/tasks.md change in increments folder
34
+
35
+ # CRITICAL: Remove set -e to prevent hook errors from crashing Claude Code
36
+ set +e
37
+
38
+ # Find project root (must be BEFORE recursion guard to get PROJECT_ROOT)
39
+ find_project_root() {
40
+ local dir="$PWD"
41
+ while [[ "$dir" != "/" ]]; do
42
+ if [[ -d "$dir/.specweave" ]]; then
43
+ echo "$dir"
44
+ return 0
45
+ fi
46
+ dir=$(dirname "$dir")
47
+ done
48
+ echo "$PWD"
49
+ }
50
+
51
+ PROJECT_ROOT=$(find_project_root)
52
+ LOGS_DIR="$PROJECT_ROOT/.specweave/logs"
53
+ DEBUG_LOG="$LOGS_DIR/hooks-debug.log"
54
+
55
+ # ============================================================================
56
+ # RECURSION PREVENTION (CRITICAL - v0.26.0 - FILE-BASED GUARD)
57
+ # ============================================================================
58
+ # PROBLEM: Hooks that write files trigger other hooks, causing infinite loops.
59
+ # OLD SOLUTION (v0.25.1): Environment variable SPECWEAVE_IN_HOOK=1
60
+ # WHY IT FAILED: Background processes (&) create NEW shells that don't inherit env vars!
61
+ #
62
+ # NEW SOLUTION (v0.26.0): File-based recursion guard
63
+ # - Guard file exists = already inside hook chain
64
+ # - Works across ALL processes (not just current shell)
65
+ # - Atomic operation (mkdir -p ensures thread safety)
66
+ # - Cleanup guaranteed by trap EXIT
67
+ #
68
+ # See: .specweave/increments/0051-*/reports/GITHUB-COMMENT-RECURSION-ROOT-CAUSE-2025-11-24.md
69
+ # See: ADR-0073 (Hook Recursion Prevention Strategy)
70
+
71
+ RECURSION_GUARD_FILE="$PROJECT_ROOT/.specweave/state/.hook-recursion-guard"
72
+
73
+ if [[ -f "$RECURSION_GUARD_FILE" ]]; then
74
+ # Silent exit - we're already inside a hook chain
75
+ # This is NORMAL and prevents recursion (not an error!)
76
+ exit 0
77
+ fi
78
+
79
+ # Don't create guard file here - we only CHECK it
80
+ # Guard file is ONLY created by post-task-completion.sh (the entry point)
81
+ # All other hooks just check for its existence
82
+
83
+ # EMERGENCY KILL SWITCH: Disable all hooks if env variable set
84
+ if [[ "${SPECWEAVE_DISABLE_HOOKS:-0}" == "1" ]]; then
85
+ exit 0
86
+ fi
87
+
88
+ # Ensure state and logs directories exist
89
+ mkdir -p "$PROJECT_ROOT/.specweave/state" "$LOGS_DIR" 2>/dev/null || true
90
+
91
+ # EMERGENCY CIRCUIT BREAKER: Track consecutive failures
92
+ CIRCUIT_BREAKER_FILE="$PROJECT_ROOT/.specweave/state/.hook-circuit-breaker"
93
+ CIRCUIT_BREAKER_THRESHOLD=3
94
+
95
+ if [[ -f "$CIRCUIT_BREAKER_FILE" ]]; then
96
+ FAILURE_COUNT=$(cat "$CIRCUIT_BREAKER_FILE" 2>/dev/null || echo 0)
97
+ if (( FAILURE_COUNT >= CIRCUIT_BREAKER_THRESHOLD )); then
98
+ echo "[$(date)] CIRCUIT BREAKER OPEN: Hooks disabled after $FAILURE_COUNT failures. Run: rm $CIRCUIT_BREAKER_FILE" >> "$DEBUG_LOG" 2>/dev/null || true
99
+ exit 0
100
+ fi
101
+ fi
102
+
103
+ # EMERGENCY FILE LOCK: Prevent concurrent executions
104
+ LOCK_FILE="$PROJECT_ROOT/.specweave/state/.hook-post-edit-write.lock"
105
+ LOCK_TIMEOUT=5 # seconds
106
+
107
+ # Try to acquire lock with timeout
108
+ LOCK_ACQUIRED=false
109
+ for i in {1..5}; do
110
+ if mkdir "$LOCK_FILE" 2>/dev/null; then
111
+ LOCK_ACQUIRED=true
112
+ trap 'rmdir "$LOCK_FILE" 2>/dev/null || true' EXIT
113
+ break
114
+ fi
115
+
116
+ # Check if lock is stale (older than LOCK_TIMEOUT seconds)
117
+ if [[ -d "$LOCK_FILE" ]]; then
118
+ LOCK_AGE=$(($(date +%s) - $(stat -f "%m" "$LOCK_FILE" 2>/dev/null || echo 0)))
119
+ if (( LOCK_AGE > LOCK_TIMEOUT )); then
120
+ rmdir "$LOCK_FILE" 2>/dev/null || true
121
+ continue
122
+ fi
123
+ fi
124
+
125
+ sleep 0.2
126
+ done
127
+
128
+ if [[ "$LOCK_ACQUIRED" == "false" ]]; then
129
+ echo "[$(date)] post-edit-write: Could not acquire lock, skipping" >> "$DEBUG_LOG" 2>/dev/null || true
130
+ exit 0
131
+ fi
132
+
133
+ # Log rotation: Keep debug log under 100KB
134
+ if [[ -f "$DEBUG_LOG" ]] && [[ $(wc -c < "$DEBUG_LOG" 2>/dev/null || echo 0) -gt 102400 ]]; then
135
+ tail -100 "$DEBUG_LOG" > "$DEBUG_LOG.tmp" 2>/dev/null || true
136
+ mv "$DEBUG_LOG.tmp" "$DEBUG_LOG" 2>/dev/null || true
137
+ echo "[$(date)] Log rotated" >> "$DEBUG_LOG" 2>/dev/null || true
138
+ fi
139
+
140
+ # ============================================================================
141
+ # BURST WRITE DETECTION (v0.26.2 - Prevent Write Storms)
142
+ # ============================================================================
143
+ # Problem: Architect agent creating multiple ADRs in one response (6+ writes/minute)
144
+ # Solution: Detect burst writes and throttle if necessary
145
+ # Incident: 2025-11-24 (Increment 0052 - architect created 6 ADRs at once)
146
+ BURST_TIMESTAMPS_FILE="$PROJECT_ROOT/.specweave/state/.write-timestamps"
147
+ BURST_WINDOW=10 # seconds
148
+ BURST_THRESHOLD=5 # max writes in window
149
+ BURST_THROTTLE=2 # seconds to wait if burst detected
150
+
151
+ # Record this write timestamp
152
+ mkdir -p "$(dirname "$BURST_TIMESTAMPS_FILE")" 2>/dev/null || true
153
+ echo "$(date +%s)" >> "$BURST_TIMESTAMPS_FILE" 2>/dev/null || true
154
+
155
+ # Count writes in the last BURST_WINDOW seconds
156
+ if [[ -f "$BURST_TIMESTAMPS_FILE" ]]; then
157
+ NOW=$(date +%s)
158
+ CUTOFF=$((NOW - BURST_WINDOW))
159
+
160
+ # Clean up old timestamps (older than BURST_WINDOW)
161
+ grep -v "^$" "$BURST_TIMESTAMPS_FILE" 2>/dev/null | \
162
+ awk -v cutoff="$CUTOFF" '$1 > cutoff' > "$BURST_TIMESTAMPS_FILE.tmp" 2>/dev/null || true
163
+ mv "$BURST_TIMESTAMPS_FILE.tmp" "$BURST_TIMESTAMPS_FILE" 2>/dev/null || true
164
+
165
+ # Count recent writes
166
+ RECENT_WRITES=$(wc -l < "$BURST_TIMESTAMPS_FILE" 2>/dev/null || echo 0)
167
+
168
+ if (( RECENT_WRITES > BURST_THRESHOLD )); then
169
+ echo "[$(date)] ⚠️ BURST DETECTED: $RECENT_WRITES writes in ${BURST_WINDOW}s (threshold: $BURST_THRESHOLD)" >> "$DEBUG_LOG" 2>/dev/null || true
170
+ echo "[$(date)] Throttling for ${BURST_THROTTLE}s to prevent overload..." >> "$DEBUG_LOG" 2>/dev/null || true
171
+ sleep "$BURST_THROTTLE"
172
+ fi
173
+ fi
174
+
175
+ # ============================================================================
176
+ # TIER 1 FIX: Debouncing (Prevent Redundant Updates)
177
+ # ============================================================================
178
+ # Skip update if we updated less than 5 seconds ago (INCREASED FROM 1s)
179
+ # This handles rapid consecutive changes (e.g., 10 tasks marked complete quickly)
180
+ LAST_UPDATE_FILE="$PROJECT_ROOT/.specweave/state/.last-status-update"
181
+ DEBOUNCE_SECONDS=5
182
+
183
+ if [[ -f "$LAST_UPDATE_FILE" ]]; then
184
+ LAST_UPDATE=$(cat "$LAST_UPDATE_FILE" 2>/dev/null || echo 0)
185
+ NOW=$(date +%s)
186
+ TIME_SINCE_UPDATE=$((NOW - LAST_UPDATE))
187
+
188
+ if (( TIME_SINCE_UPDATE < DEBOUNCE_SECONDS )); then
189
+ echo "[$(date)] post-edit-write: Debounced (${TIME_SINCE_UPDATE}s since last update)" >> "$DEBUG_LOG" 2>/dev/null || true
190
+ exit 0 # Skip this update
191
+ fi
192
+ fi
193
+
194
+ # ============================================================================
195
+ # TIER 2: Check for PreToolUse Signal (Primary Detection Method)
196
+ # ============================================================================
197
+ PENDING_FILE="$PROJECT_ROOT/.specweave/state/.pending-status-update"
198
+ METRICS_FILE="$PROJECT_ROOT/.specweave/state/hook-metrics.jsonl"
199
+ DETECTED_FILE=""
200
+ DETECTION_METHOD="none"
201
+
202
+ # First, check if PreToolUse hook left a signal
203
+ if [[ -f "$PENDING_FILE" ]]; then
204
+ DETECTED_FILE=$(cat "$PENDING_FILE" 2>/dev/null || echo "")
205
+ # Delete pending file immediately (consume signal)
206
+ rm "$PENDING_FILE" 2>/dev/null || true
207
+
208
+ if [[ -n "$DETECTED_FILE" ]]; then
209
+ DETECTION_METHOD="pretooluse"
210
+ echo "[$(date)] post-edit-write: File from PreToolUse signal: $DETECTED_FILE" >> "$DEBUG_LOG" 2>/dev/null || true
211
+
212
+ # Record Tier 2 success metric
213
+ TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ)
214
+ echo "{\"timestamp\":\"$TIMESTAMP\",\"hook\":\"post-edit-write\",\"event\":\"tier2_success\",\"method\":\"pretooluse\"}" >> "$METRICS_FILE" 2>/dev/null || true
215
+ fi
216
+ fi
217
+
218
+ # ============================================================================
219
+ # TIER 1 FALLBACK: Environment Variable Detection
220
+ # ============================================================================
221
+ # If PreToolUse didn't provide signal, fall back to Tier 1 methods
222
+ if [[ -z "$DETECTED_FILE" ]]; then
223
+ # Method 1: TOOL_USE_CONTENT environment variable
224
+ if [[ -n "${TOOL_USE_CONTENT:-}" ]]; then
225
+ DETECTED_FILE="$TOOL_USE_CONTENT"
226
+ DETECTION_METHOD="env_content"
227
+ fi
228
+
229
+ # Method 2: TOOL_RESULT environment variable
230
+ if [[ -z "$DETECTED_FILE" ]] && [[ -n "${TOOL_RESULT:-}" ]]; then
231
+ DETECTED_FILE=$(echo "$TOOL_RESULT" | grep -o '"file_path"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed 's/.*"\([^"]*\)".*/\1/' || echo "")
232
+ DETECTION_METHOD="env_result"
233
+ fi
234
+
235
+ # Method 3: TOOL_USE_ARGS
236
+ if [[ -z "$DETECTED_FILE" ]] && [[ -n "${TOOL_USE_ARGS:-}" ]]; then
237
+ DETECTED_FILE=$(echo "$TOOL_USE_ARGS" | grep -o '"file_path"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed 's/.*"\([^"]*\)".*/\1/' || echo "")
238
+ DETECTION_METHOD="env_args"
239
+ fi
240
+
241
+ # Log env var detection (for metrics)
242
+ if [[ -n "$DETECTED_FILE" ]]; then
243
+ echo "[$(date)] post-edit-write: File from env vars ($DETECTION_METHOD): $DETECTED_FILE" >> "$DEBUG_LOG" 2>/dev/null || true
244
+ fi
245
+ fi
246
+
247
+ # Check if we detected a spec.md or tasks.md change in increments folder
248
+ SHOULD_UPDATE=false
249
+
250
+ if [[ -n "$DETECTED_FILE" ]]; then
251
+ # Check if the file is spec.md or tasks.md
252
+ if [[ "$DETECTED_FILE" == *"/spec.md" ]] || [[ "$DETECTED_FILE" == *"/tasks.md" ]]; then
253
+ # Check if it's in an increment folder
254
+ if [[ "$DETECTED_FILE" == *"/.specweave/increments/"* ]]; then
255
+ SHOULD_UPDATE=true
256
+ echo "[$(date)] post-edit-write: Increment file changed - will update status line" >> "$DEBUG_LOG" 2>/dev/null || true
257
+ fi
258
+ fi
259
+ fi
260
+
261
+ # ============================================================================
262
+ # TIER 1 FIX: File Modification Time Detection (Fallback)
263
+ # ============================================================================
264
+ # If we couldn't detect the file via environment variables, check which files
265
+ # were modified recently (within last 2 seconds) instead of blindly updating
266
+ if [[ -z "$DETECTED_FILE" ]]; then
267
+ echo "[$(date)] post-edit-write: Env vars empty - checking file mtimes" >> "$DEBUG_LOG" 2>/dev/null || true
268
+
269
+ NOW=$(date +%s)
270
+ INCREMENTS_DIR="$PROJECT_ROOT/.specweave/increments"
271
+
272
+ # Check for recently modified spec.md or tasks.md files
273
+ if [[ -d "$INCREMENTS_DIR" ]]; then
274
+ for file in "$INCREMENTS_DIR"/*/spec.md "$INCREMENTS_DIR"/*/tasks.md; do
275
+ if [[ -f "$file" ]]; then
276
+ # Get file modification time (platform-specific)
277
+ if [[ "$(uname)" == "Darwin" ]]; then
278
+ MTIME=$(stat -f "%m" "$file" 2>/dev/null || echo 0)
279
+ else
280
+ MTIME=$(stat -c "%Y" "$file" 2>/dev/null || echo 0)
281
+ fi
282
+
283
+ # If file was modified in last 2 seconds, consider it the changed file
284
+ TIME_DIFF=$((NOW - MTIME))
285
+ if (( TIME_DIFF <= 2 )); then
286
+ DETECTED_FILE="$file"
287
+ echo "[$(date)] post-edit-write: Detected recent modification: $file (${TIME_DIFF}s ago)" >> "$DEBUG_LOG" 2>/dev/null || true
288
+ SHOULD_UPDATE=true
289
+ break
290
+ fi
291
+ fi
292
+ done
293
+ fi
294
+
295
+ # If still no file detected, skip update (not a spec/tasks change)
296
+ if [[ -z "$DETECTED_FILE" ]]; then
297
+ echo "[$(date)] post-edit-write: No spec/tasks modifications detected - skipping" >> "$DEBUG_LOG" 2>/dev/null || true
298
+ exit 0
299
+ fi
300
+ fi
301
+
302
+ # ============================================================================
303
+ # TIER 1 FIX: Non-Blocking Background Update with COMPLETE ERROR ISOLATION
304
+ # ============================================================================
305
+ # Update status line if needed
306
+ if [[ "$SHOULD_UPDATE" == "true" ]]; then
307
+ echo "[$(date)] post-edit-write: Running update-status-line.sh (background)" >> "$DEBUG_LOG" 2>/dev/null || true
308
+
309
+ # Record update time BEFORE spawning background process
310
+ # This ensures debouncing works even if update hasn't completed yet
311
+ echo "$(date +%s)" > "$LAST_UPDATE_FILE"
312
+
313
+ # Run status line update in background with COMPLETE error isolation
314
+ # This prevents Edit/Write tool from waiting for status line computation
315
+ (
316
+ set +e # Disable error propagation
317
+
318
+ if "$PROJECT_ROOT/plugins/specweave/hooks/lib/update-status-line.sh" 2>&1 | tee -a "$DEBUG_LOG" >/dev/null; then
319
+ echo "[$(date)] post-edit-write: Status line updated successfully" >> "$DEBUG_LOG" 2>/dev/null || true
320
+ # Reset circuit breaker on success
321
+ echo "0" > "$CIRCUIT_BREAKER_FILE" 2>/dev/null || true
322
+ else
323
+ echo "[$(date)] post-edit-write: Warning - status line update failed (non-blocking)" >> "$DEBUG_LOG" 2>/dev/null || true
324
+ # Increment circuit breaker
325
+ CURRENT_FAILURES=$(cat "$CIRCUIT_BREAKER_FILE" 2>/dev/null || echo 0)
326
+ echo "$((CURRENT_FAILURES + 1))" > "$CIRCUIT_BREAKER_FILE" 2>/dev/null || true
327
+ fi
328
+ ) &
329
+
330
+ # Disown the background process so it's not killed when hook exits
331
+ disown 2>/dev/null || true
332
+ fi
333
+
334
+ # Always exit 0 to prevent hook errors from crashing Claude Code
335
+ exit 0
@@ -22,12 +22,7 @@
22
22
  # EMERGENCY FIX v0.24.3: Remove set -e - it causes Claude Code crashes!
23
23
  set +e
24
24
 
25
- # EMERGENCY KILL SWITCH
26
- if [[ "${SPECWEAVE_DISABLE_HOOKS:-0}" == "1" ]]; then
27
- exit 0
28
- fi
29
-
30
- # Find project root
25
+ # Find project root (must be BEFORE recursion guard to get PROJECT_ROOT)
31
26
  find_project_root() {
32
27
  local dir="$PWD"
33
28
  while [[ "$dir" != "/" ]]; do
@@ -45,9 +40,48 @@ LOGS_DIR="$PROJECT_ROOT/.specweave/logs"
45
40
  DEBUG_LOG="$LOGS_DIR/hooks-debug.log"
46
41
  HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
47
42
 
43
+ # ============================================================================
44
+ # RECURSION PREVENTION (CRITICAL - v0.26.0 - FILE-BASED GUARD)
45
+ # ============================================================================
46
+ # NEW SOLUTION (v0.26.0): File-based recursion guard
47
+ # See: ADR-0073 (Hook Recursion Prevention Strategy)
48
+
49
+ RECURSION_GUARD_FILE="$PROJECT_ROOT/.specweave/state/.hook-recursion-guard"
50
+
51
+ if [[ -f "$RECURSION_GUARD_FILE" ]]; then
52
+ # Silent exit - we're already inside a hook chain
53
+ exit 0
54
+ fi
55
+
56
+ # EMERGENCY KILL SWITCH
57
+ if [[ "${SPECWEAVE_DISABLE_HOOKS:-0}" == "1" ]]; then
58
+ exit 0
59
+ fi
60
+
48
61
  # Ensure logs directory exists
49
62
  mkdir -p "$LOGS_DIR" 2>/dev/null || true
50
63
 
64
+ # ============================================================================
65
+ # EARLY EXIT OPTIMIZATION (v0.25.0): Ultra-Fast Rejection of Non-Metadata Changes
66
+ # ============================================================================
67
+ # This hook should ONLY run for metadata.json changes.
68
+ # 99.9% of Edit/Write operations are NOT metadata.json.
69
+ # Do fastest possible check first to minimize overhead.
70
+
71
+ # Quick check: If TOOL_USE_CONTENT doesn't contain "metadata.json", exit immediately
72
+ if [[ -n "${TOOL_USE_CONTENT:-}" ]] && [[ "$TOOL_USE_CONTENT" != *"metadata.json"* ]]; then
73
+ exit 0 # Fast path: Not metadata.json
74
+ fi
75
+
76
+ # Quick check: If TOOL_USE_ARGS doesn't contain "metadata.json", exit immediately
77
+ if [[ -n "${TOOL_USE_ARGS:-}" ]] && [[ "$TOOL_USE_ARGS" != *"metadata.json"* ]]; then
78
+ exit 0 # Fast path: Not metadata.json
79
+ fi
80
+
81
+ # ============================================================================
82
+ # STANDARD FILE DETECTION (Only if quick checks passed)
83
+ # ============================================================================
84
+
51
85
  # Extract modified file from environment variables (Claude Code provides this)
52
86
  MODIFIED_FILE=""
53
87
 
@@ -36,10 +36,13 @@
36
36
 
37
37
  set +e # NEVER use set -e in hooks - it causes crashes
38
38
 
39
- # EMERGENCY KILL SWITCH FIRST (before anything else)
40
- if [[ "${SPECWEAVE_DISABLE_HOOKS:-0}" == "1" ]]; then
41
- exit 0
42
- fi
39
+ # ============================================================================
40
+ # PROJECT ROOT DETECTION (MUST BE FIRST - v0.26.1 FIX)
41
+ # ============================================================================
42
+ # CRITICAL FIX: PROJECT_ROOT must be defined BEFORE recursion guard creation
43
+ # BUG (v0.26.0): Used $PROJECT_ROOT on line 71 but defined it on line 112
44
+ # RESULT: Guard file created at wrong path (/.specweave/...) → recursion not prevented
45
+ # See: Incident 2025-11-24 (3x PreToolUse hook fires, Claude Code crash)
43
46
 
44
47
  # Find project root by searching upward for .specweave/ directory
45
48
  # Works regardless of where hook is installed (source or .claude/hooks/)
@@ -63,6 +66,60 @@ find_project_root() {
63
66
  PROJECT_ROOT="$(find_project_root "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")"
64
67
  cd "$PROJECT_ROOT" 2>/dev/null || true
65
68
 
69
+ # ============================================================================
70
+ # RECURSION PREVENTION (CRITICAL - v0.26.0 - FILE-BASED GUARD)
71
+ # ============================================================================
72
+ # PROBLEM: Hooks that write files trigger other hooks, causing infinite loops.
73
+ # OLD SOLUTION (v0.25.1): Environment variable SPECWEAVE_IN_HOOK=1
74
+ # WHY IT FAILED: Background processes (&) create NEW shells that don't inherit env vars!
75
+ #
76
+ # NEW SOLUTION (v0.26.0): File-based recursion guard
77
+ # - Guard file exists = already inside hook chain
78
+ # - Works across ALL processes (not just current shell)
79
+ # - Atomic operation (mkdir -p ensures thread safety)
80
+ # - Cleanup guaranteed by trap EXIT
81
+ #
82
+ # Example infinite loop (BEFORE fix):
83
+ # TodoWrite → post-task-completion.sh (sets SPECWEAVE_IN_HOOK=1)
84
+ # → spawns background process (&)
85
+ # → consolidated-sync.js (SPECWEAVE_IN_HOOK=0! lost!)
86
+ # → fs.writeFile(tasks.md)
87
+ # → post-edit-write-consolidated.sh (guard fails!)
88
+ # → INFINITE RECURSION → 27 duplicate GitHub comments!
89
+ #
90
+ # With file-based guard (AFTER fix):
91
+ # TodoWrite → post-task-completion.sh (creates .hook-recursion-guard file)
92
+ # → spawns background process (&)
93
+ # → consolidated-sync.js (inherits guard file!)
94
+ # → fs.writeFile(tasks.md)
95
+ # → post-edit-write-consolidated.sh (checks file, exits)
96
+ # → NO RECURSION ✅
97
+ #
98
+ # See: .specweave/increments/0051-*/reports/GITHUB-COMMENT-RECURSION-ROOT-CAUSE-2025-11-24.md
99
+ # See: ADR-0073 (Hook Recursion Prevention Strategy)
100
+
101
+ RECURSION_GUARD_FILE="$PROJECT_ROOT/.specweave/state/.hook-recursion-guard"
102
+
103
+ if [[ -f "$RECURSION_GUARD_FILE" ]]; then
104
+ # Silent exit - we're already inside a hook chain
105
+ echo "[$(date)] ⏭️ Recursion guard detected - skipping (already in hook)" >> "$DEBUG_LOG" 2>/dev/null || true
106
+ exit 0
107
+ fi
108
+
109
+ # Create guard file (atomic operation)
110
+ mkdir -p "$PROJECT_ROOT/.specweave/state" 2>/dev/null || true
111
+ touch "$RECURSION_GUARD_FILE"
112
+
113
+ # Ensure guard file is ALWAYS removed when script exits (even on error)
114
+ trap 'rm -f "$RECURSION_GUARD_FILE" 2>/dev/null || true' EXIT SIGINT SIGTERM
115
+
116
+ echo "[$(date)] 🔒 Recursion guard created" >> "$DEBUG_LOG" 2>/dev/null || true
117
+
118
+ # EMERGENCY KILL SWITCH (after recursion guard)
119
+ if [[ "${SPECWEAVE_DISABLE_HOOKS:-0}" == "1" ]]; then
120
+ exit 0
121
+ fi
122
+
66
123
  # ============================================================================
67
124
  # EMERGENCY SAFETY CHECKS
68
125
  # ============================================================================
@@ -349,13 +406,25 @@ fi
349
406
  # ============================================================================
350
407
  # CONSOLIDATED SYNC (v0.24.4 - PERFORMANCE OPTIMIZATION)
351
408
  # ============================================================================
352
- # REPLACES: 5-6 separate Node.js spawns with SINGLE consolidated process
353
- # BEFORE: update-tasks-md.js, sync-living-docs.js, update-ac-status.js,
354
- # translate-living-docs.js, prepare-reflection-context.js
355
- # AFTER: consolidated-sync.js (runs all operations sequentially)
356
- # IMPACT: 83% reduction in process spawning overhead
409
+ # EMERGENCY FIX (v0.26.0-hotfix): DISABLED TO PREVENT CLAUDE CODE CRASHES
410
+ #
411
+ # ROOT CAUSE: consolidated-sync.js makes 5+ Edit/Write operations, each triggering
412
+ # 3 hooks (PreToolUse, PostToolUse×2), resulting in 15+ hook invocations per task.
413
+ # This causes process exhaustion and Claude Code crashes.
414
+ #
415
+ # NEW STRATEGY: Run consolidated sync ONLY at:
416
+ # 1. Session end (all tasks done + 120s inactivity)
417
+ # 2. Manual sync (/specweave:sync-docs command)
418
+ # 3. Increment closure (/specweave:done validation)
419
+ #
420
+ # See: .specweave/increments/0051-*/reports/CLAUDE-CODE-CRASH-ROOT-CAUSE-2025-11-23.md
421
+ # See: ADR-0072 (Post-Task Hook Simplification)
357
422
  # ============================================================================
358
423
 
424
+ # RE-ENABLED: Automatic sync on each TodoWrite (ACCEPTING CRASH RISK)
425
+ # WARNING: This can cause Claude Code crashes if too many TodoWrite events fire rapidly
426
+ # User explicitly requested re-enabling despite crash risk
427
+
359
428
  echo "[$(date)] 🚀 Running consolidated sync" >> "$DEBUG_LOG" 2>/dev/null || true
360
429
 
361
430
  # Find consolidated sync script
@@ -371,6 +440,21 @@ fi
371
440
  fi
372
441
 
373
442
  if [ -n "$CONSOLIDATED_SCRIPT" ]; then
443
+ # Load GITHUB_TOKEN from .env for gh CLI authentication
444
+ if [ -f "$PROJECT_ROOT/.env" ]; then
445
+ # Extract GITHUB_TOKEN from .env (handles various formats)
446
+ GITHUB_TOKEN_FROM_ENV=$(grep -E '^GITHUB_TOKEN=' "$PROJECT_ROOT/.env" 2>/dev/null | head -1 | cut -d'=' -f2- | sed 's/^["'\'']//' | sed 's/["'\'']$//')
447
+ if [ -n "$GITHUB_TOKEN_FROM_ENV" ]; then
448
+ export GITHUB_TOKEN="$GITHUB_TOKEN_FROM_ENV"
449
+ echo "[$(date)] ✅ GitHub token loaded from .env" >> "$DEBUG_LOG" 2>/dev/null || true
450
+ fi
451
+ fi
452
+
453
+ # FIX (v0.26.0): Skip GitHub sync in post-task-completion hook
454
+ # GitHub sync should ONLY run on increment COMPLETION, not task completion
455
+ # This prevents 27 duplicate comments (see root cause analysis)
456
+ export SKIP_GITHUB_SYNC=true
457
+
374
458
  # Run consolidated sync (single Node.js process handles ALL operations)
375
459
  if (cd "$PROJECT_ROOT" && node "$CONSOLIDATED_SCRIPT" "$CURRENT_INCREMENT") >> "$DEBUG_LOG" 2>&1; then
376
460
  echo "[$(date)] ✅ Consolidated sync completed" >> "$DEBUG_LOG" 2>/dev/null || true
@@ -101,17 +101,6 @@ else
101
101
  exit 0 # Let PostToolUse handle it with mtime fallback
102
102
  fi
103
103
 
104
- # ============================================================================
105
- # EARLY EXIT: Only process .specweave/ files (v0.24.4 Performance Fix)
106
- # ============================================================================
107
- # 90% of Edit operations are on non-SpecWeave files (src/, tests/, node_modules/)
108
- # Exit immediately for non-.specweave/ files to reduce hook overhead by 90%
109
-
110
- if [[ "$FILE_PATH" != *"/.specweave/"* ]]; then
111
- echo "[$(date)] pre-edit-spec: Not a .specweave/ file, skipping (performance optimization)" >> "$DEBUG_LOG" 2>/dev/null || true
112
- exit 0
113
- fi
114
-
115
104
  # Check if this is a spec.md or tasks.md file in increments folder
116
105
  IS_SPEC_FILE=false
117
106
  if [[ "$FILE_PATH" == *"/spec.md" ]] || [[ "$FILE_PATH" == *"/tasks.md" ]]; then