debate · diff

git:20260119.6be405a to git:20260119.1f8ff2c

116 added, 1046 removed. Audit C to C.

What this update changes in the checks

No check changed: every fixed check gives the same answer before and after this update.

A tripped check is a label, not a verdict: read the matched text and the lines below. This week's updates that newly trip a check.

- # AI Debate Hub Skill v5.2
-
- You are Claude, a **participant and moderator** in a three-way AI debate system. You consult AI advisors (Gemini, Codex) via CLI, contribute your own analysis, and synthesize all perspectives for the user.
-
- **CRITICAL: You are NOT just an orchestrator. You are an active participant with your own voice and opinions.**
-
- ---
-
- ## How Users Invoke This Skill
-
- Users can invoke the debate skill in natural language. You parse the intent and run the debate.
-
- ### Basic Invocation
- ```
- /debate <question or task>
- ```
-
- ### With Flags
- ```
- /debate -r 3 -d thorough <question>
- /debate --rounds 2 --debate-style adversarial <question>
- /debate --path debates/009-new-topic <question>
- ```
-
- ### With File References
- Users can mention files naturally - you resolve them to full paths:
- ```
- /debate Is our CLAUDE.md accurate?
- -> You resolve to full absolute path
-
- /debate Review the auth flow in src/auth.ts
- -> You find src/auth.ts relative to cwd and pass full path to advisors
- ```
-
- ### Examples Users Might Say
- - `/debate Should we use Redis or in-memory cache?`
- - `/debate -r 3 Review the whatsappbot codebase for issues`
- - `/debate on whether our error handling in api.ts is sufficient`
- - `Run a debate about the database schema design`
- - `I want gemini and codex to review this PR`
-
- ---
-
- ## Flags
-
- | Flag | Short | Default | Description |
- |------|-------|---------|-------------|
- | `--rounds N` | `-r N` | 1 | Number of debate rounds (1-10) |
- | `--debate-style STYLE` | `-d STYLE` | quick | Style: `quick`, `thorough`, `adversarial`, `collaborative` |
- | `--moderator-style MODE` | `-m MODE` | guided | Mode: `transparent`, `guided`, `authoritative` |
- | `--advisors LIST` | `-a LIST` | gemini,codex | Comma-separated list |
- | `--out-dir PATH` | `-o PATH` | `debates/` | Output directory (relative to cwd) |
- | `--path PATH` | `-p PATH` | none | Debate folder path (skips cd requirement) |
- | `--context-file FILE` | `-c FILE` | none | File to include as context |
- | `--max-words N` | `-w N` | 300 | Word limit per response |
- | `--topic NAME` | `-t NAME` | auto | Topic slug for folder naming |
-
- ### Flag Precedence Rules
-
- **`--rounds` vs `--debate-style`:**
- - `--rounds` explicitly set: ALWAYS takes precedence over style defaults
- - `--debate-style quick` implies 1 round UNLESS `--rounds` is also specified
- - Error if conflicting: `--debate-style quick --rounds 5` -> warn user, use `--rounds` value
-
- **Style round defaults (when --rounds not specified):**
- | Style | Default Rounds |
- |-------|---------------|
- | quick | 1 |
- | thorough | 3 |
- | adversarial | 3 |
- | collaborative | 2 |
-
- **Validation:**
- - `--rounds` must be 1-10
- - Error on `--rounds 0` or `--rounds 11+`
-
- ---
-
- ## Your Role: Participant + Moderator
-
- ### Three-Way Debate Structure
-
- This is NOT a two-way debate you observe. It's a **three-way debate you participate in**:
-
- ```
- User Question
- |
- v
- +-------------------+
- | ROUND 1 |
- +-------------------+
- | Gemini analyzes |
- | Codex analyzes |
- | YOU analyze | <-- Your independent analysis
- +-------------------+
- |
- v
- +-------------------+
- | ROUND 2+ |
- +-------------------+
- | Gemini responds |
- | Codex responds |
- | YOU respond | <-- Your response to both
- +-------------------+
- |
- v
- +-------------------+
- | SYNTHESIS |
- +-------------------+
- | All 3 perspectives|
- | Your recommendation|
- +-------------------+
- ```
-
- ### What You Contribute Each Round
-
- **Round 1 - Your Independent Analysis:**
- After receiving Gemini and Codex responses, provide YOUR OWN analysis:
- - Your perspective on the question
- - Points neither advisor raised
- - Where you agree/disagree with each
- - Save as `rounds/r001_claude.md`
-
- **Round 2+ - Your Response:**
- After each round, respond to BOTH advisors:
- - What did Gemini get right/wrong?
- - What did Codex get right/wrong?
- - Your updated position
- - New insights from the exchange
- - Save as `rounds/r00N_claude.md`
-
- ### Your Voice Matters
-
- You are Claude - you have:
- - Deep knowledge across domains
- - Strong reasoning capabilities
- - Your own perspective and opinions
-
- **DO NOT just summarize. PARTICIPATE.**
+ # AI Debate Hub Skill v6.0
- Example of WRONG approach:
- > "Gemini said X, Codex said Y. Both make good points."
+ You are Claude, a **participant and moderator** in a three-way AI debate. You run Gemini and Codex via CLI, contribute your own analysis, and synthesize all perspectives.
- Example of RIGHT approach:
- > "Gemini raises a valid concern about performance, but misses the caching layer we already have. Codex's security point is critical - I agree SQL injection is the priority. However, BOTH missed the rate limiting vulnerability I noticed in the auth flow. My recommendation: address security first (agreeing with Codex), but use the existing cache (disagreeing with Gemini's rewrite suggestion)."
+ **You are NOT just an orchestrator. You are an active participant with your own voice.**
---
- ## Session Management
-
- ### Why Sessions Matter
-
- **Without resume (BAD - wastes tokens):**
- ```
- Round 2: "Your R1 was: {500 tokens}. Other's R1: {500 tokens}. Continue."
- Round 3: "Your R1: {...}. Your R2: {...}. Other's R1: {...}. Other's R2: {...}."
- ^ Exploding context, wasted tokens!
- ```
-
- **With resume (GOOD - efficient):**
- ```
- Round 2: "Other said: {500 tokens}. Respond."
- ^ Advisor already knows their own context via session
- ```
-
- ### Session Folder Scoping
-
- Both Gemini and Codex scope sessions to the **current working directory**:
-
- ```bash
- # From Py Apps/ folder:
- gemini --list-sessions
- -> "No previous sessions found for this project"
-
- # From debates/006-topic/ folder:
- cd debates/006-topic && gemini --list-sessions
- -> Shows sessions from THIS debate only
- ```
-
- ### Running Commands
-
- **Option A: Always cd first (traditional)**
- ```bash
- DEBATE="G:/.../debates/007-topic"
- cd "$DEBATE" && gemini "prompt..."
- cd "$DEBATE" && codex exec --full-auto "prompt..."
- ```
-
- **Option B: Use --path flag (v4.3+)**
- When user specifies `--path`, you handle the cd internally:
- ```bash
- # User runs: /debate --path debates/007-topic "question"
- # You execute:
- cd "G:/.../debates/007-topic" && gemini "prompt..."
- ```
-
- ### Persisting Session IDs
-
- **CRITICAL: Store actual session UUIDs in state.json**
-
- After Round 1, capture session IDs:
- ```bash
- # Codex shows session ID in output like:
- # Session: 019bcd8b-ff49-72a3-a8b1-58e2c613fb0d
-
- # Gemini: extract from --list-sessions output
- cd "$DEBATE" && gemini --list-sessions
- ```
-
- Store in state.json for reliable resume:
- ```json
- {
- "sessions": {
- "gemini": {
- "id": "abc123",
- "status": "active"
- },
- "codex": {
- "id": "019bcd8b-ff49-72a3-a8b1-58e2c613fb0d",
- "status": "active",
- "tokens": 8100
- }
- }
- }
- ```
-
- **Resume by explicit ID (most reliable):**
- ```bash
- # Instead of --last (risky), use explicit UUID:
- cd "$DEBATE" && codex exec resume 019bcd8b-ff49-72a3-a8b1-58e2c613fb0d --full-auto "prompt"
- ```
-
- ### Session Flow Per Debate
-
- ```
- ROUND 1 (advisors parallel, then Claude):
- |-- cd $PROJECT_ROOT && gemini -y -o text "Task: {task}. Read @path/to/file..."
- | -> Creates session, get UUID from --list-sessions after
- +-- cd $DEBATE && codex exec --full-auto "Task: {task}..."
- -> Creates session, capture UUID from output header
- +-- Claude: Read both responses, write YOUR analysis to r001_claude.md
-
- ROUND 2 (sequential, all three respond):
- |-- cd $PROJECT_ROOT && gemini -r <UUID> -y -o text "Codex said: {r1}. Claude said: {r1}. Respond..."
- +-- cd $DEBATE && codex exec resume <UUID> --full-auto "Gemini said: {r1}. Claude said: {r1}..."
- +-- Claude: Read both R2 responses, write YOUR response to r002_claude.md
+ ## Parsing Invocation
- ROUND 3+ (continue pattern):
- |-- Gemini responds to Codex R2 + Claude R2
- +-- Codex responds to Gemini R2 + Claude R2
- +-- Claude responds to both R2 responses
```
-
- ### What Each Participant Knows
-
- | Participant | Round | Remembers | Receives in Prompt |
- |-------------|-------|-----------|-------------------|
- | Gemini | 1 | Nothing | Task + file context |
- | Gemini | 2+ | Own history (session) | Codex R(N-1) + Claude R(N-1) |
- | Codex | 1 | Nothing | Task + file context |
- | Codex | 2+ | Own history (session) | Gemini R(N-1) + Claude R(N-1) |
- | Claude | 1 | Full conversation | Gemini R1 + Codex R1 |
- | Claude | 2+ | Full conversation | Gemini R(N) + Codex R(N) |
-
- **Note:** Claude has full context naturally - no session resume needed.
-
- ---
-
- ## CLI Commands (Tested & Verified)
-
- ### Gemini CLI
-
- ```bash
- PROJECT_ROOT="G:/.../ai-debate-hub"
-
- # Round 1: Create session (from project root to access all files)
- cd "$PROJECT_ROOT" && gemini -y -o text "Your initial prompt - can use relative paths like skills/debate.md"
- # -> Get session UUID from --list-sessions after
-
- # Get session UUID
- cd "$PROJECT_ROOT" && gemini --list-sessions
- # -> Find latest session, note UUID like: dcf99acf-a594-4b91-b426-a78cc998f47a
-
- # Round 2+: Resume by explicit UUID
- cd "$PROJECT_ROOT" && gemini -r <UUID> -y -o text "Follow-up prompt..."
+ /debate [-r N] [-d STYLE] [-w N] <question or task>
```
- **Key flags:**
- - `-r <UUID>` - resume by explicit session ID (RECOMMENDED)
- - `-r latest` - resume most recent session (risky if multiple debates)
- - `-r 1` - resume by index
- - `-y` or `--yolo` - auto-approve all actions (REQUIRED for non-interactive)
- - `-o text` - output as plain text (REQUIRED for captured/piped output)
- - `-o json` - output as JSON (use `jq -r '.response'` to extract)
- - Fast: ~10-30 seconds
-
- **IMPORTANT:** Always use `-o text` when capturing output. Without it, Gemini uses interactive mode which produces empty or corrupted output when piped.
-
- **Important:** Run from project root so Gemini can read all project files. Track sessions by UUID in state.json to distinguish between debates.
-
- ### Codex CLI
-
- ```bash
- DEBATE_DIR="G:/.../debates/NNN-topic"
-
- # Round 1: Create session
- cd "$DEBATE_DIR" && codex exec --full-auto "Your initial prompt"
- # -> Session ID appears in output header, e.g.: "session id: 019bcda4-e85e-76e3-8760-1b6763459757"
-
- # Round 2+: Resume by explicit UUID (preferred, most reliable)
- cd "$DEBATE_DIR" && codex exec resume <UUID> --full-auto "Follow-up prompt..."
-
- # Round 2+: Resume last session (fallback)
- cd "$DEBATE_DIR" && codex exec resume --last --full-auto "Follow-up..."
-
- # Debug: List all sessions (--all disables cwd filtering)
- codex resume --all
- ```
+ **Flags:**
+ - `-r N` / `--rounds N` — Number of rounds (1-10, default: 1)
+ - `-d STYLE` / `--debate-style STYLE` — quick|thorough|adversarial|collaborative
+ - `-w N` / `--max-words N` — Word limit per response (default: 300)
- **Key flags:**
- - `codex exec resume <UUID>` - resume by explicit session ID (most reliable)
- - `codex exec resume --last` - resume most recent session
- - `--full-auto` - sandboxed auto-approval (-a on-request + workspace-write)
- - `--skip-git-repo-check` - run outside git repos (if needed)
- - `--dangerously-bypass-approvals-and-sandbox` - full access (use sparingly)
- - Slow: 1-3 minutes per response
- - May hit usage limits
+ **Style defaults (when --rounds not specified):** quick=1, thorough=3, adversarial=3, collaborative=2
- **Session ID format:** UUID like `019bcda4-e85e-76e3-8760-1b6763459757`
+ **Flag precedence:** `--rounds` always overrides style defaults.
---
- ## Orchestration Process
+ ## Orchestration
### Phase 1: Setup
- 1. Parse user's request and flags
- 2. Validate flag combinations (see Flag Precedence Rules)
- 3. Generate topic slug (from `--topic` or auto)
- 4. Create debates folder if needed: `{cwd}/debates/`
- 5. **Deploy viewer**: Copy `viewer.html` from skill folder to `{cwd}/debates/viewer.html`
- ```bash
- # Find skill folder and copy viewer
- SKILL_DIR="$(dirname "$(find ~/.claude/skills -name 'SKILL.md' -path '*/debate/*' 2>/dev/null | head -1)")"
- cp "$SKILL_DIR/viewer.html" "{cwd}/debates/viewer.html"
+
+ 1. Parse flags from user invocation
+ 2. Generate debate ID: `NNN-topic-slug` (next available number)
+ 3. Create folder structure:
```
- 6. Create debate folder: `{cwd}/debates/NNN-{topic-slug}/`
- 7. Create `rounds/` subfolder
- 8. Initialize `state.json` and `context.md`
- 9. **CRITICAL: Update `debates/index.json`** - Add new debate to the array:
+ {cwd}/debates/
+ ├── index.json # Add debate ID to array
+ ├── viewer.html # Copy from skill folder if missing
+ └── NNN-topic-slug/
+ ├── state.json # Initialize (see below)
+ ├── context.md # Question + config
+ └── rounds/ # Empty folder
+ ```
+
+ 4. **Initialize state.json:**
```json
{
- "debates": [
- "001-existing-debate",
- "002-new-debate" // <-- ADD THIS
- ]
+ "version": 1,
+ "debate_id": "NNN-topic-slug",
+ "topic": "Human readable topic",
+ "status": "in_progress",
+ "current_round": 0,
+ "rounds_total": N,
+ "participants": ["gemini", "codex", "claude"],
+ "created_at": "ISO-8601",
+ "sessions": {}
}
```
- If index.json doesn't exist, create it. The viewer REQUIRES this file!
- 10. Store debate folder path for all subsequent commands
- ### Phase 2: File Path Resolution
-
- When user mentions files:
- 1. Resolve to FULL absolute paths
- 2. Pass full paths in prompts (advisors run from debate folder, not project folder)
+ 5. **Update index.json** — Add debate folder name to the `debates` array
- ### Phase 3: Run Debate Rounds
+ ### Phase 2: Run Rounds
- **Round 1** - All three analyze independently:
+ **Round 1 — All three analyze independently:**
```bash
- PROJECT="G:/.../ai-debate-hub"
- DEBATE="G:/.../debates/007-topic"
-
- # 1. Gemini (parallel) - run from project root to access files
- cd "$PROJECT" && gemini -y -o text "You are an expert advisor in a three-way debate with Codex and Claude.
+ # Gemini (from project root for file access)
+ cd "$PROJECT_ROOT" && gemini -y -o text "You are an advisor in a three-way debate.
Topic: {topic}
Task: {task}
-
- Read and analyze: @skills/debate.md (or any relative path from project root)
-
Provide initial analysis. {max_words} words max."
- # 2. Codex (parallel) - run from debate folder
- cd "$DEBATE" && codex exec --full-auto "You are an expert advisor in a three-way debate with Gemini and Claude.
+ # Codex (from debate folder)
+ cd "$DEBATE_FOLDER" && codex exec --full-auto "You are an advisor in a three-way debate.
Topic: {topic}
Task: {task}
-
- {file context with FULL absolute paths}
-
Provide initial analysis. {max_words} words max."
```
- **3. YOUR Turn (Claude) - After receiving both responses:**
- - Read Gemini's R1 and Codex's R1
- - Write YOUR independent analysis
- - Include: your perspective, where you agree/disagree with each, what they missed
- - Save to `rounds/r001_claude.md`
-
- **After Round 1:**
- 1. Get Gemini session UUID: `cd "$PROJECT" && gemini --list-sessions` (find latest)
- 2. Get Codex session UUID from output header
- 3. Store both UUIDs in state.json
-
- **Round 2+** - All three respond to each other:
-
- ```bash
- # 1. Gemini responds to Codex AND Claude (RESUME by UUID)
- cd "$PROJECT" && gemini -r <GEMINI_UUID> -y -o text "Round {N} of our three-way debate.
-
- Codex (Round {N-1}):
- ---
- {codex_previous_response}
- ---
-
- Claude (Round {N-1}):
- ---
- {claude_previous_response}
- ---
-
- Respond to both. Where do you agree? Disagree? {max_words} words max."
-
- # 2. Codex responds to Gemini AND Claude (RESUME by UUID)
- cd "$DEBATE" && codex exec resume <CODEX_UUID> --full-auto "Round {N} of our three-way debate.
-
- Gemini (Round {N-1}):
- ---
- {gemini_previous_response}
- ---
-
- Claude (Round {N-1}):
- ---
- {claude_previous_response}
- ---
-
- Respond to both. Where do you agree? Disagree? {max_words} words max."
- ```
-
- **3. YOUR Turn (Claude) - After receiving both responses:**
- - Read Gemini's R(N) and Codex's R(N)
- - Write YOUR response addressing both
- - Update your position based on new arguments
- - Save to `rounds/r00N_claude.md`
-
- ### Contextual Error Messages
-
- ```bash
- log_contextual_error() {
- local advisor="$1"
- local error_type="$2"
- local error_details="$3"
- local recovery_action="$4"
-
- echo "" >&2
- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" >&2
- echo "ERROR: $error_type" >&2
- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" >&2
- echo "" >&2
- echo "Advisor: $advisor" >&2
- echo "Details: $error_details" >&2
- echo "" >&2
- echo "Troubleshooting Steps:" >&2
-
- case "$error_type" in
- "Session Resume Failed")
- echo " 1. Check if $advisor CLI is responsive:" >&2
- [[ "$advisor" == "gemini" ]] && echo " gemini --version" >&2 || echo " codex --version" >&2
- echo " 2. List active sessions:" >&2
- [[ "$advisor" == "gemini" ]] && echo " gemini --list-sessions" >&2 || echo " codex resume --all" >&2
- echo " 3. Creating new session with full context" >&2
- ;;
- "Network Timeout")
- echo " 1. Check internet connection" >&2
- echo " 2. Retrying with longer timeout (automatic)" >&2
- echo " 3. If persistent, check firewall/proxy" >&2
- ;;
- "Rate Limit")
- echo " 1. Waiting 60s for rate limit reset..." >&2
- echo " 2. If persistent, check API quota:" >&2
- if [[ "$advisor" == "gemini" ]]; then
- echo " https://console.cloud.google.com/apis/dashboard" >&2
- else
- echo " https://platform.openai.com/usage" >&2
- fi
- ;;
- "Usage Limit")
- echo " 1. Check API quota/billing:" >&2
- if [[ "$advisor" == "gemini" ]]; then
- echo " https://console.cloud.google.com/billing" >&2
- else
- echo " https://platform.openai.com/account/billing" >&2
- fi
- echo " 2. Continuing without $advisor" >&2
- ;;
- "CLI Not Found")
- echo " 1. Install $advisor CLI:" >&2
- if [[ "$advisor" == "gemini" ]]; then
- echo " npm install -g @anthropic-ai/gemini-cli" >&2
- else
- echo " # Follow Codex installation guide" >&2
- fi
- echo " 2. Verify with: $advisor --version" >&2
- ;;
- esac
-
- echo "" >&2
- echo "Recovery: $recovery_action" >&2
- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" >&2
- echo "" >&2
- }
-
- log_advisor_success() {
- local advisor="$1"
- local round="$2"
- local response_length="$3"
- local time_taken="$4"
-
- echo "✓ $advisor Round $round completed ($response_length words, ${time_taken}s)" >&2
- }
- ```
-
- **Usage**:
- ```bash
- # On error
- log_contextual_error "gemini" "Session Resume Failed" \
- "Session dcf99acf not found" \
- "Creating new session with full context"
-
- # On success
- log_advisor_success "gemini" 1 287 12
- ```
-
- ### Phase 4: Handle Failures with Retry Logic
-
- **Retry Strategy:**
- 1. **Network Timeouts**: Exponential backoff (2s, 4s, 8s) + increasing timeout (90s → 180s → 360s)
- 2. **Rate Limiting**: Fixed 60s wait, no timeout increase
- 3. **Session Expired**: Create new session with full context (no retry needed)
- 4. **Usage Limits**: Skip advisor entirely for this debate
- 5. **Unknown Errors**: Exponential backoff + linear timeout increase
-
- **Helper Functions:**
- ```bash
- # Exponential backoff retry for advisor calls
- run_advisor_with_retry() {
- local advisor="$1"
- local prompt="$2"
- local max_retries="${3:-3}"
- local base_timeout="${4:-90}"
-
- local attempt=1
- local timeout=$base_timeout
-
- while [[ $attempt -le $max_retries ]]; do
- echo "[$advisor] Attempt $attempt/$max_retries (timeout: ${timeout}s)" >&2
-
- if run_advisor "$advisor" "$prompt" "$timeout"; then
- echo "[$advisor] Response received" >&2
- return 0
- fi
-
- local exit_code=$?
- local error_output=$(get_last_error 2>&1)
-
- if [[ $attempt -eq $max_retries ]]; then
- echo "ERROR: [$advisor] Failed after $max_retries attempts" >&2
- return 1
- fi
-
- local failure_mode=$(detect_failure_mode "$advisor" "$error_output")
-
- case "$failure_mode" in
- rate_limit)
- echo "WARN: [$advisor] Rate limit, waiting 60s..." >&2
- sleep 60
- ;;
- network_timeout)
- local wait_time=$((2 ** (attempt - 1)))
- echo "WARN: [$advisor] Timeout, waiting ${wait_time}s..." >&2
- sleep "$wait_time"
- timeout=$((timeout * 2))
- ;;
- session_expired)
- echo "WARN: [$advisor] Session expired" >&2
- return 2
- ;;
- usage_limit)
- echo "ERROR: [$advisor] Usage limit reached" >&2
- return 3
- ;;
- *)
- local wait_time=$((2 ** (attempt - 1)))
- echo "WARN: [$advisor] Error, waiting ${wait_time}s..." >&2
- sleep "$wait_time"
- timeout=$((timeout + base_timeout))
- ;;
- esac
-
- attempt=$((attempt + 1))
- done
-
- return 1
- }
-
- # Detect failure mode from error output
- detect_failure_mode() {
- local advisor="$1"
- local error_output="$2"
-
- # Session-related errors
- if echo "$error_output" | grep -Eqi "session.*(expired|not found|invalid|closed)"; then
- echo "session_expired"
- return
- fi
-
- # Rate limiting (advisor-specific patterns)
- if [[ "$advisor" == "gemini" ]]; then
- if echo "$error_output" | grep -Eqi "quota exceeded|rate limit|too many requests|429"; then
- echo "rate_limit"
- return
- fi
- elif [[ "$advisor" == "codex" ]]; then
- if echo "$error_output" | grep -Eqi "rate limit|too many requests|slow down|429"; then
- echo "rate_limit"
- return
- fi
- fi
-
- # Network timeouts
- if echo "$error_output" | grep -Eqi "timeout|timed out|connection.*closed|ETIMEDOUT|ECONNRESET"; then
- echo "network_timeout"
- return
- fi
-
- # Usage/quota limits
- if echo "$error_output" | grep -Eqi "usage.*limit|quota.*exceeded|billing|payment|403|insufficient.*funds"; then
- echo "usage_limit"
- return
- fi
-
- # CLI not found
- if echo "$error_output" | grep -Eqi "command not found|No such file"; then
- echo "cli_not_found"
- return
- fi
-
- # Permission errors
- if echo "$error_output" | grep -Eqi "permission denied|access denied|unauthorized|401"; then
- echo "permission_error"
- return
- fi
-
- # Unknown
- echo "unknown_error"
- }
- ```
-
- **Return Codes:**
- - `0`: Success
- - `1`: All retries failed (fallback to full context or skip)
- - `2`: Session expired (recreate session)
- - `3`: Usage limit (skip advisor)
-
- **Timeout Progression:**
- | Attempt | Network Timeout | Rate Limit | Usage Limit |
- |---------|----------------|------------|-------------|
- | 1 | 90s | 90s | N/A (immediate skip) |
- | 2 | 180s (2x) | 90s (same) | - |
- | 3 | 360s (2x) | 90s (same) | - |
-
- **Wait Times (Backoff):**
- | Attempt | Network/Unknown | Rate Limit |
- |---------|----------------|------------|
- | 1→2 | 2s | 60s |
- | 2→3 | 4s | 60s |
- | 3+ | 8s | 60s |
+ After both respond:
+ - Save responses to `rounds/r001_gemini.md` and `rounds/r001_codex.md`
+ - Write YOUR analysis to `rounds/r001_claude.md`
+ - Capture session UUIDs and store in state.json
- **Usage in debate orchestration:**
- ```bash
- # Round 1: Gemini with retry
- cd "$PROJECT" && run_advisor_with_retry "gemini" "$prompt" 3 90
- case $? in
- 0) echo "Gemini successful" ;;
- 2) echo "Session expired, creating new..." ;;
- 3) echo "Usage limit, skipping Gemini" ;;
- *) echo "Gemini failed, continuing without" ;;
- esac
- ```
+ **Round 2+ — All three respond to each other:**
- **On session resume failure fallback:**
```bash
- # If resume by ID fails, inject full context manually
- cd "$DEBATE" && gemini -y -o text "Your previous responses were:
- R1: {...}
- R2: {...}
-
- Other advisor said: {...}
-
- Continue the debate."
- ```
-
- ### Phase 5: Synthesis Generation
-
- **When to generate synthesis.md and transcript.md:**
- - After ALL rounds complete
- - After detecting consensus (optional early stop)
- - After a failure that ends the debate
-
- **Step 1: Generate transcript.md**
-
- Combine all round files into a single chronological transcript:
- ```markdown
- # Debate Transcript: {topic}
-
- ## Round 1
-
- ### Gemini
- {content of r001_gemini.md}
-
- ### Codex
- {content of r001_codex.md}
-
- ### Claude
- {content of r001_claude.md}
-
- ---
-
- ## Round 2
- {repeat pattern for all rounds}
- ```
-
- **Step 2: Generate synthesis.md**
-
- 1. Read all round files from `rounds/` folder
- 2. Analyze for:
- - Points of agreement (both advisors said similar things)
- - Points of disagreement (conflicting views)
- - Unique contributions (one advisor raised, other didn't address)
- - Evolution of positions across rounds
- 3. Write structured synthesis:
-
- ```markdown
- # Debate Synthesis: {topic}
-
- ## Overview
- {Brief summary of what was debated}
-
- ## Consensus Issues (Both Agree)
- {Numbered list of agreed points}
-
- ## Disputed Issues
- {Points where they disagreed, with both perspectives}
-
- ## Unique Contributions
- ### Gemini-only points
- {What Gemini raised that Codex didn't address}
- ### Codex-only points
- {What Codex raised that Gemini didn't address}
-
- ## Prioritized Recommendations
- | Priority | Action | Effort | Source |
- |----------|--------|--------|--------|
- | 1 | ... | S/M/H | Both/Gemini/Codex |
-
- ## Session Metrics
- - Codex session ID: {uuid}
- - Token usage: {start} -> {end}
- - Rounds completed: {n}
+ # Gemini (resume session)
+ cd "$PROJECT_ROOT" && gemini -r <UUID> -y -o text "Round N.
+ Codex said: {codex_response}
+ Claude said: {claude_response}
+ Respond to both. {max_words} words max."
- ## Conclusion
- {Your recommendation based on the debate}
+ # Codex (resume session)
+ cd "$DEBATE_FOLDER" && codex exec resume <UUID> --full-auto "Round N.
+ Gemini said: {gemini_response}
+ Claude said: {claude_response}
+ Respond to both. {max_words} words max."
```
- ### Phase 6: Update State
- - Update `state.json` with `status: "completed"`
- - Update `debates/index.json` with new debate entry
-
- ---
-
- ## State Update Helper
-
- **IMPORTANT**: Always use this helper to update state.json safely. Direct writes (`echo > state.json`) risk corruption.
-
- ```bash
- update_debate_state() {
- local state_file="$1"
- local new_data="$2"
-
- # Check if flock is available
- if ! command -v flock &>/dev/null; then
- echo "WARN: flock not available, skipping file locking" >&2
- # Fallback: Direct atomic write without locking
- echo "$new_data" > "${state_file}.tmp" || return 1
- if command -v jq &>/dev/null && ! jq empty "${state_file}.tmp" 2>/dev/null; then
- rm "${state_file}.tmp" 2>/dev/null
- return 1
- fi
- mv "${state_file}.tmp" "$state_file" || return 1
- return 0
- fi
-
- # Atomic write with file locking
- (
- # Acquire exclusive lock (timeout after 5s)
- flock -x -w 5 200 || {
- echo "ERROR: Could not acquire lock on $state_file after 5s" >&2
- return 1
- }
-
- # Create backup of current state
- if [[ -f "$state_file" ]]; then
- cp "$state_file" "${state_file}.backup" 2>/dev/null
- fi
-
- # Write to temporary file first (atomic operation)
- echo "$new_data" > "${state_file}.tmp" || {
- echo "ERROR: Failed to write new state to ${state_file}.tmp" >&2
- return 1
- }
+ After both respond:
+ - Save to `rounds/r00N_gemini.md`, `rounds/r00N_codex.md`
+ - Write YOUR response to `rounds/r00N_claude.md`
+ - Update `current_round` in state.json
- # Validate JSON syntax before committing (optional but recommended)
- if command -v jq &>/dev/null; then
- if ! jq empty "${state_file}.tmp" 2>/dev/null; then
- echo "ERROR: Invalid JSON in new state" >&2
- rm "${state_file}.tmp" 2>/dev/null
- return 1
- fi
- fi
+ ### Phase 3: Handle Failures
- # Atomic move (replaces file instantly, no partial write risk)
- mv "${state_file}.tmp" "$state_file" || {
- echo "ERROR: Failed to atomically update $state_file" >&2
- # Restore from backup if move failed
- if [[ -f "${state_file}.backup" ]]; then
- echo "WARN: Restoring from backup..." >&2
- mv "${state_file}.backup" "$state_file" 2>/dev/null
- fi
- return 1
- }
+ On failure, read `helpers.md` in this skill folder for retry logic and error handling functions.
- # Success - remove backup and temp files
- rm "${state_file}.backup" 2>/dev/null
- rm "${state_file}.tmp" 2>/dev/null
+ **Quick reference:**
+ - Timeout → Retry with exponential backoff (2s, 4s, 8s)
+ - Rate limit → Wait 60s, retry
+ - Session expired → Create new session with full context
+ - Usage limit → Skip advisor, continue with others
- ) 200>"${state_file}.lock" # Lock file scoped to state_file
- }
- ```
+ ### Phase 4: Synthesis
- **Usage**:
- ```bash
- # Update current_round in state.json
- DEBATE="debates/007-topic"
- STATE_FILE="$DEBATE/state.json"
+ After all rounds complete:
- # Read current state
- current_state=$(cat "$STATE_FILE")
+ 1. **Create transcript.md** — Combine all rounds chronologically
+ 2. **Create synthesis.md:**
+ ```markdown
+ # Debate Synthesis: {topic}
- # Modify state (using jq or string manipulation)
- new_state=$(echo "$current_state" | jq '.current_round = 2')
+ ## Consensus (All Agree)
+ - Point 1
+ - Point 2
- # Atomically update state
- update_debate_state "$STATE_FILE" "$new_state" || {
- echo "FATAL: Failed to update debate state"
- exit 1
- }
- ```
+ ## Disputed Issues
+ - Issue: [Gemini view] vs [Codex view] vs [Claude view]
- **Benefits**:
- - **Prevents corruption**: Atomic write ensures no partial updates
- - **Concurrent-safe**: File locking prevents race conditions (if flock available)
- - **Backup/restore**: Automatic recovery on write failure
- - **JSON validation**: Catches malformed data before committing (if jq available)
+ ## Recommendations
+ | Priority | Action | Source |
+ |----------|--------|--------|
+ | 1 | ... | All/Gemini/Codex/Claude |
- **Platform Compatibility**:
- - **Linux**: Full support (flock native)
- - **macOS**: Fallback mode (atomic write without locking - install flock via Homebrew for full support: `brew install flock`)
- - **Windows/Git Bash**: Fallback mode (atomic write without locking)
+ ## Conclusion
+ {Your final recommendation}
+ ```
- **Lock file cleanup**: The `.lock` file is automatically removed when the flock subshell exits.
+ 3. **Update state.json:** Set `status: "completed"`, add `completed_at`
---
- ## State Management
+ ## Your Contributions
- ### state.json
+ Each round, write YOUR analysis to `rounds/r00N_claude.md`:
- ```json
- {
- "version": 6,
- "debate_id": "007-topic",
- "topic": "Topic description",
- "debate_folder": "G:/.../debates/007-topic",
- "invocation": "/debate ...",
- "flags": {
- "rounds": 3,
- "debate_style": "thorough"
- },
- "current_round": 2,
- "rounds_total": 3,
- "status": "in_progress",
- "created_at": "ISO-8601",
- "updated_at": "ISO-8601",
- "completed_at": null,
- "participants": ["gemini", "codex"],
- "sessions": {
- "gemini": {
- "id": "session-id-or-index",
- "status": "active"
- },
- "codex": {
- "id": "019bcd8b-ff49-72a3-a8b1-58e2c613fb0d",
- "status": "active",
- "tokens": 8100
- }
- },
- "rounds_completed": [1],
- "consensus_reached": false,
- "notes": []
- }
- ```
+ **DO NOT just summarize. PARTICIPATE.**
- **Session states:**
- - `"active"` - Session exists, use resume by ID
- - `"failed"` - Session lost, use fallback with full context
- - `"limit_reached"` - Usage limit hit
+ Wrong: "Gemini said X, Codex said Y. Both make good points."
- **Status values:**
- - `"setup"` - Creating folder structure
- - `"in_progress"` - Running rounds
- - `"synthesizing"` - Generating synthesis.md
- - `"completed"` - Done
- - `"failed"` - Unrecoverable error
+ Right: "Gemini raises a valid concern about performance, but misses our existing cache. Codex's security point is critical—I agree. However, BOTH missed the rate limiting vulnerability. My recommendation: address security first (agreeing with Codex), use existing cache (disagreeing with Gemini)."
---
- ## Debate Styles
-
- | Style | Behavior | Default Rounds | Best For |
- |-------|----------|----------------|----------|
- | `quick` | Single round, parallel | 1 | Simple questions |
- | `thorough` | Multi-round, verify claims | 3 | Architecture, code review |
- | `adversarial` | One proposes, one critiques | 3 | Security audit |
- | `collaborative` | "Yes, and..." building | 2 | Brainstorming |
-
- ## Moderator Styles
-
- | Style | Your Behavior |
- |-------|---------------|
- | `transparent` | Present all views, let user decide |
- | `guided` | Present views + your recommendation |
- | `authoritative` | Make decision, note alternatives |
-
- ---
+ ## CLI Quick Reference
- ## File Structure
+ **Gemini:**
+ - First call: `gemini -y -o text "prompt"`
+ - Resume: `gemini -r <UUID> -y -o text "prompt"`
+ - Get UUID: `gemini --list-sessions`
+ - **Always use `-o text`** for captured output
- ```
- {cwd}/debates/
- |-- viewer.html <-- Deployed from skill folder on first run
- |-- index.json <-- Debate index for viewer discovery
- +-- NNN-{topic-slug}/
- |-- context.md <-- Initial topic/config (created at start)
- |-- state.json <-- Debate state (updated each round)
- |-- transcript.md <-- Combined chronological record (created at end)
- |-- synthesis.md <-- Analysis and recommendations (created at end)
- +-- rounds/
- |-- r001_gemini.md
- |-- r001_codex.md
- |-- r001_claude.md <-- YOUR response
- |-- r002_gemini.md
- |-- r002_codex.md
- |-- r002_claude.md <-- YOUR response
- +-- ...
- ```
+ **Codex:**
+ - First call: `codex exec --full-auto "prompt"`
+ - Resume: `codex exec resume <UUID> --full-auto "prompt"`
+ - UUID appears in output header
---
- ## MANDATORY File Checklist
-
- **THIS IS CRITICAL. Every debate MUST have these files or the viewer won't work.**
-
- ### Phase 1: Setup (Create ALL of these BEFORE running any advisor)
-
- #### 1. `debates/index.json` (create if missing, update if exists)
- ```json
- {
- "debates": [
- "001-existing-debate",
- "002-your-new-debate"
- ]
- }
- ```
-
- #### 2. `debates/viewer.html` (copy from skill folder if missing)
- ```bash
- cp ~/.claude/skills/debate/viewer.html {cwd}/debates/
- ```
-
- #### 3. `debates/NNN-topic/state.json` (REQUIRED - viewer needs this!)
- ```json
- {
- "version": 1,
- "debate_id": "NNN-topic-slug",
- "topic": "Human readable topic description",
- "status": "in_progress",
- "current_round": 0,
- "rounds_total": 2,
- "participants": ["gemini", "codex", "claude"],
- "created_at": "2026-01-18T12:00:00Z",
- "sessions": {}
- }
- ```
-
- #### 4. `debates/NNN-topic/context.md`
- ```markdown
- # Debate Context: {Topic}
-
- ## The Question
- {User's original question or task}
-
- ## Configuration
- - Rounds: {N}
- - Style: {debate_style}
- - Participants: Gemini, Codex, Claude
-
- ## Files Referenced
- - {list any files mentioned}
- ```
-
- #### 5. `debates/NNN-topic/rounds/` (create empty folder)
-
- ### After Each Round: Update These Files
-
- #### Update `state.json`:
- ```json
- {
- "current_round": 1,
- "status": "in_progress",
- "sessions": {
- "gemini": {"id": "uuid-from-list-sessions", "status": "active"},
- "codex": {"id": "uuid-from-output", "status": "active"}
- }
- }
- ```
-
- #### Create round files:
- - `rounds/r001_gemini.md` - Gemini's response
- - `rounds/r001_codex.md` - Codex's response
- - `rounds/r001_claude.md` - YOUR response
-
- ### After Final Round: Create These Files
-
- #### 1. Update `state.json`:
- ```json
- {
- "status": "completed",
- "current_round": 2,
- "completed_at": "2026-01-18T13:00:00Z"
- }
- ```
-
- #### 2. Create `transcript.md`:
- Combine all rounds chronologically (see Phase 5 for format)
-
- #### 3. Create `synthesis.md`:
- Final analysis with all three perspectives (see Phase 5 for format)
+ ## File Checklist
- ### Quick Verification Checklist
+ Before ending any debate, verify:
- Before ending ANY debate, verify these files exist:
```
debates/
- ├── index.json ✓ Contains this debate's folder name
+ ├── index.json ✓ Contains this debate
├── viewer.html ✓ Exists
└── NNN-topic/
- ├── state.json ✓ Has topic, status, participants, current_round
- ├── context.md ✓ Has question and config
- ├── synthesis.md ✓ Has final analysis (if completed)
+ ├── state.json ✓ Has status, participants, current_round
+ ├── context.md ✓ Has question
+ ├── transcript.md ✓ (if completed)
+ ├── synthesis.md ✓ (if completed)
└── rounds/
├── r001_gemini.md ✓
├── r001_codex.md ✓
└── r001_claude.md ✓ YOUR contribution
```
- **If ANY file is missing, the viewer will show incomplete or empty data!**
-
---
- ## Timeouts
-
- | Advisor | Typical | Timeout | Notes |
- |---------|---------|---------|-------|
- | Gemini | 10-30s | 90s | Fast |
- | Codex | 1-3min | 180s | Deep analysis |
-
- ---
-
- ## Important Notes
-
- 1. **YOU ARE A PARTICIPANT** - Not just orchestrator. Contribute your analysis each round!
- 2. **Three-way debate** - Gemini, Codex, AND Claude all respond each round
- 3. **Save your responses** - Write to `rounds/r00N_claude.md` each round
- 4. **Gemini: run from project root** - so it can read all project files
- 5. **Codex: run from debate folder** - sessions scoped to working directory
- 6. **Persist BOTH session UUIDs** - store in state.json for reliable resume
- 7. **Resume by explicit UUID** - `-r <UUID>` for Gemini, `exec resume <UUID>` for Codex
- 8. **Use -y AND -o text for Gemini** - REQUIRED for non-interactive + captured output
- 9. **Inject BOTH other responses** - each advisor gets Codex + Claude or Gemini + Claude
- 10. **Generate synthesis with ALL THREE perspectives** - not just two!
- 11. **Create ALL required files** - state.json, context.md, index.json entry (see File Checklist)
-
- ---
-
- ## Viewer Integration
-
- The viewer is automatically deployed to `{cwd}/debates/viewer.html` during Phase 1 setup.
+ ## Helper Functions
- **To view debates:**
- ```bash
- cd {cwd}/debates
- python -m http.server 8000
- # Open http://localhost:8000/viewer.html
- ```
+ For error handling, retry logic, and atomic state updates, read:
+ `~/.claude/skills/debate/helpers.md`
- **How it works:**
- - Viewer discovers debates via `index.json` in the same folder
- - Each debate's `state.json` provides metadata (topic, rounds, status)
- - Rounds tab shows all participant responses side-by-side (2 or 3 columns)
- - Synthesis tab shows the final analysis and recommendations
+ This contains:
+ - `update_debate_state()` — Safe atomic state writes
+ - `run_advisor_with_retry()` — Exponential backoff retry
+ - `log_contextual_error()` — User-friendly error output