loopx icon indicating copy to clipboard operation
loopx copied to clipboard

[Bug]: four shipped stdio hosts still decode their UTF-8 transport with the host locale codec, so non-ASCII paths and diffs crash or are silently rewritten on a cp936 host

Open JasonBuildAI opened this issue 1 month ago • 0 comments

Preflight

  • [x] I searched existing issues and discussions for this behavior.
  • [x] This report is not an unpatched security vulnerability.
  • [x] The report and attachments contain no credentials or private/internal material.

Issue origin

Observed or reproduced in a real environment

LoopX version or commit

main at 873e8fee8 on native Windows 11 (locale.getpreferredencoding(False) = cp936), CPython 3.12 from uv.

Host or runtime surface

Not host-specific: the shipped runtime process itself. Each entry point below is started by LoopX (or by the documented workflow) with a UTF-8 stdio transport.

LoopX area

Control plane (goals, todos, quota, scheduler, registry, runtime)

Problem

LoopX pins UTF-8 for every text-mode file and subprocess read/write, and its own shipped entry points already pin their process streams: #6119 (CLI), #6168 (bundled extension providers), #6230 (presentation view validator), #6166 (Claude Code hooks) and #6399 (DSH Turn host adapter). docs/reference/source-cli-entrypoint.md states that contract explicitly: the bootstrap "pins the process's own stdin/stdout/stderr to UTF-8, matching the codec LoopX already pins for text-mode file and subprocess I/O".

Four shipped entry points were missed by that sweep. Each is launched over a stdio transport that its own caller writes and reads as UTF-8, and none of them pins its streams:

Entry point LoopX caller Caller's transport
loopx/control_plane/coordination/shadow_lock_host.py loopx/control_plane/coordination/shadow_drain_files.ts child.stdin.write(JSON.stringify(paths)) (UTF-8 bytes), createInterface({input: child.stdout})
loopx/control_plane/coordination/nokv_jsonl_helper.py loopx/control_plane/coordination/nokv_jsonl_transport.ts ([python, <helper file>]) and the live qualification probe examples/nokv-authority-store/live-qualification.ts ([python, "-I", <helper file>]) child.stdin.write(line), JSON.parse(line.toString("utf8"))
This helper is the one host in the list that is executed as a file, not as a module, so any fix must keep both of its
launch modes working: the transport's [python, <file>] and the qualification probe's [python, "-I", <file>].

| loopx/capabilities/explore/research_snapshot_host.py | loopx/control_plane/capabilities/explore_research_terminal.ts | child.stdin.write(JSON.stringify(...)), readline over the UTF-8 stdout | | loopx/capabilities/public_safe_outbound/scan_cli.py | the documented git diff --cached \| ... --diff boundary gate (capability README) | the caller pipes UTF-8 diff bytes |

On a host whose ANSI code page is not UTF-8 - zh-CN Windows (cp936), the common case for this project's users - these processes decode their caller's UTF-8 request with gbk. The result depends on the payload bytes, and both outcomes are wrong:

  1. Crash. A UTF-8 multi-byte sequence that is not a valid gbk pair raises UnicodeDecodeError before any request validation. This is the failure mode for an ordinary Chinese name such as 黄江南. The caller sees only a generic unavailable-host result (research_graph_snapshot_unavailable, shadow_lock_host_unavailable) or, for scan_cli, a raw traceback.
  2. Silent wrong result. When every byte happens to form valid gbk pairs - the case for an ordinary name such as 测试 - the decode succeeds and produces a different string with no error at all. gbk is a two-byte codec, so a lead byte swallows the byte after it; a Windows path separator is simply consumed. The process then operates on a path the caller never named and reports success.

The trigger is the default configuration, not an edge case: LoopX resolves its runtime root and registry under Path.home() (~/.loopx/registry.json, ~/.codex/...), so on a Chinese Windows account the transport already carries C:\Users\<non-ASCII name>\.... The class is also the maintainers' own Priority 0 lane: docs/development/contributor-tasks.md Lane A anchors on #4941 and states that "a reproduced defect from one of them outranks any internal polish". The same defect has been reported and fixed surface by surface since 2026-09-23 (#4155, #6116, #6167, #6228, #6233, #6352, #6395, #6405).

Minimal reproduction

In a source checkout (uv sync --extra test), run this against main at 873e8fee8. PYTHONIOENCODING=gbk makes the locale-codec behavior deterministic on any host; on a zh-CN Windows host it is the default. The two payload names are the two byte shapes above.

import json, os, subprocess, sys, tempfile
from pathlib import Path

CRASH = "\u9ec4\u6c5f\u5357"  # UTF-8 bytes are not all valid gbk pairs
QUIET = "\u6d4b\u8bd5"        # every gbk pair is valid -> decodes to different text


def run(args, payload, label, codec="gbk"):
    env = {**os.environ, "PYTHONIOENCODING": codec, "PYTHONUTF8": "0"}
    p = subprocess.run([sys.executable, *args], env=env, input=payload,
                       capture_output=True, timeout=120)
    print(label, codec, "rc:", p.returncode, "stdout:", p.stdout[:90],
          "stderr:", p.stderr.decode("gbk", "replace").strip().splitlines()[-1:])
    return p


base = Path(tempfile.mkdtemp())
quiet_root = base / ("Users-" + QUIET)
(quiet_root / "runtime").mkdir(parents=True)

# 1. shadow_lock_host with a non-ASCII lock path whose bytes decode cleanly
lock = quiet_root / "runtime" / "authority.lock"
run(["-m", "loopx.control_plane.coordination.shadow_lock_host"],
    (json.dumps([str(lock)], ensure_ascii=False) + "\nrelease\n").encode("utf-8"),
    "shadow_lock_host")
print("  requested dir:", quiet_root.name,
      "| dirs now under base:", sorted(p.name for p in base.iterdir()))

# 2. research_snapshot_host with a non-ASCII runtime_root
run(["-m", "loopx.capabilities.explore.research_snapshot_host"],
    (json.dumps({"runtime_root": str(quiet_root), "goal_id": "g1", "harness": {},
                 "agent_id": "a1", "todos": []}, ensure_ascii=False) + "\n").encode("utf-8"),
    "research_snapshot_host")

# 3. scan_cli --diff, the documented boundary gate
run(["-m", "loopx.capabilities.public_safe_outbound.scan_cli", "--diff", "--format", "text"],
    ("diff --git a/docs/x.md b/docs/x.md\n+++ b/docs/x.md\n+ note " + QUIET + "\n").encode(),
    "scan_cli --diff")

# 4. crash shape: the same three entries fed a path whose bytes are not valid gbk pairs
crash_root = base / ("CUsers-" + CRASH)
(crash_root / "runtime").mkdir(parents=True)
run(["-m", "loopx.control_plane.coordination.shadow_lock_host"],
    (json.dumps([str(crash_root / "runtime" / "a.lock")], ensure_ascii=False) + "\nrelease\n").encode(),
    "shadow_lock_host")
run(["-m", "loopx.capabilities.explore.research_snapshot_host"],
    (json.dumps({"runtime_root": str(crash_root), "goal_id": "g1", "harness": {},
                 "agent_id": "a1", "todos": []}, ensure_ascii=False) + "\n").encode(),
    "research_snapshot_host")
run(["-m", "loopx.control_plane.coordination.nokv_jsonl_helper"],
    (json.dumps({"request_id": "r1", "operation": "open", "config": {
        "root_id": "demo", "workbench_root": str(crash_root),
        "routing": {"kind": "static", "endpoint": "127.0.0.1:1", "logical_shard_id": "0",
                    "object_namespace_id": "0", "placement_generation": 1, "owner_epoch": 1},
        "object_store": {"kind": "memory"}}}, ensure_ascii=False) + "\n").encode(),
    "nokv_jsonl_helper")
run(["-m", "loopx.capabilities.public_safe_outbound.scan_cli", "--diff", "--format", "text"],
    ("diff --git a/docs/x.md b/docs/x.md\n+++ b/docs/x.md\n+ note " + CRASH + "\n").encode(),
    "scan_cli --diff")

Observed with main at 873e8fee8 (abridged; the full run is reproducible from the script above):

shadow_lock_host     gbk rc: 0 stdout: b'held\r\nreleased\r\n'
  requested dir: Users-测试 | dirs now under base: ['Users-娴嬭瘯', 'Users-测试']
research_snapshot_host gbk rc: 0 stdout: b'{"schema_version": "research_graph_snapshot_v0", ...'
  requested dir contents after the run: []          # untouched
  dirs now under base: ['Users-娴嬭瘯', 'Users-测试']  # the lock/state went here
scan_cli --diff      gbk rc: 0 stdout: b'PASS: public-safe\r\n'
  gbk   stdin.read() last line: '+ note 娴嬭瘯'
  utf-8 stdin.read() last line: '+ note 测试'
shadow_lock_host     gbk rc: 1 stderr: OSError: [WinError 123] ... : '\\\\?\\...\\CUsers-<mojibake>\runtime'
research_snapshot_host gbk rc: 1 stdout: b'{"schema_version": "research_graph_snapshot_v0", "error": "UnicodeDecodeError"}'
nokv_jsonl_helper    gbk rc: 1 stderr: UnicodeDecodeError: 'gbk' codec can't decode byte 0x97 in position 138
scan_cli --diff      gbk rc: 1 stderr: UnicodeDecodeError: 'gbk' codec can't decode byte 0x97 in position 66

The first three lines are the silent mode: shadow_lock_host reports held/released while the lock lands on a directory named Users-娴嬭瘯, not the requested Users-测试; research_snapshot_host returns a complete, plausible research_graph_snapshot_v0 computed against a different (previously nonexistent) runtime root; scan_cli --diff reports PASS: public-safe having scanned a re-encoded copy of the diff. Under UTF-8 stdio the same commands address the requested paths.

Expected behavior

Each of these shipped entries pins its own stdin/stdout/stderr to UTF-8 with the existing loopx/entrypoint.py::pin_utf8_stdio helper, exactly like the CLI and the other shipped entry points above, so a non-ASCII path or diff behaves identically on a cp936 host and on a UTF-8 host.

Actual behavior

On a non-UTF-8 host the same UTF-8 request is decoded with gbk. It either raises UnicodeDecodeError (three of the four entry points) or is accepted as a different string, in which case the entry point locks, reads or scans something the caller never named and exits 0. The caller cannot distinguish the two from a genuine unavailable host.

Sanitized diagnostics

main: 873e8fee8 (source checkout, native Windows 11, CPython 3.12)
python -c "import locale; print(locale.getpreferredencoding(False))"   # cp936
# PYTHONIOENCODING=gbk PYTHONUTF8=0 reproduces on any host (see Minimal reproduction);
# a zh-CN Windows console produces the same output without setting anything.

Additional context

  • Same defect class and fix shape as the merged #6119, #6168, #6230, #6166 and #6399. The canonical helper already exists, so no new guard family is introduced.
  • Affected users: LoopX operators on non-UTF-8 Windows (zh-CN, zh-TW, ja, ko) whose runtime root, registry, workbench root or checkout lives under a non-ASCII path - the default for a Chinese Windows account, because the runtime root resolves under Path.home().
  • Unlike the earlier reports in this family, two of the four surfaces fail silently: they lock, read or scan a different path and report success, so a caller cannot attribute the failure and may act on a wrong result.
  • A fix is in progress and will be proposed as a PR that pins these four entries and adds a focused regression test that runs each real entry point under a non-UTF-8 locale.

JasonBuildAI avatar Oct 14 '26 22:10 JasonBuildAI