stop-hook.sh 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/bin/bash
  2. # Ralph Loop Stop Hook
  3. # Prevents session exit when a ralph-loop is active
  4. # Feeds Claude's output back as input to continue the loop
  5. set -euo pipefail
  6. # Read hook input from stdin (advanced stop hook API)
  7. HOOK_INPUT=$(cat)
  8. # Check if ralph-loop is active
  9. RALPH_STATE_FILE=".claude/ralph-loop.local.md"
  10. if [[ ! -f "$RALPH_STATE_FILE" ]]; then
  11. # No active loop - allow exit
  12. exit 0
  13. fi
  14. # Parse markdown frontmatter (YAML between ---) and extract values
  15. FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$RALPH_STATE_FILE")
  16. ITERATION=$(echo "$FRONTMATTER" | grep '^iteration:' | sed 's/iteration: *//')
  17. MAX_ITERATIONS=$(echo "$FRONTMATTER" | grep '^max_iterations:' | sed 's/max_iterations: *//')
  18. # Extract completion_promise and strip surrounding quotes if present
  19. COMPLETION_PROMISE=$(echo "$FRONTMATTER" | grep '^completion_promise:' | sed 's/completion_promise: *//' | sed 's/^"\(.*\)"$/\1/')
  20. # Validate numeric fields before arithmetic operations
  21. if [[ ! "$ITERATION" =~ ^[0-9]+$ ]]; then
  22. echo "⚠️ Ralph loop: State file corrupted" >&2
  23. echo " File: $RALPH_STATE_FILE" >&2
  24. echo " Problem: 'iteration' field is not a valid number (got: '$ITERATION')" >&2
  25. echo "" >&2
  26. echo " This usually means the state file was manually edited or corrupted." >&2
  27. echo " Ralph loop is stopping. Run /ralph-loop again to start fresh." >&2
  28. rm "$RALPH_STATE_FILE"
  29. exit 0
  30. fi
  31. if [[ ! "$MAX_ITERATIONS" =~ ^[0-9]+$ ]]; then
  32. echo "⚠️ Ralph loop: State file corrupted" >&2
  33. echo " File: $RALPH_STATE_FILE" >&2
  34. echo " Problem: 'max_iterations' field is not a valid number (got: '$MAX_ITERATIONS')" >&2
  35. echo "" >&2
  36. echo " This usually means the state file was manually edited or corrupted." >&2
  37. echo " Ralph loop is stopping. Run /ralph-loop again to start fresh." >&2
  38. rm "$RALPH_STATE_FILE"
  39. exit 0
  40. fi
  41. # Check if max iterations reached
  42. if [[ $MAX_ITERATIONS -gt 0 ]] && [[ $ITERATION -ge $MAX_ITERATIONS ]]; then
  43. echo "🛑 Ralph loop: Max iterations ($MAX_ITERATIONS) reached."
  44. rm "$RALPH_STATE_FILE"
  45. exit 0
  46. fi
  47. # Get transcript path from hook input
  48. TRANSCRIPT_PATH=$(echo "$HOOK_INPUT" | jq -r '.transcript_path')
  49. if [[ ! -f "$TRANSCRIPT_PATH" ]]; then
  50. echo "⚠️ Ralph loop: Transcript file not found" >&2
  51. echo " Expected: $TRANSCRIPT_PATH" >&2
  52. echo " This is unusual and may indicate a Claude Code internal issue." >&2
  53. echo " Ralph loop is stopping." >&2
  54. rm "$RALPH_STATE_FILE"
  55. exit 0
  56. fi
  57. # Read last assistant message from transcript (JSONL format - one JSON per line)
  58. # First check if there are any assistant messages
  59. if ! grep -q '"role":"assistant"' "$TRANSCRIPT_PATH"; then
  60. echo "⚠️ Ralph loop: No assistant messages found in transcript" >&2
  61. echo " Transcript: $TRANSCRIPT_PATH" >&2
  62. echo " This is unusual and may indicate a transcript format issue" >&2
  63. echo " Ralph loop is stopping." >&2
  64. rm "$RALPH_STATE_FILE"
  65. exit 0
  66. fi
  67. # Extract last assistant message with explicit error handling
  68. LAST_LINE=$(grep '"role":"assistant"' "$TRANSCRIPT_PATH" | tail -1)
  69. if [[ -z "$LAST_LINE" ]]; then
  70. echo "⚠️ Ralph loop: Failed to extract last assistant message" >&2
  71. echo " Ralph loop is stopping." >&2
  72. rm "$RALPH_STATE_FILE"
  73. exit 0
  74. fi
  75. # Parse JSON with error handling
  76. LAST_OUTPUT=$(echo "$LAST_LINE" | jq -r '
  77. .message.content |
  78. map(select(.type == "text")) |
  79. map(.text) |
  80. join("\n")
  81. ' 2>&1)
  82. # Check if jq succeeded
  83. if [[ $? -ne 0 ]]; then
  84. echo "⚠️ Ralph loop: Failed to parse assistant message JSON" >&2
  85. echo " Error: $LAST_OUTPUT" >&2
  86. echo " This may indicate a transcript format issue" >&2
  87. echo " Ralph loop is stopping." >&2
  88. rm "$RALPH_STATE_FILE"
  89. exit 0
  90. fi
  91. if [[ -z "$LAST_OUTPUT" ]]; then
  92. echo "⚠️ Ralph loop: Assistant message contained no text content" >&2
  93. echo " Ralph loop is stopping." >&2
  94. rm "$RALPH_STATE_FILE"
  95. exit 0
  96. fi
  97. # Check for completion promise (only if set)
  98. if [[ "$COMPLETION_PROMISE" != "null" ]] && [[ -n "$COMPLETION_PROMISE" ]]; then
  99. # Extract text from <promise> tags using Perl for multiline support
  100. # -0777 slurps entire input, s flag makes . match newlines
  101. # .*? is non-greedy (takes FIRST tag), whitespace normalized
  102. PROMISE_TEXT=$(echo "$LAST_OUTPUT" | perl -0777 -pe 's/.*?<promise>(.*?)<\/promise>.*/$1/s; s/^\s+|\s+$//g; s/\s+/ /g' 2>/dev/null || echo "")
  103. # Use = for literal string comparison (not pattern matching)
  104. # == in [[ ]] does glob pattern matching which breaks with *, ?, [ characters
  105. if [[ -n "$PROMISE_TEXT" ]] && [[ "$PROMISE_TEXT" = "$COMPLETION_PROMISE" ]]; then
  106. echo "✅ Ralph loop: Detected <promise>$COMPLETION_PROMISE</promise>"
  107. rm "$RALPH_STATE_FILE"
  108. exit 0
  109. fi
  110. fi
  111. # Not complete - continue loop with SAME PROMPT
  112. NEXT_ITERATION=$((ITERATION + 1))
  113. # Extract prompt (everything after the closing ---)
  114. # Skip first --- line, skip until second --- line, then print everything after
  115. # Use i>=2 instead of i==2 to handle --- in prompt content
  116. PROMPT_TEXT=$(awk '/^---$/{i++; next} i>=2' "$RALPH_STATE_FILE")
  117. if [[ -z "$PROMPT_TEXT" ]]; then
  118. echo "⚠️ Ralph loop: State file corrupted or incomplete" >&2
  119. echo " File: $RALPH_STATE_FILE" >&2
  120. echo " Problem: No prompt text found" >&2
  121. echo "" >&2
  122. echo " This usually means:" >&2
  123. echo " • State file was manually edited" >&2
  124. echo " • File was corrupted during writing" >&2
  125. echo "" >&2
  126. echo " Ralph loop is stopping. Run /ralph-loop again to start fresh." >&2
  127. rm "$RALPH_STATE_FILE"
  128. exit 0
  129. fi
  130. # Update iteration in frontmatter (portable across macOS and Linux)
  131. # Create temp file, then atomically replace
  132. TEMP_FILE="${RALPH_STATE_FILE}.tmp.$$"
  133. sed "s/^iteration: .*/iteration: $NEXT_ITERATION/" "$RALPH_STATE_FILE" > "$TEMP_FILE"
  134. mv "$TEMP_FILE" "$RALPH_STATE_FILE"
  135. # Build system message with iteration count and completion promise info
  136. if [[ "$COMPLETION_PROMISE" != "null" ]] && [[ -n "$COMPLETION_PROMISE" ]]; then
  137. SYSTEM_MSG="🔄 Ralph iteration $NEXT_ITERATION | To stop: output <promise>$COMPLETION_PROMISE</promise> (ONLY when statement is TRUE - do not lie to exit!)"
  138. else
  139. SYSTEM_MSG="🔄 Ralph iteration $NEXT_ITERATION | No completion promise set - loop runs infinitely"
  140. fi
  141. # Output JSON to block the stop and feed prompt back
  142. # The "reason" field contains the prompt that will be sent back to Claude
  143. jq -n \
  144. --arg prompt "$PROMPT_TEXT" \
  145. --arg msg "$SYSTEM_MSG" \
  146. '{
  147. "decision": "block",
  148. "reason": $prompt,
  149. "systemMessage": $msg
  150. }'
  151. # Exit 0 for successful hook execution
  152. exit 0