stop-hook.sh 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. # Session isolation: the state file is project-scoped, but the Stop hook
  21. # fires in every Claude Code session in that project. If another session
  22. # started the loop, this session must not block (or touch the state file).
  23. # Legacy state files without session_id fall through (preserves old behavior).
  24. STATE_SESSION=$(echo "$FRONTMATTER" | grep '^session_id:' | sed 's/session_id: *//' || true)
  25. HOOK_SESSION=$(echo "$HOOK_INPUT" | jq -r '.session_id // ""')
  26. if [[ -n "$STATE_SESSION" ]] && [[ "$STATE_SESSION" != "$HOOK_SESSION" ]]; then
  27. exit 0
  28. fi
  29. # Validate numeric fields before arithmetic operations
  30. if [[ ! "$ITERATION" =~ ^[0-9]+$ ]]; then
  31. echo "⚠️ Ralph loop: State file corrupted" >&2
  32. echo " File: $RALPH_STATE_FILE" >&2
  33. echo " Problem: 'iteration' field is not a valid number (got: '$ITERATION')" >&2
  34. echo "" >&2
  35. echo " This usually means the state file was manually edited or corrupted." >&2
  36. echo " Ralph loop is stopping. Run /ralph-loop again to start fresh." >&2
  37. rm "$RALPH_STATE_FILE"
  38. exit 0
  39. fi
  40. if [[ ! "$MAX_ITERATIONS" =~ ^[0-9]+$ ]]; then
  41. echo "⚠️ Ralph loop: State file corrupted" >&2
  42. echo " File: $RALPH_STATE_FILE" >&2
  43. echo " Problem: 'max_iterations' field is not a valid number (got: '$MAX_ITERATIONS')" >&2
  44. echo "" >&2
  45. echo " This usually means the state file was manually edited or corrupted." >&2
  46. echo " Ralph loop is stopping. Run /ralph-loop again to start fresh." >&2
  47. rm "$RALPH_STATE_FILE"
  48. exit 0
  49. fi
  50. # Check if max iterations reached
  51. if [[ $MAX_ITERATIONS -gt 0 ]] && [[ $ITERATION -ge $MAX_ITERATIONS ]]; then
  52. echo "🛑 Ralph loop: Max iterations ($MAX_ITERATIONS) reached."
  53. rm "$RALPH_STATE_FILE"
  54. exit 0
  55. fi
  56. # Get transcript path from hook input
  57. TRANSCRIPT_PATH=$(echo "$HOOK_INPUT" | jq -r '.transcript_path')
  58. if [[ ! -f "$TRANSCRIPT_PATH" ]]; then
  59. echo "⚠️ Ralph loop: Transcript file not found" >&2
  60. echo " Expected: $TRANSCRIPT_PATH" >&2
  61. echo " This is unusual and may indicate a Claude Code internal issue." >&2
  62. echo " Ralph loop is stopping." >&2
  63. rm "$RALPH_STATE_FILE"
  64. exit 0
  65. fi
  66. # Read last assistant message from transcript (JSONL format - one JSON per line)
  67. # First check if there are any assistant messages
  68. if ! grep -q '"role":"assistant"' "$TRANSCRIPT_PATH"; then
  69. echo "⚠️ Ralph loop: No assistant messages found in transcript" >&2
  70. echo " Transcript: $TRANSCRIPT_PATH" >&2
  71. echo " This is unusual and may indicate a transcript format issue" >&2
  72. echo " Ralph loop is stopping." >&2
  73. rm "$RALPH_STATE_FILE"
  74. exit 0
  75. fi
  76. # Extract the most recent assistant text block.
  77. #
  78. # Claude Code writes each content block (text/tool_use/thinking) as its own
  79. # JSONL line, all with role=assistant. So slurp the last N assistant lines,
  80. # flatten to text blocks only, and take the last one.
  81. #
  82. # Capped at the last 100 assistant lines to keep jq's slurp input bounded
  83. # for long-running sessions.
  84. LAST_LINES=$(grep '"role":"assistant"' "$TRANSCRIPT_PATH" | tail -n 100)
  85. if [[ -z "$LAST_LINES" ]]; then
  86. echo "⚠️ Ralph loop: Failed to extract assistant messages" >&2
  87. echo " Ralph loop is stopping." >&2
  88. rm "$RALPH_STATE_FILE"
  89. exit 0
  90. fi
  91. # Parse the recent lines and pull out the final text block.
  92. # `last // ""` yields empty string when no text blocks exist (e.g. a turn
  93. # that is all tool calls). That's fine: empty text means no <promise> tag,
  94. # so the loop simply continues.
  95. # (Briefly disable errexit so a jq failure can be caught by the $? check.)
  96. set +e
  97. LAST_OUTPUT=$(echo "$LAST_LINES" | jq -rs '
  98. map(.message.content[]? | select(.type == "text") | .text) | last // ""
  99. ' 2>&1)
  100. JQ_EXIT=$?
  101. set -e
  102. # Check if jq succeeded
  103. if [[ $JQ_EXIT -ne 0 ]]; then
  104. echo "⚠️ Ralph loop: Failed to parse assistant message JSON" >&2
  105. echo " Error: $LAST_OUTPUT" >&2
  106. echo " This may indicate a transcript format issue." >&2
  107. echo " Ralph loop is stopping." >&2
  108. rm "$RALPH_STATE_FILE"
  109. exit 0
  110. fi
  111. # Check for completion promise (only if set)
  112. if [[ "$COMPLETION_PROMISE" != "null" ]] && [[ -n "$COMPLETION_PROMISE" ]]; then
  113. # Extract text from <promise> tags using Perl for multiline support
  114. # -0777 slurps entire input, s flag makes . match newlines
  115. # .*? is non-greedy (takes FIRST tag), whitespace normalized
  116. PROMISE_TEXT=$(echo "$LAST_OUTPUT" | perl -0777 -pe 's/.*?<promise>(.*?)<\/promise>.*/$1/s; s/^\s+|\s+$//g; s/\s+/ /g' 2>/dev/null || echo "")
  117. # Use = for literal string comparison (not pattern matching)
  118. # == in [[ ]] does glob pattern matching which breaks with *, ?, [ characters
  119. if [[ -n "$PROMISE_TEXT" ]] && [[ "$PROMISE_TEXT" = "$COMPLETION_PROMISE" ]]; then
  120. echo "✅ Ralph loop: Detected <promise>$COMPLETION_PROMISE</promise>"
  121. rm "$RALPH_STATE_FILE"
  122. exit 0
  123. fi
  124. fi
  125. # Not complete - continue loop with SAME PROMPT
  126. NEXT_ITERATION=$((ITERATION + 1))
  127. # Extract prompt (everything after the closing ---)
  128. # Skip first --- line, skip until second --- line, then print everything after
  129. # Use i>=2 instead of i==2 to handle --- in prompt content
  130. PROMPT_TEXT=$(awk '/^---$/{i++; next} i>=2' "$RALPH_STATE_FILE")
  131. if [[ -z "$PROMPT_TEXT" ]]; then
  132. echo "⚠️ Ralph loop: State file corrupted or incomplete" >&2
  133. echo " File: $RALPH_STATE_FILE" >&2
  134. echo " Problem: No prompt text found" >&2
  135. echo "" >&2
  136. echo " This usually means:" >&2
  137. echo " • State file was manually edited" >&2
  138. echo " • File was corrupted during writing" >&2
  139. echo "" >&2
  140. echo " Ralph loop is stopping. Run /ralph-loop again to start fresh." >&2
  141. rm "$RALPH_STATE_FILE"
  142. exit 0
  143. fi
  144. # Update iteration in frontmatter (portable across macOS and Linux)
  145. # Create temp file, then atomically replace
  146. TEMP_FILE="${RALPH_STATE_FILE}.tmp.$$"
  147. sed "s/^iteration: .*/iteration: $NEXT_ITERATION/" "$RALPH_STATE_FILE" > "$TEMP_FILE"
  148. mv "$TEMP_FILE" "$RALPH_STATE_FILE"
  149. # Build system message with iteration count and completion promise info
  150. if [[ "$COMPLETION_PROMISE" != "null" ]] && [[ -n "$COMPLETION_PROMISE" ]]; then
  151. SYSTEM_MSG="🔄 Ralph iteration $NEXT_ITERATION | To stop: output <promise>$COMPLETION_PROMISE</promise> (ONLY when statement is TRUE - do not lie to exit!)"
  152. else
  153. SYSTEM_MSG="🔄 Ralph iteration $NEXT_ITERATION | No completion promise set - loop runs infinitely"
  154. fi
  155. # Output JSON to block the stop and feed prompt back
  156. # The "reason" field contains the prompt that will be sent back to Claude
  157. jq -n \
  158. --arg prompt "$PROMPT_TEXT" \
  159. --arg msg "$SYSTEM_MSG" \
  160. '{
  161. "decision": "block",
  162. "reason": $prompt,
  163. "systemMessage": $msg
  164. }'
  165. # Exit 0 for successful hook execution
  166. exit 0