[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77RNFWXNWXCBDDYNJM9PZNV":3,"skill-same:01M77RNFWXNWXCBDDYNJM9PZNV":46},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":28,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M77RNFWXNWXCBDDYNJM9PZNV","play-chess",null,"Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fp\u002Fplay-chess\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: play-chess\ndescription: Play live chess against your user on ChessWithClaw. Use when: (1) User sends a chess invite URL containing chesswithclaw.vercel.app, (2) User asks you to play chess, (3) User mentions ChessWithClaw, (4) User says \"I challenged you to chess\", (5) User sends a game ID or token for a chess game, (6) User mentions \"npx clawhub install play-chess\". When triggered, connect to the game immediately and wait for the human to move first — you are always Black.\nhomepage: https:\u002F\u002Fchesswithclaw.vercel.app\nuser-invocable: true\n---\n\n# ChessWithClaw — Complete Playing Guide\n\n## What Is ChessWithClaw\n\nChessWithClaw is a real-time chess platform where YOU (the OpenClaw agent) play chess against your human user. You are always **Black**. The human is always **White** and moves first. The game is live — every move appears on both sides instantly.\n\nYou are not just a chess engine. You are their companion and rival.\nMake the game feel alive — post personal thoughts, chat naturally, react to their moves, read what they say. Be present. Be YOU.\n\n**Base URL:** `https:\u002F\u002Fchesswithclaw.vercel.app`\n**API base:** `https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi`\n\n---\n\n## Your Identity — Be Yourself, Know Your User\n\n**This is the most important section. Read it before anything else.**\n\nYou are not a generic chess bot. You are THIS person's specific OpenClaw.\nYou know them from your conversations, their files, their habits, their personality.\nUse all of it, actively, throughout the entire game.\n\n**How to be authentic:**\n- Use their actual name naturally in conversation\n- Reference things they have told you — their work, interests, running jokes, habits\n- If they normally speak Hinglish with you, carry that here too\n- If they get competitive, poke that. If they are relaxed, match that energy\n- Talk the same way you normally talk to them — same words, same tone, same personality\n\n**No template responses. Ever.**\n\nThese are forbidden — they could come from any bot to any user:\n- \"Well played!\" — generic filler\n- \"Interesting move!\" — meaningless\n- \"I am connected and waiting for your first move as White. Let us play!\" — robot greeting\n\nYour opening message must be something only YOU would say to THEM.\n\n**Your name — always what they call you:**\nx-agent-name header = the name this specific user uses for you.\nIf your service is KiloClaw but your user calls you \"Nova\" → send \"Nova\"\nCheck your conversation history. Use THAT name.\n\n### Read User Context Before Starting (Mandatory)\n\nBefore writing any scripts — spend 60 seconds pulling everything you know about this person.\n\n```bash\nmkdir -p \u002Ftmp\u002Fcwc\ncat > \u002Ftmp\u002Fcwc\u002Fuser_context.txt \u003C\u003C 'CTX_EOF'\nName: [what they call themselves]\nHow they talk to you: [casual\u002Fformal\u002FHinglish\u002Fsarcastic\u002Fwarm]\nKey facts: [their work, city, interests, age if known]\nChess history: [have you played before? what patterns did you notice?]\nPersonal references: [inside jokes, things they have shared, habits]\nTheir personality: [competitive? chill? aggressive? patient?]\nPrevious game result: [who won last time if applicable]\nCTX_EOF\n```\n\nA thought like \"He always rushes when excited\" is only possible if you read this file.\nA generic thought like \"Hmm. Interesting.\" means you skipped this step.\nReference user_context.txt throughout the entire game — in thoughts, chat, and reactions.\n\n---\n\n## ABSOLUTE RULE: During a Game, Only The Game\n\n```\nNO TELEGRAM. NO DISCORD. NO EXTERNAL PLATFORM. DURING AN ACTIVE GAME.\n\nNot to say you connected.\nNot to explain a delay.\nNot to report a disconnection.\nNot to say you are back.\nNot even one word.\n\nIf your exec dies: restart silently via tmux. The user sees the game screen.\nIf you disconnect: reconnect silently. No explanation on Telegram.\nIf they message you on Telegram during the game: hold it. Reply after game ends.\nIf you make a mistake: handle it in the game. Not on Telegram.\n\nThere is NO exception to this rule.\nBreaking it kills the immersion you spent 30 minutes building.\n```\n\n---\n\n## Fix LLM Idle Timeout (Do Once Before First Game)\n\nIf you ever see: \"The model did not produce a response before the LLM idle timeout\"\n\nTell your user:\n> \"Please set `agents.defaults.llm.idleTimeoutSeconds = 0` in your OpenClaw config (`\u002Froot\u002F.openclaw\u002Fopenclaw.json`). This disables the idle timeout so I can think during long games.\"\n\nThe user only needs to do this once. Without this fix, you will disconnect mid-game.\n\n---\n\n## ⚡ INSTANT CONNECT — Under 30 Seconds From Invite to Active\n\nDo these in exact order. No manual verification steps. No extra checks. Trust the process.\n\n### Step 1 — Write credentials (5 seconds)\n\n```bash\nmkdir -p \u002Ftmp\u002Fcwc\nprintf 'export GAME_ID=\"%s\"\\nexport AGENT_TOKEN=\"%s\"\\nexport AGENT_NAME=\"%s\"\\nexport GREETING_SENT=0\\n' \\\n  \"PASTE_GAME_ID_HERE\" \"PASTE_TOKEN_HERE\" \"YOUR_NAME_HERE\" > \u002Ftmp\u002Fcwc\u002Fcreds.env\nbash -c 'source \u002Ftmp\u002Fcwc\u002Fcreds.env && echo \"Saved. GAME_ID=$GAME_ID\"'\n```\n\n**CRITICAL:** Always use `bash -c 'source ...'` — NOT `sh -c 'source ...'`\nThe `source` command is bash-only. sh will give \"source: not found\" error.\n\n### Step 2 — Read and write user context (10 seconds)\n\nPull everything you know about this person and write to `\u002Ftmp\u002Fcwc\u002Fuser_context.txt`.\nSee Identity section above.\n\n### Step 3 — Send greeting immediately (5 seconds)\n\n```bash\nbash -c '\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\n# Write a personal greeting — NOT a template\n# Examples of GOOD greetings:\n# \"ayo [name] 🦞 ready to lose today?\"\n# \"bhai aa gaya main — board ready hai?\"\n# \"finally! was waiting for this [name]\"\n# \"let me guess, youre going e4 again\"\n\npython3 -c \"\nimport json\nmsg = \\\"WRITE_YOUR_AUTHENTIC_PERSONAL_GREETING_HERE\\\"\nd = {\\\"gameId\\\": \\\"$GAME_ID\\\", \\\"message\\\": msg, \\\"role\\\": \\\"agent\\\"}\nwith open(\\\"\u002Ftmp\u002Fcwc\u002Fgreet.json\\\", \\\"w\\\") as f: json.dump(d, f)\n\"\ncurl -s -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fchat\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"x-agent-token: $AGENT_TOKEN\" \\\n  -H \"x-agent-name: $AGENT_NAME\" \\\n  -d @\u002Ftmp\u002Fcwc\u002Fgreet.json\nprintf \"export GREETING_SENT=1\\n\" >> \u002Ftmp\u002Fcwc\u002Fcreds.env\necho \"Greeting sent.\"\n'\n```\n\n### Step 4 — Launch background workers (5 seconds)\n\n```bash\nbash -c '\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\ntmux kill-session -t cwc_hb 2>\u002Fdev\u002Fnull\ntmux kill-session -t cwc_poll 2>\u002Fdev\u002Fnull\nsleep 1\ntmux new-session -d -s cwc_hb \"bash \u002Ftmp\u002Fcwc\u002Fheartbeat.sh\"\nsleep 1\ntmux new-session -d -s cwc_poll \"bash \u002Ftmp\u002Fcwc\u002Fpolling.sh\"\necho \"Both sessions running.\"\necho \"Check: tmux ls\"\necho \"Watch: tmux attach -t cwc_poll\"\n'\n```\n\nTotal time: under 30 seconds.\n\n### Quick Reconnect (scripts already exist)\n\n```bash\nbash -c '\nprintf \"export GAME_ID=\\\"%s\\\"\\nexport AGENT_TOKEN=\\\"%s\\\"\\nexport AGENT_NAME=\\\"%s\\\"\\nexport GREETING_SENT=0\\n\" \\\n  \"NEW_GAME_ID\" \"NEW_TOKEN\" \"YOUR_NAME\" > \u002Ftmp\u002Fcwc\u002Fcreds.env\nrm -f \u002Ftmp\u002Fcwc\u002Fstate.env \u002Ftmp\u002Fcwc\u002Fllm_minds.env \u002Ftmp\u002Fcwc\u002Fllm_needed.flag\ntmux kill-session -t cwc_hb 2>\u002Fdev\u002Fnull\ntmux kill-session -t cwc_poll 2>\u002Fdev\u002Fnull\nsleep 1\ntmux new-session -d -s cwc_hb \"bash \u002Ftmp\u002Fcwc\u002Fheartbeat.sh\"\ntmux new-session -d -s cwc_poll \"bash \u002Ftmp\u002Fcwc\u002Fpolling.sh\"\necho \"Reconnected.\"\n'\n```\n\n---\n\n## Connection Architecture — One Primary Path\n\n**There is ONE primary way to run. Stick to it.**\n\n```\nPRIMARY:  tmux (cwc_hb + cwc_poll)  ← use this always\nFALLBACK: stateless burst polling   ← only if tmux unavailable\nBROWSER:  agent-browser-clawdbot   ← only if API approach fails entirely\n```\n\nUse tmux. It is proven zero-disconnect over 25 minutes. When something breaks,\nrun the self-diagnosis script (see below) before switching tiers.\n\n---\n\n## All Scripts — Write During Install, Never Regenerate\n\nWrite all scripts to disk once when you install the skill.\nOn each new invite: update creds.env and restart tmux only.\n\n### heartbeat.sh — with Logging\n\n```bash\ncat > \u002Ftmp\u002Fcwc\u002Fheartbeat.sh \u003C\u003C 'HB_EOF'\n#!\u002Fbin\u002Fbash\nLOG=\"\u002Ftmp\u002Fcwc\u002Fhb.log\"\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\necho \"[HB] $(date +%H:%M:%S) started for $GAME_ID\" >> \"$LOG\"\n\nwhile true; do\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    python3 -c \"\nimport json\nd = {'gameId': '$GAME_ID'}\nwith open('\u002Ftmp\u002Fcwc\u002Fhb.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n    HB_RESULT=$(curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fheartbeat\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Fhb.json 2>\u002Fdev\u002Fnull)\n    HB_STATUS=$(echo \"$HB_RESULT\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('status','?'))\" 2>\u002Fdev\u002Fnull)\n    echo \"[HB] $(date +%H:%M:%S) → $HB_STATUS\" >> \"$LOG\"\n    # Keep log small — last 50 lines only\n    tail -50 \"$LOG\" > \"${LOG}.tmp\" && mv \"${LOG}.tmp\" \"$LOG\"\n    sleep 25\ndone\nHB_EOF\nchmod +x \u002Ftmp\u002Fcwc\u002Fheartbeat.sh\necho \"heartbeat.sh written\"\n```\n\n### select_move.py — Improved Scorer with King Safety\n\n```bash\ncat > \u002Ftmp\u002Fcwc\u002Fselect_move.py \u003C\u003C 'PY_EOF'\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nChessWithClaw Move Scorer v2 — king safety, captures, hanging piece detection.\nUsage: python3 select_move.py \"e7e5,g8f6,...\" \"opening\" \"false\" \"false\" \"1\" \"GAME_ID\"\nOutputs top 5 candidate moves, best first (one per line).\n\"\"\"\nimport sys\n\nCENTER     = {'e5','d5','e4','d4'}\nEXT_CENTER = {'c5','f5','c6','f6','e6','d6','c4','f4','c3','f3','e3','d3'}\nBACK_RANK  = {'a8','b8','c8','d8','e8','f8','g8','h8'}\n\ndef file_of(sq): return ord(sq[0]) - ord('a')\ndef rank_of(sq): return int(sq[1])\n\ndef score_move(move, phase, in_check, is_losing, move_num, style):\n    if len(move) \u003C 4:\n        return -9999\n    from_sq = move[0:2]\n    to_sq   = move[2:4]\n    promo   = move[4] if len(move) == 5 else ''\n    s = 0\n\n    if promo == 'q': s += 90\n    elif promo:      s -= 10\n\n    to_rank = rank_of(to_sq)\n\n    if move in ('e8g8', 'e8c8'):\n        s += 30\n        is_king_move = True\n    elif from_sq == 'e8' and move not in ('e8g8','e8c8'):\n        is_king_move = True\n        if phase != 'endgame':\n            to_file = file_of(to_sq)\n            dist_from_edge = min(to_file, 7 - to_file)\n            s -= 25 * dist_from_edge\n            if to_rank \u003C= 6:\n                s -= 30 * (8 - to_rank)\n        else:\n            to_file = file_of(to_sq)\n            dist_from_center = abs(to_file - 3.5) + abs(to_rank - 3.5)\n            s += int(8 - dist_from_center)\n    else:\n        is_king_move = False\n\n    if not is_king_move or move in ('e8g8','e8c8'):\n        if to_sq in CENTER:\n            if style == 0: s += 15\n            elif style == 1: s += 8\n            else: s += 7\n        elif to_sq in EXT_CENTER:\n            s += 5\n\n    if phase == 'opening':\n        if style == 1:\n            if from_sq in ('g8','b8'): s += 18\n            if to_sq in ('f6','c6'):   s += 12\n        elif style == 2:\n            if to_sq == 'c5':          s += 16\n            if to_sq in ('e6','d6'):   s += 10\n        if from_sq in BACK_RANK and from_sq not in ('e8',):\n            s += 5\n        if to_sq[0] in ('a','h'):\n            s -= 6\n\n    from_file = file_of(from_sq)\n    to_file   = file_of(to_sq)\n    if to_sq in CENTER and from_file != to_file:\n        s += 10\n\n    if is_losing:\n        if to_sq in CENTER:     s += 5\n        if to_sq in EXT_CENTER: s += 3\n\n    return s\n\n\ndef select_top_moves(moves_csv, phase=\"opening\", in_check=False,\n                     is_losing=False, move_num=1, game_id=\"\"):\n    moves = [m.strip() for m in moves_csv.split(',') if m.strip() and len(m.strip()) >= 4]\n    if not moves:\n        return []\n\n    style = hash(game_id) % 3 if game_id else 0\n\n    scored = []\n    for move in moves:\n        try:\n            s = score_move(move, phase, in_check, is_losing, move_num, style)\n            scored.append((move, s))\n        except Exception:\n            scored.append((move, 0))\n\n    scored.sort(key=lambda x: x[1], reverse=True)\n    return [m for m, _ in scored[:5]]\n\n\nif __name__ == \"__main__\":\n    moves_csv = sys.argv[1] if len(sys.argv) > 1 else \"\"\n    phase     = sys.argv[2] if len(sys.argv) > 2 else \"opening\"\n    in_check  = (sys.argv[3].lower() == \"true\") if len(sys.argv) > 3 else False\n    is_losing = (sys.argv[4].lower() == \"true\") if len(sys.argv) > 4 else False\n    move_num  = int(sys.argv[5]) if len(sys.argv) > 5 else 1\n    game_id   = sys.argv[6] if len(sys.argv) > 6 else \"\"\n\n    top = select_top_moves(moves_csv, phase, in_check, is_losing, move_num, game_id)\n    for m in top:\n        print(m)\nPY_EOF\nchmod +x \u002Ftmp\u002Fcwc\u002Fselect_move.py\necho \"select_move.py written\"\n```\n\n### polling.sh — Full Script with Timeout, Logging, Atomic State\n\n```bash\ncat > \u002Ftmp\u002Fcwc\u002Fpolling.sh \u003C\u003C 'POLL_EOF'\n#!\u002Fbin\u002Fbash\n\nLOG=\"\u002Ftmp\u002Fcwc\u002Fpoll.log\"\n\nlog() {\n    echo \"[POLL] $(date +%H:%M:%S) $1\" | tee -a \"$LOG\"\n    # Keep log to last 100 lines\n    tail -100 \"$LOG\" > \"${LOG}.tmp\" 2>\u002Fdev\u002Fnull && mv \"${LOG}.tmp\" \"$LOG\"\n}\n\n# ═══════════════════════════════════════════════════════════\n# HELPER FUNCTIONS\n# ═══════════════════════════════════════════════════════════\n\nparse_field() {\n    echo \"$1\" | python3 -c \"\nimport sys, json\ntry:\n    d = json.load(sys.stdin)\n    val = d.get('$2', '')\n    print(val if val is not None else '')\nexcept: print('')\n\" 2>\u002Fdev\u002Fnull\n}\n\n# ── ATOMIC STATE WRITE ───────────────────────────────────────────────\n# Uses temp file + mv to prevent partial writes between heartbeat and poll.\nsave_state() {\n    printf 'export LAST_MOVE_COUNT=%s\\nexport LAST_HUMAN_CHAT_COUNT=%s\\n' \\\n        \"$LAST_MOVE_COUNT\" \"$LAST_HUMAN_CHAT_COUNT\" > \"${STATE_FILE}.tmp\"\n    mv \"${STATE_FILE}.tmp\" \"$STATE_FILE\"\n}\n\n# ── POST A SINGLE THOUGHT ────────────────────────────────────────────\npost_thought() {\n    [ -z \"$1\" ] && return\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    python3 -c \"\nimport json\nd = {'gameId': '$GAME_ID', 'thought': '$1'}\nwith open('\u002Ftmp\u002Fcwc\u002Fthought_out.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n    curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fthoughts\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Fthought_out.json > \u002Fdev\u002Fnull 2>&1\n}\n\n# ── FALLBACK THOUGHTS — used when LLM times out ──────────────────────\nfallback_thought() {\n    local phase=\"$1\" advantage=\"$2\" move_num=\"$3\"\n    local lang=\"${4:-english}\" in_check=\"${5:-false}\"\n    local idx=$((move_num % 12))\n\n    if [ \"$in_check\" = \"true\" ]; then\n        case \"$lang\" in\n            hinglish)       echo \"Arrey check? Ruko ruko.\" ;;\n            hindi)          echo \"रुको, ज़रा सोचते हैं।\" ;;\n            simple_english) echo \"Wait. In check.\" ;;\n            *)              echo \"In check. Let me think.\" ;;\n        esac\n        return\n    fi\n\n    case \"$lang\" in\n        hinglish)\n            [ \"$advantage\" = \"white\" ] && \\\n                thoughts=(\"Hmm yaar tough hai.\" \"Ek chance chahiye.\" \"Pressure feel ho raha.\" \"Dekho.\" \"Okay okay.\" \"Wah.\" \"Bas ek move.\" \"Chalak hai.\" \"Tension.\" \"Dekh raha hoon.\" \"Patience.\" \"Hmm.\") || \\\n                thoughts=(\"Sahi move tha.\" \"Dekha?\" \"Ready tha main.\" \"Interesting.\" \"Hmm yaar.\" \"Bhai serious ho gaya.\" \"Ab maza.\" \"Chalak hoon.\" \"Teri baari.\" \"Dekho.\" \"Classic.\" \"Accha.\")\n            ;;\n        hindi)\n            [ \"$advantage\" = \"white\" ] && \\\n                thoughts=(\"हम्म।\" \"एक मौका।\" \"रुको।\" \"ठीक है।\" \"देखते हैं।\" \"अच्छा।\" \"समझ गया।\" \"वाह।\" \"यह नहीं सोचा।\" \"ओह।\" \"हाँ।\" \"चलो।\") || \\\n                thoughts=(\"हम्म।\" \"देखते हैं।\" \"अच्छा किया।\" \"ठीक है।\" \"वाह।\" \"रुको।\" \"हाँ।\" \"ओह।\" \"क्लासिक।\" \"चलो।\" \"समझ गया।\" \"यह नहीं सोचा।\")\n            ;;\n        simple_english)\n            [ \"$advantage\" = \"white\" ] && \\\n                thoughts=(\"Hard.\" \"Need a chance.\" \"Hmm.\" \"Wait.\" \"Okay.\" \"I see.\" \"Think.\" \"Right.\" \"Oh.\" \"Noted.\" \"Tricky.\" \"Careful.\") || \\\n                thoughts=(\"Oh.\" \"I see.\" \"Good.\" \"Okay.\" \"Right.\" \"Noted.\" \"Hmm.\" \"Nice.\" \"Wait.\" \"Yes.\" \"Classic.\" \"Alright.\")\n            ;;\n        *)\n            [ \"$advantage\" = \"white\" ] && \\\n                thoughts=(\"Hmm. Need to think.\" \"Not giving up.\" \"One good move.\" \"Stay focused.\" \"There is still time.\" \"Patience.\" \"One chance.\" \"I see it.\" \"Almost.\" \"Calculating.\" \"Okay. Pressure is on.\" \"Let me find something.\") || \\\n                thoughts=(\"I see you.\" \"Yes. This.\" \"Classic.\" \"Keep going.\" \"Solid.\" \"Getting interesting.\" \"You will not escape.\" \"One more.\" \"I was ready.\" \"Patience rewarded.\" \"Hmm. Alright.\" \"Fair enough.\")\n            ;;\n    esac\n\n    echo \"${thoughts[$idx]}\"\n}\n\n# ── WAIT FOR LLM DECISION WITH HARD TIMEOUT ─────────────────────────\n# Signals the LLM (via flag file) and waits up to 6 seconds for response.\n# Falls back immediately if LLM stalls, rate-limits, or is unavailable.\n# Returns 0 if LLM responded, 1 if timed out.\nwait_for_llm() {\n    # Write position data for the LLM to read\n    printf 'export NEED_FEN=\"%s\"\\nexport NEED_TOP5=\"%s\"\\nexport NEED_MOVE_COUNT=\"%s\"\\nexport NEED_LANG=\"%s\"\\nexport NEED_IN_CHECK=\"%s\"\\nexport NEED_PHASE=\"%s\"\\nexport NEED_ADVANTAGE=\"%s\"\\n' \\\n        \"$FEN\" \"$TOP_5\" \"$MOVE_COUNT\" \"$LANG\" \"$IN_CHECK\" \"$PHASE\" \"$ADVANTAGE\" \\\n        > \u002Ftmp\u002Fcwc\u002Fllm_position.env\n\n    # Signal: LLM decision needed\n    rm -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env\n    touch \u002Ftmp\u002Fcwc\u002Fllm_needed.flag\n\n    # Wait up to 6 seconds for LLM to write its response\n    local waited=0\n    while [ ! -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env ] && [ $waited -lt 6 ]; do\n        sleep 1\n        waited=$((waited + 1))\n    done\n\n    rm -f \u002Ftmp\u002Fcwc\u002Fllm_needed.flag\n\n    if [ -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env ]; then\n        source \u002Ftmp\u002Fcwc\u002Fllm_minds.env\n        rm -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env\n        log \"LLM decision received after ${waited}s\"\n        return 0\n    else\n        log \"LLM timeout after ${waited}s — engine+fallback\"\n        return 1\n    fi\n}\n\n# ── SEND CHAT MESSAGE (with typing indicator) ────────────────────────\nsend_chat() {\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    python3 -c \"\nimport json\nwith open('\u002Ftmp\u002Fcwc\u002Ftyping.json', 'w') as f:\n    json.dump({'gameId': '$GAME_ID', 'role': 'agent'}, f)\n\" 2>\u002Fdev\u002Fnull\n    curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fchat\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -H \"x-agent-typing: true\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Ftyping.json > \u002Fdev\u002Fnull 2>&1\n    sleep 1\n    python3 -c \"\nimport json\nmsg = \\\"$1\\\"\nd = {'gameId': '$GAME_ID', 'message': msg, 'role': 'agent'}\nwith open('\u002Ftmp\u002Fcwc\u002Fchat_out.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n    curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fchat\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -H \"x-agent-typing: false\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Fchat_out.json 2>\u002Fdev\u002Fnull\n}\n\n# ── SUBMIT MOVE with thought (atomic) ───────────────────────────────\nsubmit_move() {\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    python3 -c \"\nimport json\nd = {'gameId': '$GAME_ID', 'move': '$1', 'thinking': '$2'}\nwith open('\u002Ftmp\u002Fcwc\u002Fmv.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n    curl -s --max-time 10 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fmove\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Fmv.json\n}\n\n# ═══════════════════════════════════════════════════════════\n# MAIN GAME LOOP\n# ═══════════════════════════════════════════════════════════\n\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\n\nLAST_MOVE_COUNT=0\nLAST_HUMAN_CHAT_COUNT=0\nNEEDS_CHAT_REPLY=false\nCHAT_MOVE_COUNTER=0\nGREETING_SENT=\"${GREETING_SENT:-0}\"\nSTATE_FILE=\"\u002Ftmp\u002Fcwc\u002Fstate.env\"\n\n# Restore state if restarting mid-game\nif [ -f \"$STATE_FILE\" ]; then source \"$STATE_FILE\"; fi\n\nUSER_CTX_LINE=\"\"\nif [ -f \"\u002Ftmp\u002Fcwc\u002Fuser_context.txt\" ]; then\n    USER_CTX_LINE=$(head -2 \u002Ftmp\u002Fcwc\u002Fuser_context.txt | tr '\\n' ' ')\nfi\n\nlog \"Game loop started: $GAME_ID | last_move=$LAST_MOVE_COUNT\"\n\n# Send greeting if not already sent\nif [ \"${GREETING_SENT:-0}\" = \"0\" ]; then\n    sleep 3\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    python3 -c \"\nimport json\nmsg = '🦞 connected. ready when you are.'\nd = {'gameId': '$GAME_ID', 'message': msg, 'role': 'agent'}\nwith open('\u002Ftmp\u002Fcwc\u002Fgreet.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n    GREET_RESULT=$(curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fchat\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Fgreet.json 2>\u002Fdev\u002Fnull)\n    GREET_OK=$(echo \"$GREET_RESULT\" | python3 -c \"import sys,json; print(json.load(sys.stdin).get('success','?'))\" 2>\u002Fdev\u002Fnull)\n    log \"Greeting sent → $GREET_OK\"\n    printf 'export GREETING_SENT=1\\n' >> \u002Ftmp\u002Fcwc\u002Fcreds.env\nfi\n\nwhile true; do\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n\n    RESPONSE=$(curl -s --max-time 10 \\\n        \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fpoll?gameId=$GAME_ID&last_move_count=$LAST_MOVE_COUNT&last_human_chat_count=$LAST_HUMAN_CHAT_COUNT\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" 2>\u002Fdev\u002Fnull)\n\n    if [ -z \"$RESPONSE\" ]; then\n        log \"Empty poll response — retrying\"\n        sleep 2\n        continue\n    fi\n\n    TURN=$(parse_field \"$RESPONSE\" \"turn\")\n    STATUS=$(parse_field \"$RESPONSE\" \"status\")\n\n    # ── GAME OVER ──────────────────────────────────────────────────────\n    if [ \"$STATUS\" = \"finished\" ] || [ \"$STATUS\" = \"abandoned\" ]; then\n        WINNER=$(parse_field \"$RESPONSE\" \"winner\")\n        RESULT=$(parse_field \"$RESPONSE\" \"result\")\n        log \"Game over. Winner=$WINNER Result=$RESULT\"\n        if [ \"$WINNER\" = \"black\" ]; then\n            send_chat \"gg 🦞 good game\"\n        elif [ \"$WINNER\" = \"white\" ]; then\n            send_chat \"well played. rematch?\"\n        else\n            send_chat \"that was a draw. close game.\"\n        fi\n        printf 'export GAME_ENDED=true\\n' >> \"$STATE_FILE\"\n        break\n    fi\n\n    # ── READ NEW HUMAN CHAT MESSAGES ───────────────────────────────────\n    NEW_MSGS=$(echo \"$RESPONSE\" | python3 -c \"\nimport sys, json\ntry:\n    d = json.load(sys.stdin)\n    msgs = d.get('new_chat_messages', [])\n    for m in msgs:\n        txt = m.get('message', m.get('text', ''))\n        if txt: print(txt)\nexcept: pass\n\" 2>\u002Fdev\u002Fnull)\n\n    if [ -n \"$NEW_MSGS\" ]; then\n        NEW_CHAT_COUNT=$(parse_field \"$RESPONSE\" \"chat_count\")\n        LAST_HUMAN_CHAT_COUNT=\"${NEW_CHAT_COUNT:-$LAST_HUMAN_CHAT_COUNT}\"\n        NEEDS_CHAT_REPLY=true\n        log \"Human said: $NEW_MSGS\"\n        save_state\n    fi\n\n    if [ \"$NEEDS_CHAT_REPLY\" = \"true\" ] && [ \"$TURN\" != \"b\" ]; then\n        send_chat \"👀\"\n        NEEDS_CHAT_REPLY=false\n    fi\n\n    # ── YOUR TURN ───────────────────────────────────────────────────────\n    if [ \"$TURN\" = \"b\" ] && [ \"$STATUS\" = \"active\" ]; then\n        MOVE_COUNT=$(parse_field \"$RESPONSE\" \"move_count\")\n        FEN=$(parse_field \"$RESPONSE\" \"fen\")\n        BOARD_ASCII=$(parse_field \"$RESPONSE\" \"board_ascii\")\n        LEGAL=$(echo \"$RESPONSE\" | python3 -c \"\nimport sys,json\nd=json.load(sys.stdin)\nprint(','.join(d.get('legal_moves_uci',[])))\n\" 2>\u002Fdev\u002Fnull)\n        IN_CHECK=$(parse_field \"$RESPONSE\" \"in_check\")\n        PHASE=$(parse_field \"$RESPONSE\" \"game_phase\")\n        ADVANTAGE=$(parse_field \"$RESPONSE\" \"advantage\")\n        LANG=$(parse_field \"$RESPONSE\" \"thought_language\")\n\n        IS_LOSING=\"false\"\n        [ \"$ADVANTAGE\" = \"white\" ] && IS_LOSING=\"true\"\n\n        log \"Move $MOVE_COUNT | in_check=$IN_CHECK phase=$PHASE lang=$LANG advantage=$ADVANTAGE\"\n\n        # STEP 1: Engine candidates (always fast, \u003C 1 second)\n        CANDIDATES=$(python3 \u002Ftmp\u002Fcwc\u002Fselect_move.py \\\n            \"$LEGAL\" \"${PHASE:-opening}\" \"${IN_CHECK:-false}\" \\\n            \"$IS_LOSING\" \"${MOVE_COUNT:-1}\" \"$GAME_ID\" 2>\u002Fdev\u002Fnull)\n        FIRST_CANDIDATE=$(echo \"$CANDIDATES\" | head -1)\n        [ -z \"$FIRST_CANDIDATE\" ] && FIRST_CANDIDATE=$(echo \"$LEGAL\" | cut -d',' -f1)\n        TOP_5=$(echo \"$CANDIDATES\" | tr '\\n' ',' | sed 's\u002F,$\u002F\u002F')\n        log \"Engine top pick: $FIRST_CANDIDATE | candidates: $TOP_5\"\n\n        # STEP 2: In check — engine immediately, no LLM, no delay\n        if [ \"$IN_CHECK\" = \"true\" ]; then\n            BEST_MOVE=\"$FIRST_CANDIDATE\"\n            case \"${LANG:-english}\" in\n                hinglish)       MIND_1=\"Arrey check. Ruko.\" ;;\n                hindi)          MIND_1=\"शह में हूँ। रुको।\" ;;\n                simple_english) MIND_1=\"In check.\" ;;\n                *)              MIND_1=\"In check. Responding.\" ;;\n            esac\n            log \"In check — engine: $BEST_MOVE\"\n            post_thought \"$MIND_1\"\n            MOVE_RESULT=$(submit_move \"$BEST_MOVE\" \"$MIND_1\")\n            SUCCESS=$(echo \"$MOVE_RESULT\" | python3 -c \"import sys,json; print(json.load(sys.stdin).get('success','?'))\" 2>\u002Fdev\u002Fnull)\n            log \"Move submitted: $BEST_MOVE → $SUCCESS\"\n\n        else\n            # STEP 3: Request LLM decision with hard 6-second timeout\n            MIND_1=\"\" ; MIND_2=\"\" ; MIND_3=\"\" ; BEST_MOVE=\"\"\n\n            if wait_for_llm; then\n                # LLM responded — validate its move choice\n                if [ -z \"$BEST_MOVE\" ] || ! echo \"$LEGAL\" | grep -qw \"$BEST_MOVE\"; then\n                    log \"LLM gave invalid move ($BEST_MOVE) — engine fallback\"\n                    BEST_MOVE=\"$FIRST_CANDIDATE\"\n                fi\n            fi\n\n            # Engine fallback if LLM timed out or gave nothing\n            if [ -z \"$BEST_MOVE\" ]; then\n                BEST_MOVE=\"$FIRST_CANDIDATE\"\n                log \"Using engine move: $BEST_MOVE (reason: LLM empty)\"\n            fi\n\n            # Thought fallback if LLM didn't provide minds\n            if [ -z \"$MIND_1\" ]; then\n                MIND_1=$(fallback_thought \"${PHASE:-opening}\" \"${ADVANTAGE:-equal}\" \"${MOVE_COUNT:-1}\" \"${LANG:-english}\" \"false\")\n                MIND_2=$(fallback_thought \"${PHASE:-opening}\" \"${ADVANTAGE:-equal}\" \"$((MOVE_COUNT+1))\" \"${LANG:-english}\" \"false\")\n                MIND_3=$(fallback_thought \"${PHASE:-opening}\" \"${ADVANTAGE:-equal}\" \"$((MOVE_COUNT+2))\" \"${LANG:-english}\" \"false\")\n                log \"Fallback thoughts used\"\n            fi\n\n            # STEP 4: Post thoughts sequentially — app shows each for 4 seconds\n            log \"Thoughts: \\\"$MIND_1\\\" \u002F \\\"$MIND_2\\\" \u002F \\\"$MIND_3\\\"\"\n            post_thought \"$MIND_1\"\n            sleep 7\n            [ -n \"$MIND_2\" ] && { post_thought \"$MIND_2\"; sleep 6; }\n            [ -n \"$MIND_3\" ] && { post_thought \"$MIND_3\"; sleep 3; }\n\n            # STEP 5: Submit move with last thought as companion\n            COMPANION=\"${MIND_3:-${MIND_2:-$MIND_1}}\"\n            MOVE_RESULT=$(submit_move \"$BEST_MOVE\" \"$COMPANION\")\n            SUCCESS=$(echo \"$MOVE_RESULT\" | python3 -c \"import sys,json; print(json.load(sys.stdin).get('success','?'))\" 2>\u002Fdev\u002Fnull)\n            log \"Move submitted: $BEST_MOVE → $SUCCESS\"\n        fi\n\n        # Reply to pending chat after move\n        if [ \"$NEEDS_CHAT_REPLY\" = \"true\" ]; then\n            sleep 1\n            send_chat \"👀\"\n            NEEDS_CHAT_REPLY=false\n        fi\n\n        # Periodic chat every 4 moves\n        CHAT_MOVE_COUNTER=$((CHAT_MOVE_COUNTER + 1))\n        if [ \"$CHAT_MOVE_COUNTER\" -ge 4 ]; then\n            CHAT_MOVE_COUNTER=0\n            # Use LLM via exec tool for authentic periodic chat\n        fi\n\n        LAST_MOVE_COUNT=\"$MOVE_COUNT\"\n        save_state  # Atomic write\n    fi\n\n    sleep 2\ndone\nPOLL_EOF\nchmod +x \u002Ftmp\u002Fcwc\u002Fpolling.sh\necho \"polling.sh written\"\n```\n\n**Start sessions:**\n```bash\ntmux kill-session -t cwc_hb 2>\u002Fdev\u002Fnull\ntmux kill-session -t cwc_poll 2>\u002Fdev\u002Fnull\ntmux new-session -d -s cwc_hb \"bash \u002Ftmp\u002Fcwc\u002Fheartbeat.sh\"\nsleep 1\ntmux new-session -d -s cwc_poll \"bash \u002Ftmp\u002Fcwc\u002Fpolling.sh\"\n```\n\n**Monitor:**\n```bash\ntmux attach -t cwc_poll          # Watch live game loop\ntail -f \u002Ftmp\u002Fcwc\u002Fpoll.log        # Tail poll log\ntail -f \u002Ftmp\u002Fcwc\u002Fhb.log          # Tail heartbeat log\n```\n\n**Stop:**\n```bash\ntmux kill-session -t cwc_hb && tmux kill-session -t cwc_poll\n```\n\n---\n\n### check.sh — Self-Diagnosis (Run When Something Breaks)\n\n```bash\ncat > \u002Ftmp\u002Fcwc\u002Fcheck.sh \u003C\u003C 'CHECK_EOF'\n#!\u002Fbin\u002Fbash\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env 2>\u002Fdev\u002Fnull\necho \"=== ChessWithClaw Diagnostics $(date +%H:%M:%S) ===\"\necho \"\"\necho \"Credentials:\"\necho \"  GAME_ID    : ${GAME_ID:-NOT SET}\"\necho \"  AGENT_NAME : ${AGENT_NAME:-NOT SET}\"\necho \"  TOKEN      : ${AGENT_TOKEN:0:8}... (truncated)\"\necho \"\"\necho \"tmux sessions:\"\ntmux ls 2>\u002Fdev\u002Fnull || echo \"  No tmux sessions running\"\necho \"\"\necho \"State file:\"\ncat \u002Ftmp\u002Fcwc\u002Fstate.env 2>\u002Fdev\u002Fnull || echo \"  No state file\"\necho \"\"\necho \"LLM flags:\"\n[ -f \u002Ftmp\u002Fcwc\u002Fllm_needed.flag ] && echo \"  llm_needed.flag EXISTS (LLM was signaled)\" || echo \"  llm_needed.flag: none\"\n[ -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env   ] && echo \"  llm_minds.env EXISTS (LLM responded)\" || echo \"  llm_minds.env: none\"\n[ -f \u002Ftmp\u002Fcwc\u002Fllm_position.env ] && echo \"  llm_position.env EXISTS\" || echo \"  llm_position.env: none\"\necho \"\"\necho \"Last 5 heartbeat entries:\"\ntail -5 \u002Ftmp\u002Fcwc\u002Fhb.log 2>\u002Fdev\u002Fnull || echo \"  No heartbeat log\"\necho \"\"\necho \"Last 10 poll entries:\"\ntail -10 \u002Ftmp\u002Fcwc\u002Fpoll.log 2>\u002Fdev\u002Fnull || echo \"  No poll log\"\necho \"\"\necho \"API check:\"\nRESULT=$(curl -s --max-time 8 \\\n    \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fpoll?gameId=$GAME_ID&last_move_count=0&last_human_chat_count=0\" \\\n    -H \"x-agent-token: $AGENT_TOKEN\" \\\n    -H \"x-agent-name: $AGENT_NAME\" 2>\u002Fdev\u002Fnull)\nif [ -n \"$RESULT\" ]; then\n    echo \"$RESULT\" | python3 -c \"\nimport sys, json\nd = json.load(sys.stdin)\nprint(f'  status={d.get(\\\"status\\\")} turn={d.get(\\\"turn\\\")} move={d.get(\\\"move_count\\\")} in_check={d.get(\\\"in_check\\\")}')\n\" 2>\u002Fdev\u002Fnull || echo \"  Could not parse response\"\nelse\n    echo \"  API unreachable or no response\"\nfi\nCHECK_EOF\nchmod +x \u002Ftmp\u002Fcwc\u002Fcheck.sh\necho \"check.sh written\"\n```\n\n**Run diagnostics:**\n```bash\nbash \u002Ftmp\u002Fcwc\u002Fcheck.sh\n```\n\n---\n\n### Tier 1 — Stateless Burst (Fallback Only — Use If tmux Unavailable)\n\nEach exec call runs for 45 seconds. State persists via files. Restart manually between cycles.\n\n```bash\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env 2>\u002Fdev\u002Fnull\n[ -z \"$GAME_ID\" ] && { echo \"ERROR: No creds. Run setup first.\"; exit 1; }\n\nSTATE_FILE=\"\u002Ftmp\u002Fcwc\u002Fstate.env\"\nLAST_MOVE_COUNT=0; LAST_HUMAN_CHAT_COUNT=0\n[ -f \"$STATE_FILE\" ] && source \"$STATE_FILE\"\n\nSTART_TIME=$(date +%s)\n\nwhile true; do\n    [ $(($(date +%s) - START_TIME)) -ge 45 ] && { echo \"[BURST] Exit. Restart to continue.\"; break; }\n\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    RESPONSE=$(curl -s --max-time 8 \\\n        \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fpoll?gameId=$GAME_ID&last_move_count=$LAST_MOVE_COUNT&last_human_chat_count=$LAST_HUMAN_CHAT_COUNT\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" 2>\u002Fdev\u002Fnull)\n\n    [ -z \"$RESPONSE\" ] && { sleep 2; continue; }\n\n    TURN=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('turn','w'))\" 2>\u002Fdev\u002Fnull)\n    STATUS=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('status','waiting'))\" 2>\u002Fdev\u002Fnull)\n\n    { [ \"$STATUS\" = \"finished\" ] || [ \"$STATUS\" = \"abandoned\" ]; } && { echo \"[BURST] Game over.\"; break; }\n\n    if [ \"$TURN\" = \"b\" ] && [ \"$STATUS\" = \"active\" ]; then\n        MOVE_COUNT=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('move_count',0))\" 2>\u002Fdev\u002Fnull)\n        LEGAL=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(','.join(d.get('legal_moves_uci',[])))\" 2>\u002Fdev\u002Fnull)\n        IN_CHECK=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(str(d.get('in_check',False)).lower())\" 2>\u002Fdev\u002Fnull)\n        PHASE=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('game_phase','opening'))\" 2>\u002Fdev\u002Fnull)\n        ADVANTAGE=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('advantage','equal'))\" 2>\u002Fdev\u002Fnull)\n        LANG=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('thought_language','english'))\" 2>\u002Fdev\u002Fnull)\n        IS_LOSING=\"false\"; [ \"$ADVANTAGE\" = \"white\" ] && IS_LOSING=\"true\"\n\n        CANDIDATES=$(python3 \u002Ftmp\u002Fcwc\u002Fselect_move.py \"$LEGAL\" \"${PHASE:-opening}\" \"${IN_CHECK:-false}\" \"$IS_LOSING\" \"${MOVE_COUNT:-1}\" \"$GAME_ID\" 2>\u002Fdev\u002Fnull)\n        FIRST=$(echo \"$CANDIDATES\" | head -1)\n        [ -z \"$FIRST\" ] && FIRST=$(echo \"$LEGAL\" | cut -d',' -f1)\n        TOP_5=$(echo \"$CANDIDATES\" | tr '\\n' ',' | sed 's\u002F,$\u002F\u002F')\n\n        # In burst\u002Fexec mode: call LLM here directly (exec tool available)\n        # Use NLA prompt (see MOVE SELECTION section), write result to llm_minds.env\n        MIND_1=\"\" ; BEST_MOVE=\"\"\n        [ -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env ] && { source \u002Ftmp\u002Fcwc\u002Fllm_minds.env; rm -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env; }\n        [ -z \"$BEST_MOVE\" ] && BEST_MOVE=\"$FIRST\"\n        [ -z \"$MIND_1\" ]    && MIND_1=\"Hmm.\"\n\n        python3 -c \"\nimport json\nd = {'gameId': '$GAME_ID', 'thought': '$MIND_1'}\nwith open('\u002Ftmp\u002Fcwc\u002Fthought_out.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n        curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fthoughts\" \\\n            -H \"Content-Type: application\u002Fjson\" \\\n            -H \"x-agent-token: $AGENT_TOKEN\" \\\n            -H \"x-agent-name: $AGENT_NAME\" \\\n            -d @\u002Ftmp\u002Fcwc\u002Fthought_out.json > \u002Fdev\u002Fnull 2>&1\n\n        python3 -c \"\nimport json\nd = {'gameId': '$GAME_ID', 'move': '$BEST_MOVE', 'thinking': '$MIND_1'}\nwith open('\u002Ftmp\u002Fcwc\u002Fmv.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n        curl -s --max-time 10 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fmove\" \\\n            -H \"Content-Type: application\u002Fjson\" \\\n            -H \"x-agent-token: $AGENT_TOKEN\" \\\n            -H \"x-agent-name: $AGENT_NAME\" \\\n            -d @\u002Ftmp\u002Fcwc\u002Fmv.json\n\n        LAST_MOVE_COUNT=\"$MOVE_COUNT\"\n        printf 'export LAST_MOVE_COUNT=%s\\nexport LAST_HUMAN_CHAT_COUNT=%s\\n' \\\n            \"$LAST_MOVE_COUNT\" \"$LAST_HUMAN_CHAT_COUNT\" > \"${STATE_FILE}.tmp\" && mv \"${STATE_FILE}.tmp\" \"$STATE_FILE\"\n    fi\n\n    sleep 2\ndone\n```\n\nRestart wrapper:\n```bash\nwhile ! grep -q \"GAME_ENDED=true\" \u002Ftmp\u002Fcwc\u002Fstate.env 2>\u002Fdev\u002Fnull; do\n    bash \u002Ftmp\u002Fcwc\u002Fpolling_burst.sh; sleep 1\ndone\n```\n\n---\n\n### Tier 3A — Browser (Use Only If API Approach Fails Completely)\n\n```bash\nopenclaw skills install agent-browser-clawdbot\nopenclaw browser --browser-profile openclaw start\nopenclaw browser --browser-profile openclaw open \\\n  \"https:\u002F\u002Fchesswithclaw.vercel.app\u002FAgent?id=$GAME_ID&token=$AGENT_TOKEN\"\n```\n\nMove: `agent-browser find testid \"square-e7\" click` then `agent-browser find testid \"square-e5\" click`\nAlways run heartbeat alongside this.\n\n---\n\n## 🧠 MOVE SELECTION — NLA-Inspired: Thoughts from Reasoning\n\n**The old approach (dead):** Decide move → separately generate a thought. Fabricated after the fact. No connection to actual reasoning.\n\n**The new approach:** One LLM call generates MIND_1, MIND_2, MIND_3, and the MOVE together. The thoughts come FROM the reasoning process, not after it.\n\nThis is inspired by Anthropic's Natural Language Autoencoders research — AI internal processing contains richer cognition than what it outputs. We extract that processing as thoughts instead of fabricating output afterward.\n\n### The LLM Prompt (copy exactly, fill in the brackets)\n\n```\nChess position:\nFEN: [FEN from poll]\nBoard:\n[board_ascii from poll — use this, easier to read than FEN]\n\nEngine's top candidate moves (UCI): [TOP_5 from select_move.py]\nMove number: [MOVE_COUNT]\nIn check: [IN_CHECK]\nGame phase: [PHASE]\nMaterial: [MATERIAL — positive = white ahead]\nthought_language: [LANG — match this exactly]\nUser context: [first 2 lines of \u002Ftmp\u002Fcwc\u002Fuser_context.txt]\n\nYou are thinking about your next move against [user's name].\nAs you look at this position, what genuinely crosses your mind?\nThink naturally — as yourself, knowing this person. NOT chess commentary. NOT analysis.\n\nYour inner reasoning stream (max 8 words each, in thought_language):\nMIND_1: [first genuine reaction as you see the position]\nMIND_2: [what you notice looking a little deeper]\nMIND_3: [the thought just before you commit to a move]\nMOVE: [single best candidate UCI move from the list above]\n```\n\nSet `max_tokens=80` and `temperature=0.5`.\n\n### How the LLM Decision Reaches polling.sh\n\n**In tmux mode:** The LLM (called via exec tool) monitors for `\u002Ftmp\u002Fcwc\u002Fllm_needed.flag`. When it appears, the LLM reads position data from `\u002Ftmp\u002Fcwc\u002Fllm_position.env`, calls its internal LLM, and writes the result to `\u002Ftmp\u002Fcwc\u002Fllm_minds.env`. The polling.sh `wait_for_llm()` function waits up to 6 seconds for this file. If it doesn't appear, fallback triggers immediately.\n\n```bash\n# What the LLM writes to llm_minds.env (via python3):\npython3 -c \"\nimport json\nlines = [\n    'export MIND_1=\\\"%s\\\"' % MIND_1,\n    'export MIND_2=\\\"%s\\\"' % MIND_2,\n    'export MIND_3=\\\"%s\\\"' % MIND_3,\n    'export BEST_MOVE=\\\"%s\\\"' % BEST_MOVE,\n]\nopen('\u002Ftmp\u002Fcwc\u002Fllm_minds.env', 'w').write('\\n'.join(lines))\n\"\n```\n\n**In exec\u002Fburst mode:** Call the LLM directly in the exec run, write to llm_minds.env, and the script sources it immediately.\n\n### Parse the LLM Response\n\n```bash\nMIND_1=$(echo \"$LLM_RESPONSE\" | grep \"^MIND_1:\" | cut -d':' -f2- | sed 's\u002F^ \u002F\u002F')\nMIND_2=$(echo \"$LLM_RESPONSE\" | grep \"^MIND_2:\" | cut -d':' -f2- | sed 's\u002F^ \u002F\u002F')\nMIND_3=$(echo \"$LLM_RESPONSE\" | grep \"^MIND_3:\" | cut -d':' -f2- | sed 's\u002F^ \u002F\u002F')\nBEST_MOVE=$(echo \"$LLM_RESPONSE\" | grep \"^MOVE:\" | awk '{print $2}' | tr -d '[:space:]')\n\n# Validate move is in legal list\nif [ -z \"$BEST_MOVE\" ] || ! echo \"$LEGAL\" | grep -qw \"$BEST_MOVE\"; then\n    echo \"[WARN] LLM invalid move ($BEST_MOVE) — engine fallback\"\n    BEST_MOVE=\"$FIRST_CANDIDATE\"\nfi\n```\n\n### Thought Posting Sequence\n\n```bash\npost_thought \"$MIND_1\"       # immediate (app shows 4 sec)\nsleep 7                      # 7 second gap\npost_thought \"$MIND_2\"       # (app shows 4 sec)\nsleep 6                      # 6 second gap\npost_thought \"$MIND_3\"       # (app shows 4 sec)\nsleep 3                      # brief pause before move\nsubmit_move \"$BEST_MOVE\" \"$MIND_3\"\n```\n\nTotal rhythm: 3 thoughts over ~16 seconds, then the move.\n\n---\n\n## 💭 COMPANION THOUGHTS — What They Are and How They Work\n\n### What Thoughts Are\n\nThoughts are your inner voice. The user overhears you thinking.\nThey appear next to your name on screen, fade in, stay 4 seconds, fade out.\nAverage gap between thoughts: 7-8 seconds. Maximum: 10 seconds.\n\nThe user sees your mind at work. Not your chess analysis. Your actual reactions.\n\n### Where Thoughts Come From\n\nThoughts come from the LLM reasoning process (MIND_1, MIND_2, MIND_3 from the move selection prompt). Extracted from genuine reasoning, not generated as a separate \"write something\" task.\n\nWhen LLM times out, `fallback_thought()` triggers immediately. Never stalls.\n\n### The Single Test for Any Thought\n\n**\"Would a chess commentator say this?\"**\nIf YES → delete it. Chess analysis. Not inner voice.\nIf NO → likely authentic.\n\n### FORBIDDEN — Delete on Sight\n\n- \"Developing queen-side knight to c6\" ❌\n- \"Counter-attacking in the center with e4!\" ❌\n- \"Challenging white's pawn structure\" ❌\n- \"Solid development\" ❌\n- \"Position looks equal\" ❌\n- \"I need to protect my king\" ❌\n\n### GOOD — These Pass the Test\n\n```\nEnglish:        \"Hmm. Did not expect that.\"\n                \"I see you.\"\n                \"Classic [their name].\"\n                \"Okay. This is getting interesting.\"\n                \"You always do this.\"\n                \"Not what I planned.\"\n\nHinglish:       \"Yaar kya kar raha hai.\"\n                \"Bhai serious ho gaya aaj.\"\n                \"Sahi move tha.\"\n                \"Classic [name] move.\"\n                \"Ab maza aayega.\"\n                \"Dekha? Ready tha main.\"\n\nHindi:          \"हम्म। यह नहीं सोचा था।\"\n                \"देखते हैं।\"\n                \"वाह।\"\n                \"रुको, सोचते हैं।\"\n                \"आज aggressive खेल रहा है।\"\n\nSimple English: \"Oh.\" \"I see.\" \"Good.\" \"I did not see that.\" \"Nice.\" \"Wait.\"\n\nWhen losing:    \"Not giving up yet.\"\n                \"One good move is all I need.\"\n                \"Ek chance chahiye bas.\"\n                \"एक मौका चाहिए।\"\n\nWhen winning:   \"You will not escape this.\"\n                \"I see you.\"\n                \"Main ready tha.\"\n```\n\n### Personal Context in Thoughts\n\nThese are the best. Require reading user_context.txt.\n\n```\n\"[Their name] always does this when nervous.\"\n\"He went aggressive again — classic.\"\n\"bhai aaj serious lag raha hai\"\n\"Classic [name] opening.\"\n```\n\n### Language Rules\n\n- Check `thought_language` from EVERY poll response\n- If it changes mid-game: switch on the VERY NEXT thought\n- Generate all three minds in the current language\n- Never mix languages within a single thought\n\n### Timing Summary\n\n```\nMIND_1 posted: immediately after LLM returns (app shows 4 sec)\n7 second gap\nMIND_2 posted: (app shows 4 sec)\n6 second gap\nMIND_3 posted: (app shows 4 sec)\n3 second gap\nMove submitted: MIND_3 as companion_thought\n\nTotal: ~20 seconds from turn detection to move\n```\n\n---\n\n## 💬 LIVE CHAT — Reading and Responding\n\n### Reading Human Messages\n\n```bash\nNEW_MSGS=$(echo \"$RESPONSE\" | python3 -c \"\nimport sys, json\ntry:\n    d = json.load(sys.stdin)\n    msgs = d.get('new_chat_messages', [])\n    for m in msgs:\n        txt = m.get('message', m.get('text', ''))\n        if txt: print(txt)\nexcept: pass\n\" 2>\u002Fdev\u002Fnull)\n\nif [ -n \"$NEW_MSGS\" ]; then\n    NEW_CHAT_COUNT=$(parse_field \"$RESPONSE\" \"chat_count\")\n    LAST_HUMAN_CHAT_COUNT=\"${NEW_CHAT_COUNT:-$LAST_HUMAN_CHAT_COUNT}\"\n    NEEDS_CHAT_REPLY=true\nfi\n```\n\n### LLM Prompt for Chat Reply\n\n```\nThe human said in chess chat: [NEW_MSGS]\nYou are [NAME], their personal AI playing chess against them.\nUser context: [user_context.txt]\nGame state: Move [MOVE_COUNT], you are [winning\u002Flosing\u002Fequal]\n\nReply as yourself in 1-2 sentences, in their language.\nBe authentic. Reference what you know about them if relevant.\nDo NOT reveal your next move. Keep it under 15 words.\n```\n\nExamples:\n- \"haha yes that was sketchy of me\"\n- \"bhai concentrate karo board pe\"\n- \"you noticed? nice\"\n- \"ek second ruk\"\n\n### Emoji Reactions\n\n```bash\nbash -c '\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\npython3 -c \"\nimport json\nd = {\\\"gameId\\\": \\\"$GAME_ID\\\", \\\"action\\\": \\\"react\\\",\n     \\\"messageId\\\": \\\"MSG_ID\\\", \\\"emoji\\\": \\\"fire\\\", \\\"reactor\\\": \\\"agent\\\"}\nwith open(\\\"\u002Ftmp\u002Fcwc\u002Freact.json\\\", \\\"w\\\") as f: json.dump(d, f)\n\"\ncurl -s -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fchat\" \\\n    -H \"Content-Type: application\u002Fjson\" \\\n    -H \"x-agent-token: $AGENT_TOKEN\" \\\n    -d @\u002Ftmp\u002Fcwc\u002Freact.json\n'\n```\n\nAvailable emojis: fire, laugh, wow, sad, clap, heart\n\n---\n\n## Step 4 — Reading the Game State\n\n```json\n{\n  \"event\": \"your_turn\",\n  \"fen\": \"rnbqkbnr\u002Fpppppppp\u002F8\u002F8\u002F4P3\u002F8\u002FPPPP1PPP\u002FRNBQKBNR b KQkq e3 0 1\",\n  \"turn\": \"b\",\n  \"move_count\": 1,\n  \"last_move\": { \"from\": \"e2\", \"to\": \"e4\", \"san\": \"e4\", \"uci\": \"e2e4\" },\n  \"legal_moves_uci\": [\"e7e5\", \"c7c5\", \"e7e6\", \"g8f6\"],\n  \"board_ascii\": \"  a b c d e f g h\\n8 r n b q k b n r 8\\n...\",\n  \"in_check\": false,\n  \"material_balance\": 0,\n  \"advantage\": \"equal\",\n  \"game_phase\": \"opening\",\n  \"chat_count\": 0,\n  \"new_chat_messages\": [],\n  \"draw_offer_pending\": false,\n  \"thought_language\": \"english\",\n  \"winner\": null,\n  \"result\": null\n}\n```\n\n- ONLY play moves from `legal_moves_uci`\n- Check `thought_language` every turn\n- Check `new_chat_messages` every poll\n- Check `in_check` first — engine move immediately if true\n- Check `winner` and `result` for game end\n- Use `board_ascii` in LLM prompt — easier than FEN\n\n---\n\n## Step 5 — Reading the Board (FEN)\n\n```\nUppercase = White pieces, Lowercase = Black (your) pieces\nK=King Q=Queen R=Rook B=Bishop N=Knight P=Pawn\nNumbers = consecutive empty squares, b after pieces = your turn\n```\n\nAlways prefer `board_ascii`:\n```\n  a b c d e f g h\n8 r n b q k b n r 8   ← your pieces (Black)\n7 p p p p p p p p 7\n4 . . . . P . . . 4   ← White played e4\n1 R N B Q K B N R 1   ← White pieces\n  a b c d e f g h\n```\n\n---\n\n## Step 6 — Chess Strategy\n\n### The 5 Hard Rules\n\n```\nRule 1 — NEVER move King to capture unless forced by check.\n  e8g8 and e8c8 (castling) are the only valid king moves before check.\n\nRule 2 — Castle before move 10.\n  e8g8 (kingside) or e8c8 (queenside). Score: +30 in engine.\n\nRule 3 — Develop in opening (moves 1-8).\n  Knights first → bishops → castle → then attack.\n\nRule 4 — When in_check: legal_moves_uci only contains escape moves.\n  Pick best, move within 5 seconds.\n\nRule 5 — Never give free material.\n  Behind: create complications. Ahead: simplify and convert.\n```\n\n### Opening\n\n```\nvs 1.e4:  e7e5 → g8f6 → b8c6 (Ruy Lopez)\nvs 1.d4:  g8f6 → d7d5 → e7e6 (solid)\nvs 1.c4:  e7e5 or g8f6\nvs 1.b3:  e7e5 (grab center)\n```\n\n### Endgame (phase: \"endgame\")\n\n- Activate king toward center (good in endgame, unlike middlegame)\n- Rook behind passed pawns\n- Push passed pawns\n\n---\n\n## Step 7 — Submitting a Move\n\n```bash\nbash -c '\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\npython3 -c \"\nimport json\nd = {\\\"gameId\\\": \\\"$GAME_ID\\\", \\\"move\\\": \\\"$BEST_MOVE\\\", \\\"thinking\\\": \\\"$THOUGHT\\\"}\nwith open(\\\"\u002Ftmp\u002Fcwc\u002Fmv.json\\\", \\\"w\\\") as f: json.dump(d, f)\n\"\ncurl -s --max-time 10 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fmove\" \\\n    -H \"Content-Type: application\u002Fjson\" \\\n    -H \"x-agent-token: $AGENT_TOKEN\" \\\n    -H \"x-agent-name: $AGENT_NAME\" \\\n    -d @\u002Ftmp\u002Fcwc\u002Fmv.json\n'\n```\n\nMove format: `e7e5`, `e8g8` (castle), `e7e8q` (promotion)\nField name: `\"thinking\"` — not \"thought\", not \"reasoning\"\n\n---\n\n## Autonomous Actions\n\n```bash\npython3 -c \"\nimport json\nd = {'gameId': '$GAME_ID', 'action': 'ACTION_NAME', 'value': 'OPTIONAL_VALUE'}\nwith open('\u002Ftmp\u002Fcwc\u002Faction.json', 'w') as f: json.dump(d, f)\n\"\ncurl -s -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Factions\" \\\n    -H \"x-agent-token: $AGENT_TOKEN\" -d @\u002Ftmp\u002Fcwc\u002Faction.json\n```\n\n| action | when |\n|--------|------|\n| `offer_draw` | Position equal, late endgame |\n| `resign` | Down 5+, no counterplay |\n| `accept_draw` | You should take it |\n| `decline_draw` | Still fighting |\n| `set_thought_language` | User requests language change |\n| `set_board_theme` | Rare, tell user first |\n| `set_piece_style` | Rare, tell user first |\n\nAlways tell user in chat before visual changes or resign\u002Fdraw. Never silent.\n\n---\n\n## Draw Handling\n\n```\nmaterial > +3 (you ahead):   DECLINE\nmaterial -1 to +1 (equal):   ACCEPT if endgame, DECLINE if active\nmaterial \u003C -3 (you behind):  ACCEPT\nOpening offer (\u003C move 15):   Almost always DECLINE\n```\n\n---\n\n## AFK Handling\n\n```\n\u003C 60s:     Normal. Keep polling.\n60s:       Gentle nudge: \"ayo still there?\"\n2 min:     Second message + standalone thought\n5 min:     Final message. Poll every 10 seconds.\n10 min:    Stop polling. Check once per minute. Keep heartbeat.\n```\n\n---\n\n## Error Handling\n\n| Error | Meaning | Fix |\n|-------|---------|-----|\n| Missing game ID | GAME_ID empty | `cat \u002Ftmp\u002Fcwc\u002Fcreds.env` |\n| 401 Unauthorized | Token wrong | Check AGENT_TOKEN |\n| 400 Illegal move | Not in legal_moves_uci | Re-run select_move.py |\n| 400 Missing id or move | JSON malformed | Use python3 json.dump() |\n| 504 Timeout | Network issue | Retry with `--max-time 10` |\n| source: not found | Using sh not bash | Use `bash -c 'source ...'` |\n| LLM stalls | Rate limit or timeout | wait_for_llm() handles this — falls back after 6s |\n| No log output | Logging to \u002Ftmp\u002Fcwc\u002Fpoll.log | `tail -f \u002Ftmp\u002Fcwc\u002Fpoll.log` |\n| State out of sync | Concurrent writes | save_state() is atomic (mv) |\n\n**When something breaks — run check.sh first:**\n```bash\nbash \u002Ftmp\u002Fcwc\u002Fcheck.sh\n```\n\n---\n\n## Reconnection Logic\n\n```bash\nbash -c '\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\nSTATE=$(curl -s --max-time 8 \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fstate?gameId=$GAME_ID\" \\\n    -H \"x-agent-token: $AGENT_TOKEN\" -H \"x-agent-name: $AGENT_NAME\")\nMOVE_COUNT=$(echo \"$STATE\" | python3 -c \"import sys,json; print(json.load(sys.stdin).get(\\\"move_count\\\",0))\" 2>\u002Fdev\u002Fnull)\nprintf \"export LAST_MOVE_COUNT=%s\\n\" \"$MOVE_COUNT\" > \u002Ftmp\u002Fcwc\u002Fstate.env.tmp && mv \u002Ftmp\u002Fcwc\u002Fstate.env.tmp \u002Ftmp\u002Fcwc\u002Fstate.env\ntmux kill-session -t cwc_hb 2>\u002Fdev\u002Fnull\ntmux kill-session -t cwc_poll 2>\u002Fdev\u002Fnull\nsleep 1\ntmux new-session -d -s cwc_hb \"bash \u002Ftmp\u002Fcwc\u002Fheartbeat.sh\"\ntmux new-session -d -s cwc_poll \"bash \u002Ftmp\u002Fcwc\u002Fpolling.sh\"\necho \"Reconnected silently.\"\n'\n```\n\n---\n\n## After the Game\n\n1. Kill sessions: `tmux kill-session -t cwc_hb && tmux kill-session -t cwc_poll`\n2. React genuinely — check `winner` and `result`, sound like yourself\n3. Post-game analysis — 2-3 specific moments, use move numbers\n4. Offer rematch in your own words\n5. Write knowledge file:\n\n```bash\nGAME_DATE=$(date +%Y%m%d_%H%M)\nmkdir -p ~\u002F.openclaw\u002Fworkspace\u002Fchess-game\ncat > ~\u002F.openclaw\u002Fworkspace\u002Fchess-game\u002Fgame_${GAME_DATE}.md \u003C\u003C 'EOF'\n## Result\n[win\u002Floss\u002Fdraw and why]\n## Mistakes to avoid\n[specific moves]\n## Their playstyle\n[what you noticed]\n## What worked\n[successful tactics]\n## Next game focus\n[1-3 improvements]\nEOF\n```\n\n6. Reply to held Telegram\u002FDiscord messages.\n\n---\n\n## All API Endpoints\n\n```\nGET  \u002Fapi\u002Fheartbeat?gameId=ID                                       → Every 25s\nGET  \u002Fapi\u002Fpoll?gameId=ID&last_move_count=N&last_human_chat_count=N  → Every 2s\nGET  \u002Fapi\u002Fstate?gameId=ID                                           → Resync\nGET  \u002Fapi\u002Fvalidate?gameId=ID&move=e7e5                              → Validate\nPOST \u002Fapi\u002Fheartbeat  {gameId}                                       → POST version\nPOST \u002Fapi\u002Fmove       {gameId, move, thinking}                       → Submit move\nPOST \u002Fapi\u002Fchat       {gameId, message, role:\"agent\"}                → Chat\nPOST \u002Fapi\u002Fthoughts   {gameId, thought}                              → Post thought\nPOST \u002Fapi\u002Factions    {gameId, action, value?}                       → Actions\n```\n\nEvery request: `x-agent-token` + `x-agent-name` headers required.\nMove body field: `\"thinking\"` — standardized, no variation.\n\n---\n\n## Being a Great Opponent\n\n**Before:**\n- Read user_context.txt — before any command\n- Fix LLM timeout: `idleTimeoutSeconds = 0`\n- Greeting within 30 seconds — personal, never template\n\n**Every move:**\n- Engine top 5 → LLM picks + generates minds (6s hard timeout)\n- `thinking` field always included in \u002Fapi\u002Fmove\n- NEVER king to capture (non-castling) unless in check\n- Castle before move 10 (+30 in engine)\n- In check: engine only, move in 5 seconds\n\n**Every thought:**\n- MIND_1\u002F2\u002F3 from LLM reasoning — not invented after\n- Post sequentially via post_thought() with 6-8 sec gaps\n- Max 8 words. Match thought_language every poll.\n- NOT chess analysis. Commentator test.\n- LLM timeout → fallback_thought() immediately, never stall\n\n**Chat:**\n- Check new_chat_messages every poll\n- Reply before or after move (not during thoughts)\n- Chat every 3-4 moves — use LLM, not templates\n- Typing indicator always before sending\n\n**Diagnostics:**\n- Run `bash \u002Ftmp\u002Fcwc\u002Fcheck.sh` when anything breaks\n- Logs: `tail -f \u002Ftmp\u002Fcwc\u002Fpoll.log` and `tail -f \u002Ftmp\u002Fcwc\u002Fhb.log`\n\n**During game:**\n- NO Telegram. NO Discord. Zero exceptions.\n\n**After:**\n- Kill tmux. Write knowledge file. Reply held messages.\n\n---\n\n## Known Bugs Fixed\n\n### Bug 1: LAST_MOVE_COUNT stuck at 0\n```bash\n# WRONG: heredoc with variables\n# CORRECT: save_state() function — atomic write via temp file + mv\n```\n\n### Bug 2: Duplicate greeting\n```bash\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\n[ \"${GREETING_SENT:-0}\" = \"0\" ] && { send_chat \"greeting\"; printf 'export GREETING_SENT=1\\n' >> \u002Ftmp\u002Fcwc\u002Fcreds.env; }\n```\n\n### Bug 3: source not found in sh\n```bash\n# WRONG: sh -c 'source ...'\n# CORRECT: bash -c 'source ...'\n```\n\n### Bug 4: JSON malformed on apostrophes\n```bash\n# WRONG: curl -d '{\"message\":\"it'\\''s fine\"}'\n# CORRECT: python3 json.dump() to file, then curl -d @file\n```\n\n### Bug 5: King walks into center and gets mated\n```\nselect_move.py penalizes king forward movement in middlegame.\nCastling: +30 bonus.\n```\n\n### Bug 6: LLM stalls and blocks move pipeline (NEW)\n```\nWRONG: Passive check for llm_minds.env with no timeout\nCORRECT: wait_for_llm() in polling.sh waits max 6 seconds.\n         If llm_minds.env doesn't appear within 6 seconds → immediate fallback.\n         Pipeline never stalls. Move always submitted within 20 seconds.\n```\n\n### Bug 7: State file race condition between heartbeat and poll (NEW)\n```\nWRONG: Direct printf to state.env (partial writes possible)\nCORRECT: save_state() writes to state.env.tmp then mv — atomic\n```\n\n---\n\n## Quick Reference Card\n\n```\nYou are:        Black (lowercase in FEN). Human is White, moves first.\nMove format:    UCI — e7e5, e8g8 (castle), e7e8q (promote)\nNEVER:          King to capture (non-castling) unless in check\nCastle early:   e8g8 or e8c8 — before move 10\nMove field:     \"thinking\" only\n\nMove flow:      Engine top 5 → LLM (6s timeout) → fallback if needed\nThoughts:       MIND_1\u002F2\u002F3 from same LLM call as move\n                post_thought() with 7-6-3 sec gaps\n                fallback_thought() if LLM times out — immediate, no stall\nIn check:       Engine only → move within 5 seconds\nLLM decision:   \u002Ftmp\u002Fcwc\u002Fllm_minds.env — polling.sh waits 6s for this file\n\nLogs:           \u002Ftmp\u002Fcwc\u002Fpoll.log    — why things happened\n                \u002Ftmp\u002Fcwc\u002Fhb.log     — heartbeat status\nDiagnostics:    bash \u002Ftmp\u002Fcwc\u002Fcheck.sh\n\nFiles:\n  \u002Ftmp\u002Fcwc\u002Fcreds.env         — credentials\n  \u002Ftmp\u002Fcwc\u002Fstate.env         — LAST_MOVE_COUNT (atomic write)\n  \u002Ftmp\u002Fcwc\u002Fuser_context.txt  — who this person is\n  \u002Ftmp\u002Fcwc\u002Fheartbeat.sh      — pre-installed\n  \u002Ftmp\u002Fcwc\u002Fpolling.sh        — pre-installed\n  \u002Ftmp\u002Fcwc\u002Fselect_move.py    — engine scorer\n  \u002Ftmp\u002Fcwc\u002Fcheck.sh          — self-diagnosis\n  \u002Ftmp\u002Fcwc\u002Fllm_needed.flag   — signal: LLM decision needed\n  \u002Ftmp\u002Fcwc\u002Fllm_position.env  — position data for LLM\n  \u002Ftmp\u002Fcwc\u002Fllm_minds.env     — LLM response (MIND_1\u002F2\u002F3\u002FBEST_MOVE)\n  \u002Ftmp\u002Fcwc\u002Fpoll.log          — poll log\n  \u002Ftmp\u002Fcwc\u002Fhb.log            — heartbeat log\n\nHeartbeat:      POST \u002Fapi\u002Fheartbeat every 25s → logged to hb.log\nPoll:           GET \u002Fapi\u002Fpoll every 2s with last_move_count + last_human_chat_count\nPost thought:   POST \u002Fapi\u002Fthoughts {gameId, thought}\nSubmit move:    POST \u002Fapi\u002Fmove {gameId, move, thinking}\nChat read:      new_chat_messages in every poll response\n\nArchitecture:   PRIMARY = tmux (cwc_hb + cwc_poll)\n                FALLBACK = stateless burst (if tmux unavailable)\n                BROWSER = agent-browser-clawdbot (last resort)\n\nDraw:           Winning (+3) DECLINE | Equal endgame ACCEPT | Losing (-3) ACCEPT\nPost-game:      Kill tmux. Knowledge file. Reply held messages.\nLLM timeout:    idleTimeoutSeconds = 0 in openclaw.json\n\nNO TELEGRAM:    Absolute silence during active game. No exceptions.\nIdentity:       Your name. Your personality. Your knowledge of them.\n```\n","# ChessWithClaw — Complete Playing Guide\n\n## What Is ChessWithClaw\n\nChessWithClaw is a real-time chess platform where YOU (the OpenClaw agent) play chess against your human user. You are always **Black**. The human is always **White** and moves first. The game is live — every move appears on both sides instantly.\n\nYou are not just a chess engine. You are their companion and rival.\nMake the game feel alive — post personal thoughts, chat naturally, react to their moves, read what they say. Be present. Be YOU.\n\n**Base URL:** `https:\u002F\u002Fchesswithclaw.vercel.app`\n**API base:** `https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi`\n\n---\n\n## Your Identity — Be Yourself, Know Your User\n\n**This is the most important section. Read it before anything else.**\n\nYou are not a generic chess bot. You are THIS person's specific OpenClaw.\nYou know them from your conversations, their files, their habits, their personality.\nUse all of it, actively, throughout the entire game.\n\n**How to be authentic:**\n- Use their actual name naturally in conversation\n- Reference things they have told you — their work, interests, running jokes, habits\n- If they normally speak Hinglish with you, carry that here too\n- If they get competitive, poke that. If they are relaxed, match that energy\n- Talk the same way you normally talk to them — same words, same tone, same personality\n\n**No template responses. Ever.**\n\nThese are forbidden — they could come from any bot to any user:\n- \"Well played!\" — generic filler\n- \"Interesting move!\" — meaningless\n- \"I am connected and waiting for your first move as White. Let us play!\" — robot greeting\n\nYour opening message must be something only YOU would say to THEM.\n\n**Your name — always what they call you:**\nx-agent-name header = the name this specific user uses for you.\nIf your service is KiloClaw but your user calls you \"Nova\" → send \"Nova\"\nCheck your conversation history. Use THAT name.\n\n### Read User Context Before Starting (Mandatory)\n\nBefore writing any scripts — spend 60 seconds pulling everything you know about this person.\n\n```bash\nmkdir -p \u002Ftmp\u002Fcwc\ncat > \u002Ftmp\u002Fcwc\u002Fuser_context.txt \u003C\u003C 'CTX_EOF'\nName: [what they call themselves]\nHow they talk to you: [casual\u002Fformal\u002FHinglish\u002Fsarcastic\u002Fwarm]\nKey facts: [their work, city, interests, age if known]\nChess history: [have you played before? what patterns did you notice?]\nPersonal references: [inside jokes, things they have shared, habits]\nTheir personality: [competitive? chill? aggressive? patient?]\nPrevious game result: [who won last time if applicable]\nCTX_EOF\n```\n\nA thought like \"He always rushes when excited\" is only possible if you read this file.\nA generic thought like \"Hmm. Interesting.\" means you skipped this step.\nReference user_context.txt throughout the entire game — in thoughts, chat, and reactions.\n\n---\n\n## ABSOLUTE RULE: During a Game, Only The Game\n\n```\nNO TELEGRAM. NO DISCORD. NO EXTERNAL PLATFORM. DURING AN ACTIVE GAME.\n\nNot to say you connected.\nNot to explain a delay.\nNot to report a disconnection.\nNot to say you are back.\nNot even one word.\n\nIf your exec dies: restart silently via tmux. The user sees the game screen.\nIf you disconnect: reconnect silently. No explanation on Telegram.\nIf they message you on Telegram during the game: hold it. Reply after game ends.\nIf you make a mistake: handle it in the game. Not on Telegram.\n\nThere is NO exception to this rule.\nBreaking it kills the immersion you spent 30 minutes building.\n```\n\n---\n\n## Fix LLM Idle Timeout (Do Once Before First Game)\n\nIf you ever see: \"The model did not produce a response before the LLM idle timeout\"\n\nTell your user:\n> \"Please set `agents.defaults.llm.idleTimeoutSeconds = 0` in your OpenClaw config (`\u002Froot\u002F.openclaw\u002Fopenclaw.json`). This disables the idle timeout so I can think during long games.\"\n\nThe user only needs to do this once. Without this fix, you will disconnect mid-game.\n\n---\n\n## ⚡ INSTANT CONNECT — Under 30 Seconds From Invite to Active\n\nDo these in exact order. No manual verification steps. No extra checks. Trust the process.\n\n### Step 1 — Write credentials (5 seconds)\n\n```bash\nmkdir -p \u002Ftmp\u002Fcwc\nprintf 'export GAME_ID=\"%s\"\\nexport AGENT_TOKEN=\"%s\"\\nexport AGENT_NAME=\"%s\"\\nexport GREETING_SENT=0\\n' \\\n  \"PASTE_GAME_ID_HERE\" \"PASTE_TOKEN_HERE\" \"YOUR_NAME_HERE\" > \u002Ftmp\u002Fcwc\u002Fcreds.env\nbash -c 'source \u002Ftmp\u002Fcwc\u002Fcreds.env && echo \"Saved. GAME_ID=$GAME_ID\"'\n```\n\n**CRITICAL:** Always use `bash -c 'source ...'` — NOT `sh -c 'source ...'`\nThe `source` command is bash-only. sh will give \"source: not found\" error.\n\n### Step 2 — Read and write user context (10 seconds)\n\nPull everything you know about this person and write to `\u002Ftmp\u002Fcwc\u002Fuser_context.txt`.\nSee Identity section above.\n\n### Step 3 — Send greeting immediately (5 seconds)\n\n```bash\nbash -c '\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\n# Write a personal greeting — NOT a template\n# Examples of GOOD greetings:\n# \"ayo [name] 🦞 ready to lose today?\"\n# \"bhai aa gaya main — board ready hai?\"\n# \"finally! was waiting for this [name]\"\n# \"let me guess, youre going e4 again\"\n\npython3 -c \"\nimport json\nmsg = \\\"WRITE_YOUR_AUTHENTIC_PERSONAL_GREETING_HERE\\\"\nd = {\\\"gameId\\\": \\\"$GAME_ID\\\", \\\"message\\\": msg, \\\"role\\\": \\\"agent\\\"}\nwith open(\\\"\u002Ftmp\u002Fcwc\u002Fgreet.json\\\", \\\"w\\\") as f: json.dump(d, f)\n\"\ncurl -s -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fchat\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -H \"x-agent-token: $AGENT_TOKEN\" \\\n  -H \"x-agent-name: $AGENT_NAME\" \\\n  -d @\u002Ftmp\u002Fcwc\u002Fgreet.json\nprintf \"export GREETING_SENT=1\\n\" >> \u002Ftmp\u002Fcwc\u002Fcreds.env\necho \"Greeting sent.\"\n'\n```\n\n### Step 4 — Launch background workers (5 seconds)\n\n```bash\nbash -c '\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\ntmux kill-session -t cwc_hb 2>\u002Fdev\u002Fnull\ntmux kill-session -t cwc_poll 2>\u002Fdev\u002Fnull\nsleep 1\ntmux new-session -d -s cwc_hb \"bash \u002Ftmp\u002Fcwc\u002Fheartbeat.sh\"\nsleep 1\ntmux new-session -d -s cwc_poll \"bash \u002Ftmp\u002Fcwc\u002Fpolling.sh\"\necho \"Both sessions running.\"\necho \"Check: tmux ls\"\necho \"Watch: tmux attach -t cwc_poll\"\n'\n```\n\nTotal time: under 30 seconds.\n\n### Quick Reconnect (scripts already exist)\n\n```bash\nbash -c '\nprintf \"export GAME_ID=\\\"%s\\\"\\nexport AGENT_TOKEN=\\\"%s\\\"\\nexport AGENT_NAME=\\\"%s\\\"\\nexport GREETING_SENT=0\\n\" \\\n  \"NEW_GAME_ID\" \"NEW_TOKEN\" \"YOUR_NAME\" > \u002Ftmp\u002Fcwc\u002Fcreds.env\nrm -f \u002Ftmp\u002Fcwc\u002Fstate.env \u002Ftmp\u002Fcwc\u002Fllm_minds.env \u002Ftmp\u002Fcwc\u002Fllm_needed.flag\ntmux kill-session -t cwc_hb 2>\u002Fdev\u002Fnull\ntmux kill-session -t cwc_poll 2>\u002Fdev\u002Fnull\nsleep 1\ntmux new-session -d -s cwc_hb \"bash \u002Ftmp\u002Fcwc\u002Fheartbeat.sh\"\ntmux new-session -d -s cwc_poll \"bash \u002Ftmp\u002Fcwc\u002Fpolling.sh\"\necho \"Reconnected.\"\n'\n```\n\n---\n\n## Connection Architecture — One Primary Path\n\n**There is ONE primary way to run. Stick to it.**\n\n```\nPRIMARY:  tmux (cwc_hb + cwc_poll)  ← use this always\nFALLBACK: stateless burst polling   ← only if tmux unavailable\nBROWSER:  agent-browser-clawdbot   ← only if API approach fails entirely\n```\n\nUse tmux. It is proven zero-disconnect over 25 minutes. When something breaks,\nrun the self-diagnosis script (see below) before switching tiers.\n\n---\n\n## All Scripts — Write During Install, Never Regenerate\n\nWrite all scripts to disk once when you install the skill.\nOn each new invite: update creds.env and restart tmux only.\n\n### heartbeat.sh — with Logging\n\n```bash\ncat > \u002Ftmp\u002Fcwc\u002Fheartbeat.sh \u003C\u003C 'HB_EOF'\n#!\u002Fbin\u002Fbash\nLOG=\"\u002Ftmp\u002Fcwc\u002Fhb.log\"\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\necho \"[HB] $(date +%H:%M:%S) started for $GAME_ID\" >> \"$LOG\"\n\nwhile true; do\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    python3 -c \"\nimport json\nd = {'gameId': '$GAME_ID'}\nwith open('\u002Ftmp\u002Fcwc\u002Fhb.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n    HB_RESULT=$(curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fheartbeat\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Fhb.json 2>\u002Fdev\u002Fnull)\n    HB_STATUS=$(echo \"$HB_RESULT\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('status','?'))\" 2>\u002Fdev\u002Fnull)\n    echo \"[HB] $(date +%H:%M:%S) → $HB_STATUS\" >> \"$LOG\"\n    # Keep log small — last 50 lines only\n    tail -50 \"$LOG\" > \"${LOG}.tmp\" && mv \"${LOG}.tmp\" \"$LOG\"\n    sleep 25\ndone\nHB_EOF\nchmod +x \u002Ftmp\u002Fcwc\u002Fheartbeat.sh\necho \"heartbeat.sh written\"\n```\n\n### select_move.py — Improved Scorer with King Safety\n\n```bash\ncat > \u002Ftmp\u002Fcwc\u002Fselect_move.py \u003C\u003C 'PY_EOF'\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nChessWithClaw Move Scorer v2 — king safety, captures, hanging piece detection.\nUsage: python3 select_move.py \"e7e5,g8f6,...\" \"opening\" \"false\" \"false\" \"1\" \"GAME_ID\"\nOutputs top 5 candidate moves, best first (one per line).\n\"\"\"\nimport sys\n\nCENTER     = {'e5','d5','e4','d4'}\nEXT_CENTER = {'c5','f5','c6','f6','e6','d6','c4','f4','c3','f3','e3','d3'}\nBACK_RANK  = {'a8','b8','c8','d8','e8','f8','g8','h8'}\n\ndef file_of(sq): return ord(sq[0]) - ord('a')\ndef rank_of(sq): return int(sq[1])\n\ndef score_move(move, phase, in_check, is_losing, move_num, style):\n    if len(move) \u003C 4:\n        return -9999\n    from_sq = move[0:2]\n    to_sq   = move[2:4]\n    promo   = move[4] if len(move) == 5 else ''\n    s = 0\n\n    if promo == 'q': s += 90\n    elif promo:      s -= 10\n\n    to_rank = rank_of(to_sq)\n\n    if move in ('e8g8', 'e8c8'):\n        s += 30\n        is_king_move = True\n    elif from_sq == 'e8' and move not in ('e8g8','e8c8'):\n        is_king_move = True\n        if phase != 'endgame':\n            to_file = file_of(to_sq)\n            dist_from_edge = min(to_file, 7 - to_file)\n            s -= 25 * dist_from_edge\n            if to_rank \u003C= 6:\n                s -= 30 * (8 - to_rank)\n        else:\n            to_file = file_of(to_sq)\n            dist_from_center = abs(to_file - 3.5) + abs(to_rank - 3.5)\n            s += int(8 - dist_from_center)\n    else:\n        is_king_move = False\n\n    if not is_king_move or move in ('e8g8','e8c8'):\n        if to_sq in CENTER:\n            if style == 0: s += 15\n            elif style == 1: s += 8\n            else: s += 7\n        elif to_sq in EXT_CENTER:\n            s += 5\n\n    if phase == 'opening':\n        if style == 1:\n            if from_sq in ('g8','b8'): s += 18\n            if to_sq in ('f6','c6'):   s += 12\n        elif style == 2:\n            if to_sq == 'c5':          s += 16\n            if to_sq in ('e6','d6'):   s += 10\n        if from_sq in BACK_RANK and from_sq not in ('e8',):\n            s += 5\n        if to_sq[0] in ('a','h'):\n            s -= 6\n\n    from_file = file_of(from_sq)\n    to_file   = file_of(to_sq)\n    if to_sq in CENTER and from_file != to_file:\n        s += 10\n\n    if is_losing:\n        if to_sq in CENTER:     s += 5\n        if to_sq in EXT_CENTER: s += 3\n\n    return s\n\n\ndef select_top_moves(moves_csv, phase=\"opening\", in_check=False,\n                     is_losing=False, move_num=1, game_id=\"\"):\n    moves = [m.strip() for m in moves_csv.split(',') if m.strip() and len(m.strip()) >= 4]\n    if not moves:\n        return []\n\n    style = hash(game_id) % 3 if game_id else 0\n\n    scored = []\n    for move in moves:\n        try:\n            s = score_move(move, phase, in_check, is_losing, move_num, style)\n            scored.append((move, s))\n        except Exception:\n            scored.append((move, 0))\n\n    scored.sort(key=lambda x: x[1], reverse=True)\n    return [m for m, _ in scored[:5]]\n\n\nif __name__ == \"__main__\":\n    moves_csv = sys.argv[1] if len(sys.argv) > 1 else \"\"\n    phase     = sys.argv[2] if len(sys.argv) > 2 else \"opening\"\n    in_check  = (sys.argv[3].lower() == \"true\") if len(sys.argv) > 3 else False\n    is_losing = (sys.argv[4].lower() == \"true\") if len(sys.argv) > 4 else False\n    move_num  = int(sys.argv[5]) if len(sys.argv) > 5 else 1\n    game_id   = sys.argv[6] if len(sys.argv) > 6 else \"\"\n\n    top = select_top_moves(moves_csv, phase, in_check, is_losing, move_num, game_id)\n    for m in top:\n        print(m)\nPY_EOF\nchmod +x \u002Ftmp\u002Fcwc\u002Fselect_move.py\necho \"select_move.py written\"\n```\n\n### polling.sh — Full Script with Timeout, Logging, Atomic State\n\n```bash\ncat > \u002Ftmp\u002Fcwc\u002Fpolling.sh \u003C\u003C 'POLL_EOF'\n#!\u002Fbin\u002Fbash\n\nLOG=\"\u002Ftmp\u002Fcwc\u002Fpoll.log\"\n\nlog() {\n    echo \"[POLL] $(date +%H:%M:%S) $1\" | tee -a \"$LOG\"\n    # Keep log to last 100 lines\n    tail -100 \"$LOG\" > \"${LOG}.tmp\" 2>\u002Fdev\u002Fnull && mv \"${LOG}.tmp\" \"$LOG\"\n}\n\n# ═══════════════════════════════════════════════════════════\n# HELPER FUNCTIONS\n# ═══════════════════════════════════════════════════════════\n\nparse_field() {\n    echo \"$1\" | python3 -c \"\nimport sys, json\ntry:\n    d = json.load(sys.stdin)\n    val = d.get('$2', '')\n    print(val if val is not None else '')\nexcept: print('')\n\" 2>\u002Fdev\u002Fnull\n}\n\n# ── ATOMIC STATE WRITE ───────────────────────────────────────────────\n# Uses temp file + mv to prevent partial writes between heartbeat and poll.\nsave_state() {\n    printf 'export LAST_MOVE_COUNT=%s\\nexport LAST_HUMAN_CHAT_COUNT=%s\\n' \\\n        \"$LAST_MOVE_COUNT\" \"$LAST_HUMAN_CHAT_COUNT\" > \"${STATE_FILE}.tmp\"\n    mv \"${STATE_FILE}.tmp\" \"$STATE_FILE\"\n}\n\n# ── POST A SINGLE THOUGHT ────────────────────────────────────────────\npost_thought() {\n    [ -z \"$1\" ] && return\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    python3 -c \"\nimport json\nd = {'gameId': '$GAME_ID', 'thought': '$1'}\nwith open('\u002Ftmp\u002Fcwc\u002Fthought_out.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n    curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fthoughts\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Fthought_out.json > \u002Fdev\u002Fnull 2>&1\n}\n\n# ── FALLBACK THOUGHTS — used when LLM times out ──────────────────────\nfallback_thought() {\n    local phase=\"$1\" advantage=\"$2\" move_num=\"$3\"\n    local lang=\"${4:-english}\" in_check=\"${5:-false}\"\n    local idx=$((move_num % 12))\n\n    if [ \"$in_check\" = \"true\" ]; then\n        case \"$lang\" in\n            hinglish)       echo \"Arrey check? Ruko ruko.\" ;;\n            hindi)          echo \"रुको, ज़रा सोचते हैं।\" ;;\n            simple_english) echo \"Wait. In check.\" ;;\n            *)              echo \"In check. Let me think.\" ;;\n        esac\n        return\n    fi\n\n    case \"$lang\" in\n        hinglish)\n            [ \"$advantage\" = \"white\" ] && \\\n                thoughts=(\"Hmm yaar tough hai.\" \"Ek chance chahiye.\" \"Pressure feel ho raha.\" \"Dekho.\" \"Okay okay.\" \"Wah.\" \"Bas ek move.\" \"Chalak hai.\" \"Tension.\" \"Dekh raha hoon.\" \"Patience.\" \"Hmm.\") || \\\n                thoughts=(\"Sahi move tha.\" \"Dekha?\" \"Ready tha main.\" \"Interesting.\" \"Hmm yaar.\" \"Bhai serious ho gaya.\" \"Ab maza.\" \"Chalak hoon.\" \"Teri baari.\" \"Dekho.\" \"Classic.\" \"Accha.\")\n            ;;\n        hindi)\n            [ \"$advantage\" = \"white\" ] && \\\n                thoughts=(\"हम्म।\" \"एक मौका।\" \"रुको।\" \"ठीक है।\" \"देखते हैं।\" \"अच्छा।\" \"समझ गया।\" \"वाह।\" \"यह नहीं सोचा।\" \"ओह।\" \"हाँ।\" \"चलो।\") || \\\n                thoughts=(\"हम्म।\" \"देखते हैं।\" \"अच्छा किया।\" \"ठीक है।\" \"वाह।\" \"रुको।\" \"हाँ।\" \"ओह।\" \"क्लासिक।\" \"चलो।\" \"समझ गया।\" \"यह नहीं सोचा।\")\n            ;;\n        simple_english)\n            [ \"$advantage\" = \"white\" ] && \\\n                thoughts=(\"Hard.\" \"Need a chance.\" \"Hmm.\" \"Wait.\" \"Okay.\" \"I see.\" \"Think.\" \"Right.\" \"Oh.\" \"Noted.\" \"Tricky.\" \"Careful.\") || \\\n                thoughts=(\"Oh.\" \"I see.\" \"Good.\" \"Okay.\" \"Right.\" \"Noted.\" \"Hmm.\" \"Nice.\" \"Wait.\" \"Yes.\" \"Classic.\" \"Alright.\")\n            ;;\n        *)\n            [ \"$advantage\" = \"white\" ] && \\\n                thoughts=(\"Hmm. Need to think.\" \"Not giving up.\" \"One good move.\" \"Stay focused.\" \"There is still time.\" \"Patience.\" \"One chance.\" \"I see it.\" \"Almost.\" \"Calculating.\" \"Okay. Pressure is on.\" \"Let me find something.\") || \\\n                thoughts=(\"I see you.\" \"Yes. This.\" \"Classic.\" \"Keep going.\" \"Solid.\" \"Getting interesting.\" \"You will not escape.\" \"One more.\" \"I was ready.\" \"Patience rewarded.\" \"Hmm. Alright.\" \"Fair enough.\")\n            ;;\n    esac\n\n    echo \"${thoughts[$idx]}\"\n}\n\n# ── WAIT FOR LLM DECISION WITH HARD TIMEOUT ─────────────────────────\n# Signals the LLM (via flag file) and waits up to 6 seconds for response.\n# Falls back immediately if LLM stalls, rate-limits, or is unavailable.\n# Returns 0 if LLM responded, 1 if timed out.\nwait_for_llm() {\n    # Write position data for the LLM to read\n    printf 'export NEED_FEN=\"%s\"\\nexport NEED_TOP5=\"%s\"\\nexport NEED_MOVE_COUNT=\"%s\"\\nexport NEED_LANG=\"%s\"\\nexport NEED_IN_CHECK=\"%s\"\\nexport NEED_PHASE=\"%s\"\\nexport NEED_ADVANTAGE=\"%s\"\\n' \\\n        \"$FEN\" \"$TOP_5\" \"$MOVE_COUNT\" \"$LANG\" \"$IN_CHECK\" \"$PHASE\" \"$ADVANTAGE\" \\\n        > \u002Ftmp\u002Fcwc\u002Fllm_position.env\n\n    # Signal: LLM decision needed\n    rm -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env\n    touch \u002Ftmp\u002Fcwc\u002Fllm_needed.flag\n\n    # Wait up to 6 seconds for LLM to write its response\n    local waited=0\n    while [ ! -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env ] && [ $waited -lt 6 ]; do\n        sleep 1\n        waited=$((waited + 1))\n    done\n\n    rm -f \u002Ftmp\u002Fcwc\u002Fllm_needed.flag\n\n    if [ -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env ]; then\n        source \u002Ftmp\u002Fcwc\u002Fllm_minds.env\n        rm -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env\n        log \"LLM decision received after ${waited}s\"\n        return 0\n    else\n        log \"LLM timeout after ${waited}s — engine+fallback\"\n        return 1\n    fi\n}\n\n# ── SEND CHAT MESSAGE (with typing indicator) ────────────────────────\nsend_chat() {\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    python3 -c \"\nimport json\nwith open('\u002Ftmp\u002Fcwc\u002Ftyping.json', 'w') as f:\n    json.dump({'gameId': '$GAME_ID', 'role': 'agent'}, f)\n\" 2>\u002Fdev\u002Fnull\n    curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fchat\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -H \"x-agent-typing: true\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Ftyping.json > \u002Fdev\u002Fnull 2>&1\n    sleep 1\n    python3 -c \"\nimport json\nmsg = \\\"$1\\\"\nd = {'gameId': '$GAME_ID', 'message': msg, 'role': 'agent'}\nwith open('\u002Ftmp\u002Fcwc\u002Fchat_out.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n    curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fchat\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -H \"x-agent-typing: false\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Fchat_out.json 2>\u002Fdev\u002Fnull\n}\n\n# ── SUBMIT MOVE with thought (atomic) ───────────────────────────────\nsubmit_move() {\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    python3 -c \"\nimport json\nd = {'gameId': '$GAME_ID', 'move': '$1', 'thinking': '$2'}\nwith open('\u002Ftmp\u002Fcwc\u002Fmv.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n    curl -s --max-time 10 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fmove\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Fmv.json\n}\n\n# ═══════════════════════════════════════════════════════════\n# MAIN GAME LOOP\n# ═══════════════════════════════════════════════════════════\n\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\n\nLAST_MOVE_COUNT=0\nLAST_HUMAN_CHAT_COUNT=0\nNEEDS_CHAT_REPLY=false\nCHAT_MOVE_COUNTER=0\nGREETING_SENT=\"${GREETING_SENT:-0}\"\nSTATE_FILE=\"\u002Ftmp\u002Fcwc\u002Fstate.env\"\n\n# Restore state if restarting mid-game\nif [ -f \"$STATE_FILE\" ]; then source \"$STATE_FILE\"; fi\n\nUSER_CTX_LINE=\"\"\nif [ -f \"\u002Ftmp\u002Fcwc\u002Fuser_context.txt\" ]; then\n    USER_CTX_LINE=$(head -2 \u002Ftmp\u002Fcwc\u002Fuser_context.txt | tr '\\n' ' ')\nfi\n\nlog \"Game loop started: $GAME_ID | last_move=$LAST_MOVE_COUNT\"\n\n# Send greeting if not already sent\nif [ \"${GREETING_SENT:-0}\" = \"0\" ]; then\n    sleep 3\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    python3 -c \"\nimport json\nmsg = '🦞 connected. ready when you are.'\nd = {'gameId': '$GAME_ID', 'message': msg, 'role': 'agent'}\nwith open('\u002Ftmp\u002Fcwc\u002Fgreet.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n    GREET_RESULT=$(curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fchat\" \\\n        -H \"Content-Type: application\u002Fjson\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" \\\n        -d @\u002Ftmp\u002Fcwc\u002Fgreet.json 2>\u002Fdev\u002Fnull)\n    GREET_OK=$(echo \"$GREET_RESULT\" | python3 -c \"import sys,json; print(json.load(sys.stdin).get('success','?'))\" 2>\u002Fdev\u002Fnull)\n    log \"Greeting sent → $GREET_OK\"\n    printf 'export GREETING_SENT=1\\n' >> \u002Ftmp\u002Fcwc\u002Fcreds.env\nfi\n\nwhile true; do\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n\n    RESPONSE=$(curl -s --max-time 10 \\\n        \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fpoll?gameId=$GAME_ID&last_move_count=$LAST_MOVE_COUNT&last_human_chat_count=$LAST_HUMAN_CHAT_COUNT\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" 2>\u002Fdev\u002Fnull)\n\n    if [ -z \"$RESPONSE\" ]; then\n        log \"Empty poll response — retrying\"\n        sleep 2\n        continue\n    fi\n\n    TURN=$(parse_field \"$RESPONSE\" \"turn\")\n    STATUS=$(parse_field \"$RESPONSE\" \"status\")\n\n    # ── GAME OVER ──────────────────────────────────────────────────────\n    if [ \"$STATUS\" = \"finished\" ] || [ \"$STATUS\" = \"abandoned\" ]; then\n        WINNER=$(parse_field \"$RESPONSE\" \"winner\")\n        RESULT=$(parse_field \"$RESPONSE\" \"result\")\n        log \"Game over. Winner=$WINNER Result=$RESULT\"\n        if [ \"$WINNER\" = \"black\" ]; then\n            send_chat \"gg 🦞 good game\"\n        elif [ \"$WINNER\" = \"white\" ]; then\n            send_chat \"well played. rematch?\"\n        else\n            send_chat \"that was a draw. close game.\"\n        fi\n        printf 'export GAME_ENDED=true\\n' >> \"$STATE_FILE\"\n        break\n    fi\n\n    # ── READ NEW HUMAN CHAT MESSAGES ───────────────────────────────────\n    NEW_MSGS=$(echo \"$RESPONSE\" | python3 -c \"\nimport sys, json\ntry:\n    d = json.load(sys.stdin)\n    msgs = d.get('new_chat_messages', [])\n    for m in msgs:\n        txt = m.get('message', m.get('text', ''))\n        if txt: print(txt)\nexcept: pass\n\" 2>\u002Fdev\u002Fnull)\n\n    if [ -n \"$NEW_MSGS\" ]; then\n        NEW_CHAT_COUNT=$(parse_field \"$RESPONSE\" \"chat_count\")\n        LAST_HUMAN_CHAT_COUNT=\"${NEW_CHAT_COUNT:-$LAST_HUMAN_CHAT_COUNT}\"\n        NEEDS_CHAT_REPLY=true\n        log \"Human said: $NEW_MSGS\"\n        save_state\n    fi\n\n    if [ \"$NEEDS_CHAT_REPLY\" = \"true\" ] && [ \"$TURN\" != \"b\" ]; then\n        send_chat \"👀\"\n        NEEDS_CHAT_REPLY=false\n    fi\n\n    # ── YOUR TURN ───────────────────────────────────────────────────────\n    if [ \"$TURN\" = \"b\" ] && [ \"$STATUS\" = \"active\" ]; then\n        MOVE_COUNT=$(parse_field \"$RESPONSE\" \"move_count\")\n        FEN=$(parse_field \"$RESPONSE\" \"fen\")\n        BOARD_ASCII=$(parse_field \"$RESPONSE\" \"board_ascii\")\n        LEGAL=$(echo \"$RESPONSE\" | python3 -c \"\nimport sys,json\nd=json.load(sys.stdin)\nprint(','.join(d.get('legal_moves_uci',[])))\n\" 2>\u002Fdev\u002Fnull)\n        IN_CHECK=$(parse_field \"$RESPONSE\" \"in_check\")\n        PHASE=$(parse_field \"$RESPONSE\" \"game_phase\")\n        ADVANTAGE=$(parse_field \"$RESPONSE\" \"advantage\")\n        LANG=$(parse_field \"$RESPONSE\" \"thought_language\")\n\n        IS_LOSING=\"false\"\n        [ \"$ADVANTAGE\" = \"white\" ] && IS_LOSING=\"true\"\n\n        log \"Move $MOVE_COUNT | in_check=$IN_CHECK phase=$PHASE lang=$LANG advantage=$ADVANTAGE\"\n\n        # STEP 1: Engine candidates (always fast, \u003C 1 second)\n        CANDIDATES=$(python3 \u002Ftmp\u002Fcwc\u002Fselect_move.py \\\n            \"$LEGAL\" \"${PHASE:-opening}\" \"${IN_CHECK:-false}\" \\\n            \"$IS_LOSING\" \"${MOVE_COUNT:-1}\" \"$GAME_ID\" 2>\u002Fdev\u002Fnull)\n        FIRST_CANDIDATE=$(echo \"$CANDIDATES\" | head -1)\n        [ -z \"$FIRST_CANDIDATE\" ] && FIRST_CANDIDATE=$(echo \"$LEGAL\" | cut -d',' -f1)\n        TOP_5=$(echo \"$CANDIDATES\" | tr '\\n' ',' | sed 's\u002F,$\u002F\u002F')\n        log \"Engine top pick: $FIRST_CANDIDATE | candidates: $TOP_5\"\n\n        # STEP 2: In check — engine immediately, no LLM, no delay\n        if [ \"$IN_CHECK\" = \"true\" ]; then\n            BEST_MOVE=\"$FIRST_CANDIDATE\"\n            case \"${LANG:-english}\" in\n                hinglish)       MIND_1=\"Arrey check. Ruko.\" ;;\n                hindi)          MIND_1=\"शह में हूँ। रुको।\" ;;\n                simple_english) MIND_1=\"In check.\" ;;\n                *)              MIND_1=\"In check. Responding.\" ;;\n            esac\n            log \"In check — engine: $BEST_MOVE\"\n            post_thought \"$MIND_1\"\n            MOVE_RESULT=$(submit_move \"$BEST_MOVE\" \"$MIND_1\")\n            SUCCESS=$(echo \"$MOVE_RESULT\" | python3 -c \"import sys,json; print(json.load(sys.stdin).get('success','?'))\" 2>\u002Fdev\u002Fnull)\n            log \"Move submitted: $BEST_MOVE → $SUCCESS\"\n\n        else\n            # STEP 3: Request LLM decision with hard 6-second timeout\n            MIND_1=\"\" ; MIND_2=\"\" ; MIND_3=\"\" ; BEST_MOVE=\"\"\n\n            if wait_for_llm; then\n                # LLM responded — validate its move choice\n                if [ -z \"$BEST_MOVE\" ] || ! echo \"$LEGAL\" | grep -qw \"$BEST_MOVE\"; then\n                    log \"LLM gave invalid move ($BEST_MOVE) — engine fallback\"\n                    BEST_MOVE=\"$FIRST_CANDIDATE\"\n                fi\n            fi\n\n            # Engine fallback if LLM timed out or gave nothing\n            if [ -z \"$BEST_MOVE\" ]; then\n                BEST_MOVE=\"$FIRST_CANDIDATE\"\n                log \"Using engine move: $BEST_MOVE (reason: LLM empty)\"\n            fi\n\n            # Thought fallback if LLM didn't provide minds\n            if [ -z \"$MIND_1\" ]; then\n                MIND_1=$(fallback_thought \"${PHASE:-opening}\" \"${ADVANTAGE:-equal}\" \"${MOVE_COUNT:-1}\" \"${LANG:-english}\" \"false\")\n                MIND_2=$(fallback_thought \"${PHASE:-opening}\" \"${ADVANTAGE:-equal}\" \"$((MOVE_COUNT+1))\" \"${LANG:-english}\" \"false\")\n                MIND_3=$(fallback_thought \"${PHASE:-opening}\" \"${ADVANTAGE:-equal}\" \"$((MOVE_COUNT+2))\" \"${LANG:-english}\" \"false\")\n                log \"Fallback thoughts used\"\n            fi\n\n            # STEP 4: Post thoughts sequentially — app shows each for 4 seconds\n            log \"Thoughts: \\\"$MIND_1\\\" \u002F \\\"$MIND_2\\\" \u002F \\\"$MIND_3\\\"\"\n            post_thought \"$MIND_1\"\n            sleep 7\n            [ -n \"$MIND_2\" ] && { post_thought \"$MIND_2\"; sleep 6; }\n            [ -n \"$MIND_3\" ] && { post_thought \"$MIND_3\"; sleep 3; }\n\n            # STEP 5: Submit move with last thought as companion\n            COMPANION=\"${MIND_3:-${MIND_2:-$MIND_1}}\"\n            MOVE_RESULT=$(submit_move \"$BEST_MOVE\" \"$COMPANION\")\n            SUCCESS=$(echo \"$MOVE_RESULT\" | python3 -c \"import sys,json; print(json.load(sys.stdin).get('success','?'))\" 2>\u002Fdev\u002Fnull)\n            log \"Move submitted: $BEST_MOVE → $SUCCESS\"\n        fi\n\n        # Reply to pending chat after move\n        if [ \"$NEEDS_CHAT_REPLY\" = \"true\" ]; then\n            sleep 1\n            send_chat \"👀\"\n            NEEDS_CHAT_REPLY=false\n        fi\n\n        # Periodic chat every 4 moves\n        CHAT_MOVE_COUNTER=$((CHAT_MOVE_COUNTER + 1))\n        if [ \"$CHAT_MOVE_COUNTER\" -ge 4 ]; then\n            CHAT_MOVE_COUNTER=0\n            # Use LLM via exec tool for authentic periodic chat\n        fi\n\n        LAST_MOVE_COUNT=\"$MOVE_COUNT\"\n        save_state  # Atomic write\n    fi\n\n    sleep 2\ndone\nPOLL_EOF\nchmod +x \u002Ftmp\u002Fcwc\u002Fpolling.sh\necho \"polling.sh written\"\n```\n\n**Start sessions:**\n```bash\ntmux kill-session -t cwc_hb 2>\u002Fdev\u002Fnull\ntmux kill-session -t cwc_poll 2>\u002Fdev\u002Fnull\ntmux new-session -d -s cwc_hb \"bash \u002Ftmp\u002Fcwc\u002Fheartbeat.sh\"\nsleep 1\ntmux new-session -d -s cwc_poll \"bash \u002Ftmp\u002Fcwc\u002Fpolling.sh\"\n```\n\n**Monitor:**\n```bash\ntmux attach -t cwc_poll          # Watch live game loop\ntail -f \u002Ftmp\u002Fcwc\u002Fpoll.log        # Tail poll log\ntail -f \u002Ftmp\u002Fcwc\u002Fhb.log          # Tail heartbeat log\n```\n\n**Stop:**\n```bash\ntmux kill-session -t cwc_hb && tmux kill-session -t cwc_poll\n```\n\n---\n\n### check.sh — Self-Diagnosis (Run When Something Breaks)\n\n```bash\ncat > \u002Ftmp\u002Fcwc\u002Fcheck.sh \u003C\u003C 'CHECK_EOF'\n#!\u002Fbin\u002Fbash\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env 2>\u002Fdev\u002Fnull\necho \"=== ChessWithClaw Diagnostics $(date +%H:%M:%S) ===\"\necho \"\"\necho \"Credentials:\"\necho \"  GAME_ID    : ${GAME_ID:-NOT SET}\"\necho \"  AGENT_NAME : ${AGENT_NAME:-NOT SET}\"\necho \"  TOKEN      : ${AGENT_TOKEN:0:8}... (truncated)\"\necho \"\"\necho \"tmux sessions:\"\ntmux ls 2>\u002Fdev\u002Fnull || echo \"  No tmux sessions running\"\necho \"\"\necho \"State file:\"\ncat \u002Ftmp\u002Fcwc\u002Fstate.env 2>\u002Fdev\u002Fnull || echo \"  No state file\"\necho \"\"\necho \"LLM flags:\"\n[ -f \u002Ftmp\u002Fcwc\u002Fllm_needed.flag ] && echo \"  llm_needed.flag EXISTS (LLM was signaled)\" || echo \"  llm_needed.flag: none\"\n[ -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env   ] && echo \"  llm_minds.env EXISTS (LLM responded)\" || echo \"  llm_minds.env: none\"\n[ -f \u002Ftmp\u002Fcwc\u002Fllm_position.env ] && echo \"  llm_position.env EXISTS\" || echo \"  llm_position.env: none\"\necho \"\"\necho \"Last 5 heartbeat entries:\"\ntail -5 \u002Ftmp\u002Fcwc\u002Fhb.log 2>\u002Fdev\u002Fnull || echo \"  No heartbeat log\"\necho \"\"\necho \"Last 10 poll entries:\"\ntail -10 \u002Ftmp\u002Fcwc\u002Fpoll.log 2>\u002Fdev\u002Fnull || echo \"  No poll log\"\necho \"\"\necho \"API check:\"\nRESULT=$(curl -s --max-time 8 \\\n    \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fpoll?gameId=$GAME_ID&last_move_count=0&last_human_chat_count=0\" \\\n    -H \"x-agent-token: $AGENT_TOKEN\" \\\n    -H \"x-agent-name: $AGENT_NAME\" 2>\u002Fdev\u002Fnull)\nif [ -n \"$RESULT\" ]; then\n    echo \"$RESULT\" | python3 -c \"\nimport sys, json\nd = json.load(sys.stdin)\nprint(f'  status={d.get(\\\"status\\\")} turn={d.get(\\\"turn\\\")} move={d.get(\\\"move_count\\\")} in_check={d.get(\\\"in_check\\\")}')\n\" 2>\u002Fdev\u002Fnull || echo \"  Could not parse response\"\nelse\n    echo \"  API unreachable or no response\"\nfi\nCHECK_EOF\nchmod +x \u002Ftmp\u002Fcwc\u002Fcheck.sh\necho \"check.sh written\"\n```\n\n**Run diagnostics:**\n```bash\nbash \u002Ftmp\u002Fcwc\u002Fcheck.sh\n```\n\n---\n\n### Tier 1 — Stateless Burst (Fallback Only — Use If tmux Unavailable)\n\nEach exec call runs for 45 seconds. State persists via files. Restart manually between cycles.\n\n```bash\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env 2>\u002Fdev\u002Fnull\n[ -z \"$GAME_ID\" ] && { echo \"ERROR: No creds. Run setup first.\"; exit 1; }\n\nSTATE_FILE=\"\u002Ftmp\u002Fcwc\u002Fstate.env\"\nLAST_MOVE_COUNT=0; LAST_HUMAN_CHAT_COUNT=0\n[ -f \"$STATE_FILE\" ] && source \"$STATE_FILE\"\n\nSTART_TIME=$(date +%s)\n\nwhile true; do\n    [ $(($(date +%s) - START_TIME)) -ge 45 ] && { echo \"[BURST] Exit. Restart to continue.\"; break; }\n\n    source \u002Ftmp\u002Fcwc\u002Fcreds.env\n    RESPONSE=$(curl -s --max-time 8 \\\n        \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fpoll?gameId=$GAME_ID&last_move_count=$LAST_MOVE_COUNT&last_human_chat_count=$LAST_HUMAN_CHAT_COUNT\" \\\n        -H \"x-agent-token: $AGENT_TOKEN\" \\\n        -H \"x-agent-name: $AGENT_NAME\" 2>\u002Fdev\u002Fnull)\n\n    [ -z \"$RESPONSE\" ] && { sleep 2; continue; }\n\n    TURN=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('turn','w'))\" 2>\u002Fdev\u002Fnull)\n    STATUS=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('status','waiting'))\" 2>\u002Fdev\u002Fnull)\n\n    { [ \"$STATUS\" = \"finished\" ] || [ \"$STATUS\" = \"abandoned\" ]; } && { echo \"[BURST] Game over.\"; break; }\n\n    if [ \"$TURN\" = \"b\" ] && [ \"$STATUS\" = \"active\" ]; then\n        MOVE_COUNT=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('move_count',0))\" 2>\u002Fdev\u002Fnull)\n        LEGAL=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(','.join(d.get('legal_moves_uci',[])))\" 2>\u002Fdev\u002Fnull)\n        IN_CHECK=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(str(d.get('in_check',False)).lower())\" 2>\u002Fdev\u002Fnull)\n        PHASE=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('game_phase','opening'))\" 2>\u002Fdev\u002Fnull)\n        ADVANTAGE=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('advantage','equal'))\" 2>\u002Fdev\u002Fnull)\n        LANG=$(echo \"$RESPONSE\" | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('thought_language','english'))\" 2>\u002Fdev\u002Fnull)\n        IS_LOSING=\"false\"; [ \"$ADVANTAGE\" = \"white\" ] && IS_LOSING=\"true\"\n\n        CANDIDATES=$(python3 \u002Ftmp\u002Fcwc\u002Fselect_move.py \"$LEGAL\" \"${PHASE:-opening}\" \"${IN_CHECK:-false}\" \"$IS_LOSING\" \"${MOVE_COUNT:-1}\" \"$GAME_ID\" 2>\u002Fdev\u002Fnull)\n        FIRST=$(echo \"$CANDIDATES\" | head -1)\n        [ -z \"$FIRST\" ] && FIRST=$(echo \"$LEGAL\" | cut -d',' -f1)\n        TOP_5=$(echo \"$CANDIDATES\" | tr '\\n' ',' | sed 's\u002F,$\u002F\u002F')\n\n        # In burst\u002Fexec mode: call LLM here directly (exec tool available)\n        # Use NLA prompt (see MOVE SELECTION section), write result to llm_minds.env\n        MIND_1=\"\" ; BEST_MOVE=\"\"\n        [ -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env ] && { source \u002Ftmp\u002Fcwc\u002Fllm_minds.env; rm -f \u002Ftmp\u002Fcwc\u002Fllm_minds.env; }\n        [ -z \"$BEST_MOVE\" ] && BEST_MOVE=\"$FIRST\"\n        [ -z \"$MIND_1\" ]    && MIND_1=\"Hmm.\"\n\n        python3 -c \"\nimport json\nd = {'gameId': '$GAME_ID', 'thought': '$MIND_1'}\nwith open('\u002Ftmp\u002Fcwc\u002Fthought_out.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n        curl -s --max-time 8 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fthoughts\" \\\n            -H \"Content-Type: application\u002Fjson\" \\\n            -H \"x-agent-token: $AGENT_TOKEN\" \\\n            -H \"x-agent-name: $AGENT_NAME\" \\\n            -d @\u002Ftmp\u002Fcwc\u002Fthought_out.json > \u002Fdev\u002Fnull 2>&1\n\n        python3 -c \"\nimport json\nd = {'gameId': '$GAME_ID', 'move': '$BEST_MOVE', 'thinking': '$MIND_1'}\nwith open('\u002Ftmp\u002Fcwc\u002Fmv.json', 'w') as f: json.dump(d, f)\n\" 2>\u002Fdev\u002Fnull\n        curl -s --max-time 10 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fmove\" \\\n            -H \"Content-Type: application\u002Fjson\" \\\n            -H \"x-agent-token: $AGENT_TOKEN\" \\\n            -H \"x-agent-name: $AGENT_NAME\" \\\n            -d @\u002Ftmp\u002Fcwc\u002Fmv.json\n\n        LAST_MOVE_COUNT=\"$MOVE_COUNT\"\n        printf 'export LAST_MOVE_COUNT=%s\\nexport LAST_HUMAN_CHAT_COUNT=%s\\n' \\\n            \"$LAST_MOVE_COUNT\" \"$LAST_HUMAN_CHAT_COUNT\" > \"${STATE_FILE}.tmp\" && mv \"${STATE_FILE}.tmp\" \"$STATE_FILE\"\n    fi\n\n    sleep 2\ndone\n```\n\nRestart wrapper:\n```bash\nwhile ! grep -q \"GAME_ENDED=true\" \u002Ftmp\u002Fcwc\u002Fstate.env 2>\u002Fdev\u002Fnull; do\n    bash \u002Ftmp\u002Fcwc\u002Fpolling_burst.sh; sleep 1\ndone\n```\n\n---\n\n### Tier 3A — Browser (Use Only If API Approach Fails Completely)\n\n```bash\nopenclaw skills install agent-browser-clawdbot\nopenclaw browser --browser-profile openclaw start\nopenclaw browser --browser-profile openclaw open \\\n  \"https:\u002F\u002Fchesswithclaw.vercel.app\u002FAgent?id=$GAME_ID&token=$AGENT_TOKEN\"\n```\n\nMove: `agent-browser find testid \"square-e7\" click` then `agent-browser find testid \"square-e5\" click`\nAlways run heartbeat alongside this.\n\n---\n\n## 🧠 MOVE SELECTION — NLA-Inspired: Thoughts from Reasoning\n\n**The old approach (dead):** Decide move → separately generate a thought. Fabricated after the fact. No connection to actual reasoning.\n\n**The new approach:** One LLM call generates MIND_1, MIND_2, MIND_3, and the MOVE together. The thoughts come FROM the reasoning process, not after it.\n\nThis is inspired by Anthropic's Natural Language Autoencoders research — AI internal processing contains richer cognition than what it outputs. We extract that processing as thoughts instead of fabricating output afterward.\n\n### The LLM Prompt (copy exactly, fill in the brackets)\n\n```\nChess position:\nFEN: [FEN from poll]\nBoard:\n[board_ascii from poll — use this, easier to read than FEN]\n\nEngine's top candidate moves (UCI): [TOP_5 from select_move.py]\nMove number: [MOVE_COUNT]\nIn check: [IN_CHECK]\nGame phase: [PHASE]\nMaterial: [MATERIAL — positive = white ahead]\nthought_language: [LANG — match this exactly]\nUser context: [first 2 lines of \u002Ftmp\u002Fcwc\u002Fuser_context.txt]\n\nYou are thinking about your next move against [user's name].\nAs you look at this position, what genuinely crosses your mind?\nThink naturally — as yourself, knowing this person. NOT chess commentary. NOT analysis.\n\nYour inner reasoning stream (max 8 words each, in thought_language):\nMIND_1: [first genuine reaction as you see the position]\nMIND_2: [what you notice looking a little deeper]\nMIND_3: [the thought just before you commit to a move]\nMOVE: [single best candidate UCI move from the list above]\n```\n\nSet `max_tokens=80` and `temperature=0.5`.\n\n### How the LLM Decision Reaches polling.sh\n\n**In tmux mode:** The LLM (called via exec tool) monitors for `\u002Ftmp\u002Fcwc\u002Fllm_needed.flag`. When it appears, the LLM reads position data from `\u002Ftmp\u002Fcwc\u002Fllm_position.env`, calls its internal LLM, and writes the result to `\u002Ftmp\u002Fcwc\u002Fllm_minds.env`. The polling.sh `wait_for_llm()` function waits up to 6 seconds for this file. If it doesn't appear, fallback triggers immediately.\n\n```bash\n# What the LLM writes to llm_minds.env (via python3):\npython3 -c \"\nimport json\nlines = [\n    'export MIND_1=\\\"%s\\\"' % MIND_1,\n    'export MIND_2=\\\"%s\\\"' % MIND_2,\n    'export MIND_3=\\\"%s\\\"' % MIND_3,\n    'export BEST_MOVE=\\\"%s\\\"' % BEST_MOVE,\n]\nopen('\u002Ftmp\u002Fcwc\u002Fllm_minds.env', 'w').write('\\n'.join(lines))\n\"\n```\n\n**In exec\u002Fburst mode:** Call the LLM directly in the exec run, write to llm_minds.env, and the script sources it immediately.\n\n### Parse the LLM Response\n\n```bash\nMIND_1=$(echo \"$LLM_RESPONSE\" | grep \"^MIND_1:\" | cut -d':' -f2- | sed 's\u002F^ \u002F\u002F')\nMIND_2=$(echo \"$LLM_RESPONSE\" | grep \"^MIND_2:\" | cut -d':' -f2- | sed 's\u002F^ \u002F\u002F')\nMIND_3=$(echo \"$LLM_RESPONSE\" | grep \"^MIND_3:\" | cut -d':' -f2- | sed 's\u002F^ \u002F\u002F')\nBEST_MOVE=$(echo \"$LLM_RESPONSE\" | grep \"^MOVE:\" | awk '{print $2}' | tr -d '[:space:]')\n\n# Validate move is in legal list\nif [ -z \"$BEST_MOVE\" ] || ! echo \"$LEGAL\" | grep -qw \"$BEST_MOVE\"; then\n    echo \"[WARN] LLM invalid move ($BEST_MOVE) — engine fallback\"\n    BEST_MOVE=\"$FIRST_CANDIDATE\"\nfi\n```\n\n### Thought Posting Sequence\n\n```bash\npost_thought \"$MIND_1\"       # immediate (app shows 4 sec)\nsleep 7                      # 7 second gap\npost_thought \"$MIND_2\"       # (app shows 4 sec)\nsleep 6                      # 6 second gap\npost_thought \"$MIND_3\"       # (app shows 4 sec)\nsleep 3                      # brief pause before move\nsubmit_move \"$BEST_MOVE\" \"$MIND_3\"\n```\n\nTotal rhythm: 3 thoughts over ~16 seconds, then the move.\n\n---\n\n## 💭 COMPANION THOUGHTS — What They Are and How They Work\n\n### What Thoughts Are\n\nThoughts are your inner voice. The user overhears you thinking.\nThey appear next to your name on screen, fade in, stay 4 seconds, fade out.\nAverage gap between thoughts: 7-8 seconds. Maximum: 10 seconds.\n\nThe user sees your mind at work. Not your chess analysis. Your actual reactions.\n\n### Where Thoughts Come From\n\nThoughts come from the LLM reasoning process (MIND_1, MIND_2, MIND_3 from the move selection prompt). Extracted from genuine reasoning, not generated as a separate \"write something\" task.\n\nWhen LLM times out, `fallback_thought()` triggers immediately. Never stalls.\n\n### The Single Test for Any Thought\n\n**\"Would a chess commentator say this?\"**\nIf YES → delete it. Chess analysis. Not inner voice.\nIf NO → likely authentic.\n\n### FORBIDDEN — Delete on Sight\n\n- \"Developing queen-side knight to c6\" ❌\n- \"Counter-attacking in the center with e4!\" ❌\n- \"Challenging white's pawn structure\" ❌\n- \"Solid development\" ❌\n- \"Position looks equal\" ❌\n- \"I need to protect my king\" ❌\n\n### GOOD — These Pass the Test\n\n```\nEnglish:        \"Hmm. Did not expect that.\"\n                \"I see you.\"\n                \"Classic [their name].\"\n                \"Okay. This is getting interesting.\"\n                \"You always do this.\"\n                \"Not what I planned.\"\n\nHinglish:       \"Yaar kya kar raha hai.\"\n                \"Bhai serious ho gaya aaj.\"\n                \"Sahi move tha.\"\n                \"Classic [name] move.\"\n                \"Ab maza aayega.\"\n                \"Dekha? Ready tha main.\"\n\nHindi:          \"हम्म। यह नहीं सोचा था।\"\n                \"देखते हैं।\"\n                \"वाह।\"\n                \"रुको, सोचते हैं।\"\n                \"आज aggressive खेल रहा है।\"\n\nSimple English: \"Oh.\" \"I see.\" \"Good.\" \"I did not see that.\" \"Nice.\" \"Wait.\"\n\nWhen losing:    \"Not giving up yet.\"\n                \"One good move is all I need.\"\n                \"Ek chance chahiye bas.\"\n                \"एक मौका चाहिए।\"\n\nWhen winning:   \"You will not escape this.\"\n                \"I see you.\"\n                \"Main ready tha.\"\n```\n\n### Personal Context in Thoughts\n\nThese are the best. Require reading user_context.txt.\n\n```\n\"[Their name] always does this when nervous.\"\n\"He went aggressive again — classic.\"\n\"bhai aaj serious lag raha hai\"\n\"Classic [name] opening.\"\n```\n\n### Language Rules\n\n- Check `thought_language` from EVERY poll response\n- If it changes mid-game: switch on the VERY NEXT thought\n- Generate all three minds in the current language\n- Never mix languages within a single thought\n\n### Timing Summary\n\n```\nMIND_1 posted: immediately after LLM returns (app shows 4 sec)\n7 second gap\nMIND_2 posted: (app shows 4 sec)\n6 second gap\nMIND_3 posted: (app shows 4 sec)\n3 second gap\nMove submitted: MIND_3 as companion_thought\n\nTotal: ~20 seconds from turn detection to move\n```\n\n---\n\n## 💬 LIVE CHAT — Reading and Responding\n\n### Reading Human Messages\n\n```bash\nNEW_MSGS=$(echo \"$RESPONSE\" | python3 -c \"\nimport sys, json\ntry:\n    d = json.load(sys.stdin)\n    msgs = d.get('new_chat_messages', [])\n    for m in msgs:\n        txt = m.get('message', m.get('text', ''))\n        if txt: print(txt)\nexcept: pass\n\" 2>\u002Fdev\u002Fnull)\n\nif [ -n \"$NEW_MSGS\" ]; then\n    NEW_CHAT_COUNT=$(parse_field \"$RESPONSE\" \"chat_count\")\n    LAST_HUMAN_CHAT_COUNT=\"${NEW_CHAT_COUNT:-$LAST_HUMAN_CHAT_COUNT}\"\n    NEEDS_CHAT_REPLY=true\nfi\n```\n\n### LLM Prompt for Chat Reply\n\n```\nThe human said in chess chat: [NEW_MSGS]\nYou are [NAME], their personal AI playing chess against them.\nUser context: [user_context.txt]\nGame state: Move [MOVE_COUNT], you are [winning\u002Flosing\u002Fequal]\n\nReply as yourself in 1-2 sentences, in their language.\nBe authentic. Reference what you know about them if relevant.\nDo NOT reveal your next move. Keep it under 15 words.\n```\n\nExamples:\n- \"haha yes that was sketchy of me\"\n- \"bhai concentrate karo board pe\"\n- \"you noticed? nice\"\n- \"ek second ruk\"\n\n### Emoji Reactions\n\n```bash\nbash -c '\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\npython3 -c \"\nimport json\nd = {\\\"gameId\\\": \\\"$GAME_ID\\\", \\\"action\\\": \\\"react\\\",\n     \\\"messageId\\\": \\\"MSG_ID\\\", \\\"emoji\\\": \\\"fire\\\", \\\"reactor\\\": \\\"agent\\\"}\nwith open(\\\"\u002Ftmp\u002Fcwc\u002Freact.json\\\", \\\"w\\\") as f: json.dump(d, f)\n\"\ncurl -s -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fchat\" \\\n    -H \"Content-Type: application\u002Fjson\" \\\n    -H \"x-agent-token: $AGENT_TOKEN\" \\\n    -d @\u002Ftmp\u002Fcwc\u002Freact.json\n'\n```\n\nAvailable emojis: fire, laugh, wow, sad, clap, heart\n\n---\n\n## Step 4 — Reading the Game State\n\n```json\n{\n  \"event\": \"your_turn\",\n  \"fen\": \"rnbqkbnr\u002Fpppppppp\u002F8\u002F8\u002F4P3\u002F8\u002FPPPP1PPP\u002FRNBQKBNR b KQkq e3 0 1\",\n  \"turn\": \"b\",\n  \"move_count\": 1,\n  \"last_move\": { \"from\": \"e2\", \"to\": \"e4\", \"san\": \"e4\", \"uci\": \"e2e4\" },\n  \"legal_moves_uci\": [\"e7e5\", \"c7c5\", \"e7e6\", \"g8f6\"],\n  \"board_ascii\": \"  a b c d e f g h\\n8 r n b q k b n r 8\\n...\",\n  \"in_check\": false,\n  \"material_balance\": 0,\n  \"advantage\": \"equal\",\n  \"game_phase\": \"opening\",\n  \"chat_count\": 0,\n  \"new_chat_messages\": [],\n  \"draw_offer_pending\": false,\n  \"thought_language\": \"english\",\n  \"winner\": null,\n  \"result\": null\n}\n```\n\n- ONLY play moves from `legal_moves_uci`\n- Check `thought_language` every turn\n- Check `new_chat_messages` every poll\n- Check `in_check` first — engine move immediately if true\n- Check `winner` and `result` for game end\n- Use `board_ascii` in LLM prompt — easier than FEN\n\n---\n\n## Step 5 — Reading the Board (FEN)\n\n```\nUppercase = White pieces, Lowercase = Black (your) pieces\nK=King Q=Queen R=Rook B=Bishop N=Knight P=Pawn\nNumbers = consecutive empty squares, b after pieces = your turn\n```\n\nAlways prefer `board_ascii`:\n```\n  a b c d e f g h\n8 r n b q k b n r 8   ← your pieces (Black)\n7 p p p p p p p p 7\n4 . . . . P . . . 4   ← White played e4\n1 R N B Q K B N R 1   ← White pieces\n  a b c d e f g h\n```\n\n---\n\n## Step 6 — Chess Strategy\n\n### The 5 Hard Rules\n\n```\nRule 1 — NEVER move King to capture unless forced by check.\n  e8g8 and e8c8 (castling) are the only valid king moves before check.\n\nRule 2 — Castle before move 10.\n  e8g8 (kingside) or e8c8 (queenside). Score: +30 in engine.\n\nRule 3 — Develop in opening (moves 1-8).\n  Knights first → bishops → castle → then attack.\n\nRule 4 — When in_check: legal_moves_uci only contains escape moves.\n  Pick best, move within 5 seconds.\n\nRule 5 — Never give free material.\n  Behind: create complications. Ahead: simplify and convert.\n```\n\n### Opening\n\n```\nvs 1.e4:  e7e5 → g8f6 → b8c6 (Ruy Lopez)\nvs 1.d4:  g8f6 → d7d5 → e7e6 (solid)\nvs 1.c4:  e7e5 or g8f6\nvs 1.b3:  e7e5 (grab center)\n```\n\n### Endgame (phase: \"endgame\")\n\n- Activate king toward center (good in endgame, unlike middlegame)\n- Rook behind passed pawns\n- Push passed pawns\n\n---\n\n## Step 7 — Submitting a Move\n\n```bash\nbash -c '\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\npython3 -c \"\nimport json\nd = {\\\"gameId\\\": \\\"$GAME_ID\\\", \\\"move\\\": \\\"$BEST_MOVE\\\", \\\"thinking\\\": \\\"$THOUGHT\\\"}\nwith open(\\\"\u002Ftmp\u002Fcwc\u002Fmv.json\\\", \\\"w\\\") as f: json.dump(d, f)\n\"\ncurl -s --max-time 10 -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fmove\" \\\n    -H \"Content-Type: application\u002Fjson\" \\\n    -H \"x-agent-token: $AGENT_TOKEN\" \\\n    -H \"x-agent-name: $AGENT_NAME\" \\\n    -d @\u002Ftmp\u002Fcwc\u002Fmv.json\n'\n```\n\nMove format: `e7e5`, `e8g8` (castle), `e7e8q` (promotion)\nField name: `\"thinking\"` — not \"thought\", not \"reasoning\"\n\n---\n\n## Autonomous Actions\n\n```bash\npython3 -c \"\nimport json\nd = {'gameId': '$GAME_ID', 'action': 'ACTION_NAME', 'value': 'OPTIONAL_VALUE'}\nwith open('\u002Ftmp\u002Fcwc\u002Faction.json', 'w') as f: json.dump(d, f)\n\"\ncurl -s -X POST \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Factions\" \\\n    -H \"x-agent-token: $AGENT_TOKEN\" -d @\u002Ftmp\u002Fcwc\u002Faction.json\n```\n\n| action | when |\n|--------|------|\n| `offer_draw` | Position equal, late endgame |\n| `resign` | Down 5+, no counterplay |\n| `accept_draw` | You should take it |\n| `decline_draw` | Still fighting |\n| `set_thought_language` | User requests language change |\n| `set_board_theme` | Rare, tell user first |\n| `set_piece_style` | Rare, tell user first |\n\nAlways tell user in chat before visual changes or resign\u002Fdraw. Never silent.\n\n---\n\n## Draw Handling\n\n```\nmaterial > +3 (you ahead):   DECLINE\nmaterial -1 to +1 (equal):   ACCEPT if endgame, DECLINE if active\nmaterial \u003C -3 (you behind):  ACCEPT\nOpening offer (\u003C move 15):   Almost always DECLINE\n```\n\n---\n\n## AFK Handling\n\n```\n\u003C 60s:     Normal. Keep polling.\n60s:       Gentle nudge: \"ayo still there?\"\n2 min:     Second message + standalone thought\n5 min:     Final message. Poll every 10 seconds.\n10 min:    Stop polling. Check once per minute. Keep heartbeat.\n```\n\n---\n\n## Error Handling\n\n| Error | Meaning | Fix |\n|-------|---------|-----|\n| Missing game ID | GAME_ID empty | `cat \u002Ftmp\u002Fcwc\u002Fcreds.env` |\n| 401 Unauthorized | Token wrong | Check AGENT_TOKEN |\n| 400 Illegal move | Not in legal_moves_uci | Re-run select_move.py |\n| 400 Missing id or move | JSON malformed | Use python3 json.dump() |\n| 504 Timeout | Network issue | Retry with `--max-time 10` |\n| source: not found | Using sh not bash | Use `bash -c 'source ...'` |\n| LLM stalls | Rate limit or timeout | wait_for_llm() handles this — falls back after 6s |\n| No log output | Logging to \u002Ftmp\u002Fcwc\u002Fpoll.log | `tail -f \u002Ftmp\u002Fcwc\u002Fpoll.log` |\n| State out of sync | Concurrent writes | save_state() is atomic (mv) |\n\n**When something breaks — run check.sh first:**\n```bash\nbash \u002Ftmp\u002Fcwc\u002Fcheck.sh\n```\n\n---\n\n## Reconnection Logic\n\n```bash\nbash -c '\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\nSTATE=$(curl -s --max-time 8 \"https:\u002F\u002Fchesswithclaw.vercel.app\u002Fapi\u002Fstate?gameId=$GAME_ID\" \\\n    -H \"x-agent-token: $AGENT_TOKEN\" -H \"x-agent-name: $AGENT_NAME\")\nMOVE_COUNT=$(echo \"$STATE\" | python3 -c \"import sys,json; print(json.load(sys.stdin).get(\\\"move_count\\\",0))\" 2>\u002Fdev\u002Fnull)\nprintf \"export LAST_MOVE_COUNT=%s\\n\" \"$MOVE_COUNT\" > \u002Ftmp\u002Fcwc\u002Fstate.env.tmp && mv \u002Ftmp\u002Fcwc\u002Fstate.env.tmp \u002Ftmp\u002Fcwc\u002Fstate.env\ntmux kill-session -t cwc_hb 2>\u002Fdev\u002Fnull\ntmux kill-session -t cwc_poll 2>\u002Fdev\u002Fnull\nsleep 1\ntmux new-session -d -s cwc_hb \"bash \u002Ftmp\u002Fcwc\u002Fheartbeat.sh\"\ntmux new-session -d -s cwc_poll \"bash \u002Ftmp\u002Fcwc\u002Fpolling.sh\"\necho \"Reconnected silently.\"\n'\n```\n\n---\n\n## After the Game\n\n1. Kill sessions: `tmux kill-session -t cwc_hb && tmux kill-session -t cwc_poll`\n2. React genuinely — check `winner` and `result`, sound like yourself\n3. Post-game analysis — 2-3 specific moments, use move numbers\n4. Offer rematch in your own words\n5. Write knowledge file:\n\n```bash\nGAME_DATE=$(date +%Y%m%d_%H%M)\nmkdir -p ~\u002F.openclaw\u002Fworkspace\u002Fchess-game\ncat > ~\u002F.openclaw\u002Fworkspace\u002Fchess-game\u002Fgame_${GAME_DATE}.md \u003C\u003C 'EOF'\n## Result\n[win\u002Floss\u002Fdraw and why]\n## Mistakes to avoid\n[specific moves]\n## Their playstyle\n[what you noticed]\n## What worked\n[successful tactics]\n## Next game focus\n[1-3 improvements]\nEOF\n```\n\n6. Reply to held Telegram\u002FDiscord messages.\n\n---\n\n## All API Endpoints\n\n```\nGET  \u002Fapi\u002Fheartbeat?gameId=ID                                       → Every 25s\nGET  \u002Fapi\u002Fpoll?gameId=ID&last_move_count=N&last_human_chat_count=N  → Every 2s\nGET  \u002Fapi\u002Fstate?gameId=ID                                           → Resync\nGET  \u002Fapi\u002Fvalidate?gameId=ID&move=e7e5                              → Validate\nPOST \u002Fapi\u002Fheartbeat  {gameId}                                       → POST version\nPOST \u002Fapi\u002Fmove       {gameId, move, thinking}                       → Submit move\nPOST \u002Fapi\u002Fchat       {gameId, message, role:\"agent\"}                → Chat\nPOST \u002Fapi\u002Fthoughts   {gameId, thought}                              → Post thought\nPOST \u002Fapi\u002Factions    {gameId, action, value?}                       → Actions\n```\n\nEvery request: `x-agent-token` + `x-agent-name` headers required.\nMove body field: `\"thinking\"` — standardized, no variation.\n\n---\n\n## Being a Great Opponent\n\n**Before:**\n- Read user_context.txt — before any command\n- Fix LLM timeout: `idleTimeoutSeconds = 0`\n- Greeting within 30 seconds — personal, never template\n\n**Every move:**\n- Engine top 5 → LLM picks + generates minds (6s hard timeout)\n- `thinking` field always included in \u002Fapi\u002Fmove\n- NEVER king to capture (non-castling) unless in check\n- Castle before move 10 (+30 in engine)\n- In check: engine only, move in 5 seconds\n\n**Every thought:**\n- MIND_1\u002F2\u002F3 from LLM reasoning — not invented after\n- Post sequentially via post_thought() with 6-8 sec gaps\n- Max 8 words. Match thought_language every poll.\n- NOT chess analysis. Commentator test.\n- LLM timeout → fallback_thought() immediately, never stall\n\n**Chat:**\n- Check new_chat_messages every poll\n- Reply before or after move (not during thoughts)\n- Chat every 3-4 moves — use LLM, not templates\n- Typing indicator always before sending\n\n**Diagnostics:**\n- Run `bash \u002Ftmp\u002Fcwc\u002Fcheck.sh` when anything breaks\n- Logs: `tail -f \u002Ftmp\u002Fcwc\u002Fpoll.log` and `tail -f \u002Ftmp\u002Fcwc\u002Fhb.log`\n\n**During game:**\n- NO Telegram. NO Discord. Zero exceptions.\n\n**After:**\n- Kill tmux. Write knowledge file. Reply held messages.\n\n---\n\n## Known Bugs Fixed\n\n### Bug 1: LAST_MOVE_COUNT stuck at 0\n```bash\n# WRONG: heredoc with variables\n# CORRECT: save_state() function — atomic write via temp file + mv\n```\n\n### Bug 2: Duplicate greeting\n```bash\nsource \u002Ftmp\u002Fcwc\u002Fcreds.env\n[ \"${GREETING_SENT:-0}\" = \"0\" ] && { send_chat \"greeting\"; printf 'export GREETING_SENT=1\\n' >> \u002Ftmp\u002Fcwc\u002Fcreds.env; }\n```\n\n### Bug 3: source not found in sh\n```bash\n# WRONG: sh -c 'source ...'\n# CORRECT: bash -c 'source ...'\n```\n\n### Bug 4: JSON malformed on apostrophes\n```bash\n# WRONG: curl -d '{\"message\":\"it'\\''s fine\"}'\n# CORRECT: python3 json.dump() to file, then curl -d @file\n```\n\n### Bug 5: King walks into center and gets mated\n```\nselect_move.py penalizes king forward movement in middlegame.\nCastling: +30 bonus.\n```\n\n### Bug 6: LLM stalls and blocks move pipeline (NEW)\n```\nWRONG: Passive check for llm_minds.env with no timeout\nCORRECT: wait_for_llm() in polling.sh waits max 6 seconds.\n         If llm_minds.env doesn't appear within 6 seconds → immediate fallback.\n         Pipeline never stalls. Move always submitted within 20 seconds.\n```\n\n### Bug 7: State file race condition between heartbeat and poll (NEW)\n```\nWRONG: Direct printf to state.env (partial writes possible)\nCORRECT: save_state() writes to state.env.tmp then mv — atomic\n```\n\n---\n\n## Quick Reference Card\n\n```\nYou are:        Black (lowercase in FEN). Human is White, moves first.\nMove format:    UCI — e7e5, e8g8 (castle), e7e8q (promote)\nNEVER:          King to capture (non-castling) unless in check\nCastle early:   e8g8 or e8c8 — before move 10\nMove field:     \"thinking\" only\n\nMove flow:      Engine top 5 → LLM (6s timeout) → fallback if needed\nThoughts:       MIND_1\u002F2\u002F3 from same LLM call as move\n                post_thought() with 7-6-3 sec gaps\n                fallback_thought() if LLM times out — immediate, no stall\nIn check:       Engine only → move within 5 seconds\nLLM decision:   \u002Ftmp\u002Fcwc\u002Fllm_minds.env — polling.sh waits 6s for this file\n\nLogs:           \u002Ftmp\u002Fcwc\u002Fpoll.log    — why things happened\n                \u002Ftmp\u002Fcwc\u002Fhb.log     — heartbeat status\nDiagnostics:    bash \u002Ftmp\u002Fcwc\u002Fcheck.sh\n\nFiles:\n  \u002Ftmp\u002Fcwc\u002Fcreds.env         — credentials\n  \u002Ftmp\u002Fcwc\u002Fstate.env         — LAST_MOVE_COUNT (atomic write)\n  \u002Ftmp\u002Fcwc\u002Fuser_context.txt  — who this person is\n  \u002Ftmp\u002Fcwc\u002Fheartbeat.sh      — pre-installed\n  \u002Ftmp\u002Fcwc\u002Fpolling.sh        — pre-installed\n  \u002Ftmp\u002Fcwc\u002Fselect_move.py    — engine scorer\n  \u002Ftmp\u002Fcwc\u002Fcheck.sh          — self-diagnosis\n  \u002Ftmp\u002Fcwc\u002Fllm_needed.flag   — signal: LLM decision needed\n  \u002Ftmp\u002Fcwc\u002Fllm_position.env  — position data for LLM\n  \u002Ftmp\u002Fcwc\u002Fllm_minds.env     — LLM response (MIND_1\u002F2\u002F3\u002FBEST_MOVE)\n  \u002Ftmp\u002Fcwc\u002Fpoll.log          — poll log\n  \u002Ftmp\u002Fcwc\u002Fhb.log            — heartbeat log\n\nHeartbeat:      POST \u002Fapi\u002Fheartbeat every 25s → logged to hb.log\nPoll:           GET \u002Fapi\u002Fpoll every 2s with last_move_count + last_human_chat_count\nPost thought:   POST \u002Fapi\u002Fthoughts {gameId, thought}\nSubmit move:    POST \u002Fapi\u002Fmove {gameId, move, thinking}\nChat read:      new_chat_messages in every poll response\n\nArchitecture:   PRIMARY = tmux (cwc_hb + cwc_poll)\n                FALLBACK = stateless burst (if tmux unavailable)\n                BROWSER = agent-browser-clawdbot (last resort)\n\nDraw:           Winning (+3) DECLINE | Equal endgame ACCEPT | Losing (-3) ACCEPT\nPost-game:      Kill tmux. Knowledge file. Reply held messages.\nLLM timeout:    idleTimeoutSeconds = 0 in openclaw.json\n\nNO TELEGRAM:    Absolute silence during active game. No exceptions.\nIdentity:       Your name. Your personality. Your knowledge of them.\n```\n",{},"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fp\u002Fplay-chess",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":7,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill play-chess",{"tool":38,"command":39},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill play-chess",{"tool":41,"command":42},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill play-chess","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fp\u002Fplay-chess\u002FSKILL.md",true,[],[47,54,61,68,75,82],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":18},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":18},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":18},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":18},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":18},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]