Windows Execution Bugs: cp1252 Encoding Crashes, Parallel Run Collisions, and CLI Detection
`# skill-creator: description optimisation fails or silently mis-scores on Windows
The trigger-evaluation scripts behind skill-creator's Description Optimization
step (scripts/run_eval.py, scripts/run_loop.py, scripts/improve_description.py)
cannot run on Windows as shipped. Worse, two of the defects are not Windows-specific
and do not crash. They turn failed or contaminated runs into plausible-looking
scores, so the optimiser can pick a "best" description from noise.
Five defects, each reproduced and fixed below. A consolidated patch is at the end.
Environment
| OS | Windows 11 Home (10.0.26200) |
| Python | 3.14.3 (python.org build; locale encoding cp1252) |
| Claude Code | 2.1.183 via npm (%APPDATA%\npm\claude.cmd); 2.1.280 bundled with Claude Desktop |
| skill-creator | from the anthropic-skills plugin 1.0.0 shipped with Claude Desktop |
| Invocation | python -m scripts.run_loop --eval-set ... --skill-path ... --model <id> |
Summary
| # | Defect | Platform | Failure mode |
|---|---|---|---|
| 1 | A failed claude -p run is scored as "did not trigger" |
all | Silent: wrong scores |
| 2 | Parallel workers see each other's temporary skill copies | all | Silent: rates depressed at random |
| 3 | File I/O uses the locale encoding (cp1252) |
Windows | Crash, and silent text corruption |
| 4 | select.select() on a subprocess pipe |
Windows | Crash on every query |
| 5 | Popen(["claude", ...]) cannot find npm's claude.cmd |
Windows | Crash on every query |
Defects 4 and 5 turn into silent wrong scores rather than crashes because of defect 1. Fixing 1 first makes every other failure loud.
1. Failed runs are scored as "did not trigger" (all platforms)
Symptom. With an expired Claude Code login, run_eval.py exits 0 and reports
results. Every should_trigger: false query passes, and every
should_trigger: true query fails:
should_trigger=False triggered 0/1 pass=True
should_trigger=True triggered 0/1 pass=FalseEvery candidate description then scores about 50%, and run_loop.py goes on to
"improve" against that signal.
Root cause. Two places turn failure into False:
run_single_querynever inspects the stream for errors. An auth failure arrives as an assistant message with"error": "authentication_failed", followed by aresultevent with"is_error": true. Note that the result'ssubtypeis still"success", so checkingsubtypeis not enough. The function falls through and returnstriggered, which isFalse.In
run_eval,except ExceptionappendsFalsefor any worker that raised:except Exception as e: print(f"Warning: query failed: {e}", file=sys.stderr) query_triggers[query].append(False)
Reproduce. Let the CLI's OAuth token expire, or pass a --model the installed
CLI does not support, then run run_eval.py on any eval set. It exits 0 with
scores. The two errors observed were:
API Error: 401 OAuth access token has expired. Re-authenticate to continue.
API Error: 400 Claude Code 2.1.183 does not support this model; version 2.1.280 or newer is required.Fix. Raise on assistant events carrying error and on result events with
is_error. Leave failed runs out of the rate instead of counting them as False,
and refuse to score if more than 10% of runs failed or any query has no valid run.
With that change, the expired-token case aborts:
RuntimeError: 2 of 2 runs failed and 2 queries have no valid run - refusing to score.
First failure: claude -p failed (authentication_failed): Failed to authenticate. API Error: 401 ...Also worth adding: a preflight in run_loop.py, one claude -p call with the
chosen --model before any evaluation, would catch both errors above in seconds
rather than after a batch.
2. Parallel workers see each other's temporary skills (all platforms)
Symptom. Trigger rates are depressed at random, more so with more workers.
Root cause. Every worker writes its temporary command,
<skill>-skill-<uuid>.md, into the same <project_root>/.claude/commands/ and
runs claude -p with cwd=project_root. With --num-workers 10, each session's
skill list holds up to ten copies of the skill under different names, all with the
same description. Detection only counts the worker's own name:
if clean_name in accumulated_json:
return TrueSo when Claude picks a sibling's copy, which is equally correct, the run scores as "did not trigger".
Evidence. While run_eval.py ran in a project that a Claude Code session also
had open, that session's skill list showed two temporary copies at the same moment,
verify-mutation-skill-082e76a9 and verify-mutation-skill-33e6c8ce. The
temporary files are visible to every session reading that project, not just the
worker's own. (I observed the overlap directly; I did not measure how much it moves
the rates.)
Fix. Give each run a private project directory containing only its own
temporary command. Keep the real project reachable with --add-dir, and remove the
directory afterwards.
private_root = Path(tempfile.mkdtemp(prefix="trigger-eval-"))
project_commands_dir = private_root / ".claude" / "commands"
...
cmd = [..., "--add-dir", str(project_root)]
process = subprocess.Popen(cmd, ..., cwd=str(private_root), ...)
...
finally:
shutil.rmtree(private_root, ignore_errors=True)This also stops temporary skills from appearing in any interactive session that has the real project open.
3. Locale-encoded file I/O: crash and silent corruption (Windows)
Symptom (crash). run_loop.py dies after the first evaluation round, and that
round's results are lost:
File "scripts/run_loop.py", line 151, in run_loop
live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name))
UnicodeEncodeError: 'charmap' codec can't encode character '\u2713' in position 13191Symptom (silent, and worse). With no error at all:
- Reading a UTF-8 SKILL.md whose description contains an em dash gives
'a \xe2\u20ac\u201d b'(a — b) instead of'a — b'. The description is evaluated, and sent to the improver, as garbled text. - Writing the temporary command file encodes
—as the single cp1252 byte0x97, which is not valid UTF-8. Claude Code then reads a corrupted description.
Root cause. Path.read_text(), Path.write_text() and open() default to the
locale encoding, which is cp1252 on most Windows installs. There are 20 such calls
in scripts/ with no encoding=:
aggregate_benchmark.py:90, 120, 142, 377, 383
generate_report.py:314, 319
improve_description.py:189, 208, 211
quick_validate.py:64
run_eval.py:68, 272
run_loop.py:151, 261, 278, 313, 317, 321
utils.py:9Reproduce.
p.write_bytes('description: a \u2014 b'.encode('utf-8'))
ascii(p.read_text()) # 'description: a \xe2\u20ac\u201d b' under cp1252Fix. Pass encoding="utf-8" at all 20 sites. As a workaround, running with
PYTHONUTF8=1 (Python UTF-8 mode) fixes every site at once without code changes.
That is how the runs below were completed.
4. select.select() on a subprocess pipe (Windows)
Symptom. Every query fails immediately. Because of defect 1, each failure is then scored as "did not trigger".
Root cause. run_single_query polls stdout with:
ready, _, _ = select.select([process.stdout], [], [], 1.0)On Windows, select() accepts only sockets:
OSError: [WinError 10093] Either the application has not called WSAStartup, or WSAStartup failedFix. Read the pipe on a daemon thread and hand chunks over through a
queue.Queue, keeping the one-second poll for the timeout. This works on every
platform:
chunks = queue.Queue()
def _pump():
for raw in iter(lambda: process.stdout.read1(8192), b""):
chunks.put(raw)
chunks.put(None)
threading.Thread(target=_pump, daemon=True).start()
while time.time() - start_time < timeout:
try:
chunk = chunks.get(timeout=1.0)
except queue.Empty:
continue
if chunk is None:
break
buffer += chunk.decode("utf-8", errors="replace")5. claude is not found by subprocess (Windows)
Symptom. FileNotFoundError from both run_eval.py and improve_description.py.
Root cause. npm installs the CLI as shims (claude, claude.cmd,
claude.ps1) that wrap node_modules/@anthropic-ai/claude-code/bin/claude.exe.
subprocess.Popen(["claude", ...]) without shell=True resolves only .exe, so it
finds nothing. shutil.which("claude") does return claude.CMD, but running a
.cmd goes through cmd.exe. That would mangle %, &, ^ and quotes in
arbitrary query text, which run_eval.py passes as an argument.
Fix. Call the native executable, and let an environment variable override it:
cmd = [os.environ.get("CLAUDE_BIN", "claude"), "-p", ...]A more automatic option is to resolve the .cmd shim to the claude.exe beside it
when running on Windows.
Related. The optimiser should measure the Claude Code version the user
actually uses. On this machine the npm CLI (2.1.183) was older than the build
bundled with Claude Desktop (2.1.280), and only the bundled build supports the
current model. The bundled executable lives under
%APPDATA%\Claude\claude-code\<version>\claude.exe; with the MSIX build it is
virtualised to %LOCALAPPDATA%\Packages\Claude_<id>\LocalCache\Roaming\Claude\....
Pointing CLAUDE_BIN at it measured the right version without touching the user's
install. The docs should mention this.
Verification
With all five fixes applied, and PYTHONUTF8=1 standing in for the encoding fix:
| Check | Result |
|---|---|
| Smoke test, expired login | aborts with RuntimeError ... refusing to score (previously: exit 0 with scores) |
| Smoke test, working login | should-trigger 2/2, near-miss 0/2 |
Full run_loop.py, 20 queries (12 train / 8 held out), 3 runs each |
completes; 60/60 correct, 0 failed runs |
run_eval.py of a second description on the same set |
60/60 correct, 0 failed runs, 130 s with 10 workers |
| Leftover temporary files after runs | none, in the project or in the private directories |
Minor
run_loop.pyprints the held-out set's time as0.0s, because train and test are evaluated in one batch and the whole duration is credited to train. The runs are real (each held-out query showsruns: 3inresults.json); only the timing line misleads.
Patch
The fixes for defects 1, 2, 4 and 5, as applied and verified. Defect 3 was worked
around with PYTHONUTF8=1 and is not in this diff; its fix is the 20
encoding="utf-8" additions listed above. run_loop.py is unchanged.
--- a/scripts/run_eval.py
+++ b/scripts/run_eval.py
@@ -8,9 +8,12 @@
import argparse
import json
import os
-import select
+import queue
+import shutil
import subprocess
import sys
+import tempfile
+import threading
import time
import uuid
from concurrent.futures import ProcessPoolExecutor, as_completed
@@ -50,7 +53,13 @@
"""
unique_id = uuid.uuid4().hex[:8]
clean_name = f"{skill_name}-skill-{unique_id}"
- project_commands_dir = Path(project_root) / ".claude" / "commands"
+ # [patch] A private project per run. With every parallel worker writing its
+ # copy into the one shared project, each session saw ~num_workers copies of
+ # the skill under different names; picking another worker's copy scored as
+ # "did not trigger" and depressed every rate at random. The real project is
+ # still reachable through --add-dir.
+ private_root = Path(tempfile.mkdtemp(prefix="trigger-eval-"))
+ project_commands_dir = private_root / ".claude" / "commands"
command_file = project_commands_dir / f"{clean_name}.md"
try:
@@ -68,11 +77,14 @@
command_file.write_text(command_content)
cmd = [
- "claude",
+ # [windows patch] Popen cannot find npm's claude.cmd shim; call the
+ # native executable it wraps. CLAUDE_BIN overrides.
+ os.environ.get("CLAUDE_BIN", "claude"),
"-p", query,
"--output-format", "stream-json",
"--verbose",
"--include-partial-messages",
+ "--add-dir", str(project_root),
]
if model:
cmd.extend(["--model", model])
@@ -86,7 +98,7 @@
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
- cwd=project_root,
+ cwd=str(private_root),
env=env,
)
@@ -97,20 +109,24 @@
pending_tool_name = None
accumulated_json = ""
+ # [windows patch] select() only accepts sockets on Windows, so read the
+ # pipe on a thread and hand chunks over through a queue instead.
+ chunks = queue.Queue()
+
+ def _pump():
+ for raw in iter(lambda: process.stdout.read1(8192), b""):
+ chunks.put(raw)
+ chunks.put(None)
+
+ threading.Thread(target=_pump, daemon=True).start()
+
try:
while time.time() - start_time < timeout:
- if process.poll() is not None:
- remaining = process.stdout.read()
- if remaining:
- buffer += remaining.decode("utf-8", errors="replace")
- break
-
- ready, _, _ = select.select([process.stdout], [], [], 1.0)
- if not ready:
+ try:
+ chunk = chunks.get(timeout=1.0)
+ except queue.Empty:
continue
-
- chunk = os.read(process.stdout.fileno(), 8192)
- if not chunk:
+ if chunk is None:
break
buffer += chunk.decode("utf-8", errors="replace")
@@ -153,6 +169,17 @@
if se_type == "message_stop":
return False
+ # [patch] A run that failed - expired login, rate limit,
+ # API error - must not be scored as "did not trigger". Unguarded,
+ # an expired OAuth token made every query score False: every
+ # negative "passed", every positive "failed", and the loop
+ # would have optimised against noise.
+ elif event.get("type") == "assistant" and event.get("error"):
+ text = "".join(c.get("text", "") for c in event.get("message", {}).get("content", []))
+ raise RuntimeError(f"claude -p failed ({event['error']}): {text[:200]}")
+ elif event.get("type") == "result" and event.get("is_error"):
+ raise RuntimeError(f"claude -p failed: {str(event.get('result'))[:200]}")
+
# Fallback: full assistant message
elif event.get("type") == "assistant":
message = event.get("message", {})
@@ -177,8 +204,7 @@
return triggered
finally:
- if command_file.exists():
- command_file.unlink()
+ shutil.rmtree(private_root, ignore_errors=True)
def run_eval(
@@ -212,6 +238,7 @@
query_triggers: dict[str, list[bool]] = {}
query_items: dict[str, dict] = {}
+ failures: list[str] = []
for future in as_completed(future_to_info):
item, _ = future_to_info[future]
query = item["query"]
@@ -221,8 +248,21 @@
try:
query_triggers[query].append(future.result())
except Exception as e:
+ # [patch] A run that crashed tells us nothing about triggering.
+ # Recording it as False scored every broken run as "did not
+ # trigger", which silently rewards descriptions for failures.
print(f"Warning: query failed: {e}", file=sys.stderr)
- query_triggers[query].append(False)
+ failures.append(str(e))
+
+ # [patch] A few transient failures are tolerable - they are left out of the
+ # rate. More than that, or a query with no valid runs, and the numbers
+ # mean nothing: stop rather than report them.
+ total_runs = sum(len(t) for t in query_triggers.values()) + len(failures)
+ empty = [q for q, t in query_triggers.items() if not t]
+ if empty or len(failures) > 0.1 * total_runs:
+ raise RuntimeError(
+ f"{len(failures)} of {total_runs} runs failed and {len(empty)} queries have no "
+ f"valid run - refusing to score. First failure: {failures[0] if failures else '-'}")
for query, triggers in query_triggers.items():
item = query_items[query]
--- a/scripts/improve_description.py
+++ b/scripts/improve_description.py
@@ -23,7 +23,8 @@
Prompt goes over stdin (not argv) because it embeds the full SKILL.md
body and can easily exceed comfortable argv length.
"""
- cmd = ["claude", "-p", "--output-format", "text"]
+ # [windows patch] see run_eval.py - call the native executable.
+ cmd = [os.environ.get("CLAUDE_BIN", "claude"), "-p", "--output-format", "text"]
if model:
cmd.extend(["--model", model])
`
Source: anthropics/claude-plugins-official