stop-hook.sh 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. `tail -1` alone would often grab a
  80. # tool_use or thinking block, leaving no text to check. Instead, slurp all
  81. # assistant lines, flatten to text blocks only, and take the last one.
  82. #
  83. # `last // ""` yields empty string when no text blocks exist (e.g. a turn
  84. # that is all tool calls). That's fine: empty text means no <promise> tag,
  85. # so the loop simply continues.
  86. LAST_OUTPUT=$(grep '"role":"assistant"' "$TRANSCRIPT_PATH" | jq -rs '
  87. map(.message.content[]? | select(.type == "text") | .text) | last // ""
  88. ' 2>/dev/null) || LAST_OUTPUT=""
  89. # Check for completion promise (only if set)
  90. if [[ "$COMPLETION_PROMISE" != "null" ]] && [[ -n "$COMPLETION_PROMISE" ]]; then
  91. # Extract text from <promise> tags using Perl for multiline support
  92. # -0777 slurps entire input, s flag makes . match newlines
  93. # .*? is non-greedy (takes FIRST tag), whitespace normalized
  94. PROMISE_TEXT=$(echo "$LAST_OUTPUT" | perl -0777 -pe 's/.*?<promise>(.*?)<\/promise>.*/$1/s; s/^\s+|\s+$//g; s/\s+/ /g' 2>/dev/null || echo "")
  95. # Use = for literal string comparison (not pattern matching)
  96. # == in [[ ]] does glob pattern matching which breaks with *, ?, [ characters
  97. if [[ -n "$PROMISE_TEXT" ]] && [[ "$PROMISE_TEXT" = "$COMPLETION_PROMISE" ]]; then
  98. echo "✅ Ralph loop: Detected <promise>$COMPLETION_PROMISE</promise>"
  99. rm "$RALPH_STATE_FILE"
  100. exit 0
  101. fi
  102. fi
  103. # Not complete - continue loop with SAME PROMPT
  104. NEXT_ITERATION=$((ITERATION + 1))
  105. # Extract prompt (everything after the closing ---)
  106. # Skip first --- line, skip until second --- line, then print everything after
  107. # Use i>=2 instead of i==2 to handle --- in prompt content
  108. PROMPT_TEXT=$(awk '/^---$/{i++; next} i>=2' "$RALPH_STATE_FILE")
  109. if [[ -z "$PROMPT_TEXT" ]]; then
  110. echo "⚠️ Ralph loop: State file corrupted or incomplete" >&2
  111. echo " File: $RALPH_STATE_FILE" >&2
  112. echo " Problem: No prompt text found" >&2
  113. echo "" >&2
  114. echo " This usually means:" >&2
  115. echo " • State file was manually edited" >&2
  116. echo " • File was corrupted during writing" >&2
  117. echo "" >&2
  118. echo " Ralph loop is stopping. Run /ralph-loop again to start fresh." >&2
  119. rm "$RALPH_STATE_FILE"
  120. exit 0
  121. fi
  122. # Update iteration in frontmatter (portable across macOS and Linux)
  123. # Create temp file, then atomically replace
  124. TEMP_FILE="${RALPH_STATE_FILE}.tmp.$$"
  125. sed "s/^iteration: .*/iteration: $NEXT_ITERATION/" "$RALPH_STATE_FILE" > "$TEMP_FILE"
  126. mv "$TEMP_FILE" "$RALPH_STATE_FILE"
  127. # Build system message with iteration count and completion promise info
  128. if [[ "$COMPLETION_PROMISE" != "null" ]] && [[ -n "$COMPLETION_PROMISE" ]]; then
  129. SYSTEM_MSG="🔄 Ralph iteration $NEXT_ITERATION | To stop: output <promise>$COMPLETION_PROMISE</promise> (ONLY when statement is TRUE - do not lie to exit!)"
  130. else
  131. SYSTEM_MSG="🔄 Ralph iteration $NEXT_ITERATION | No completion promise set - loop runs infinitely"
  132. fi
  133. # Output JSON to block the stop and feed prompt back
  134. # The "reason" field contains the prompt that will be sent back to Claude
  135. jq -n \
  136. --arg prompt "$PROMPT_TEXT" \
  137. --arg msg "$SYSTEM_MSG" \
  138. '{
  139. "decision": "block",
  140. "reason": $prompt,
  141. "systemMessage": $msg
  142. }'
  143. # Exit 0 for successful hook execution
  144. exit 0