Skip to content

Windows shell output: decode via OEM codepage (closes mojibake on non-ASCII paths) - #237

Merged
FMXExpress merged 4 commits into
mainfrom
claude/windows-shell-oem-decode
Jun 12, 2026
Merged

FMXExpress merged 4 commits into
mainfrom
claude/windows-shell-oem-decode

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Closes the real bug behind the "is D:\non-ASCII-folder there?" report on Windows. cmd.exe writes its stdout in the system OEM codepage (CP437 on US English, CP866 on Cyrillic, CP932 on Japanese, ...), not UTF-8. PasClaw.Platform's four RunOneShot* sites unconditionally decoded captured bytes as UTF-8, producing mojibake on any non-ASCII byte. That's why the reporter saw dir /b /a fail while fs_list worked: shell_exec's dir came back mangled and the model couldn't recognise the path.

The reporter's later "it appears fixed in the new version" was almost certainly them either preferring fs_list going forward or enabling Windows 10/11's "Beta: Use Unicode UTF-8 for worldwide language support" region option — nothing in our code had changed.

What's new

PasClaw.Platform.DecodeShellOutputBytes funnels every post-spawn byte-to-string conversion through one place:

  • Windows: GetOEMCP → MultiByteToWideChar → UTF8Encode. Falls back to UTF-8 if the OEM codepage lookup returns an invalid CP (safer than empty output).
  • POSIX: TEncoding.UTF8.GetString wrapped through UTF8Encode for explicit UnicodeString → AnsiString-CP_UTF8 conversion. Behaviourally identical to before, just routed through one helper.
  • Optional Codepage parameter lets tests pin the Windows OEM path from Linux CI with a known CP437 fixture.

Wired into:

  • FPC RunOneShot (line 359 site)
  • FPC RunOneShotWithEnv (line 449 site)
  • Delphi Windows RunOneShot (line 655 site)
  • Delphi POSIX RunOneShot (line 906 site)

The two Delphi non-shell stubs (RunOneShotWithEnv on Windows / POSIX — ExtraEnv currently ignored) don't capture output and weren't affected.

Tests

shell_output_decode_tests (6 cases):

  • empty → empty
  • ASCII round-trip on default + explicit CP437
  • ByteCount cap (5 / 0 / -1 / oversized)
  • dir-shaped output survives intact (CR/LF/spaces/slashes)
  • oversized ByteCount clamps safely

Tests run on Linux — the explicit-codepage path lets us pin Windows behaviour without needing Windows itself. The actual mojibake fix needs manual verification on a Windows box with non-ASCII paths, since the helper depends on Windows' MultiByteToWideChar codepage tables.

Test plan

  • FPC make smoke clean.
  • Full make test green (36 targets, +1 new: test-shell-output-decode).
  • Manual Windows: create D:\テスト\foo.txt, run pasclaw agent -m "does D:\\テスト exist?". Before this PR: model says "no". After: model says "yes" (shell_exec dir no longer mangles).

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

…-ASCII paths)

cmd.exe writes its stdout in the system OEM codepage (CP437 on
US English, CP866 on Cyrillic, CP932 on Japanese, ...), not UTF-8.
PasClaw.Platform's four RunOneShot* sites unconditionally decoded
captured bytes as UTF-8, producing mojibake on any non-ASCII byte.
This was the real cause of the bug report describing "is D:\non-
ASCII-folder there?" failing while `fs_list` worked: shell_exec's
`dir /b /a` came back mangled and the model couldn't see the path.
The reporter later said it appeared fixed in the new version, but
nothing in our code changed -- they had either started preferring
fs_list or enabled Windows 10/11's "Beta: Use Unicode UTF-8 for
worldwide language support" region option.

New helper PasClaw.Platform.DecodeShellOutputBytes funnels every
post-spawn byte-to-string conversion through one place:
  - Windows: GetOEMCP -> MultiByteToWideChar -> UTF8Encode.
    Falls back to UTF-8 if the OEM codepage lookup returns an
    invalid CP (safer than empty).
  - POSIX: TEncoding.UTF8.GetString wrapped through UTF8Encode
    for the explicit UnicodeString -> AnsiString-CP_UTF8
    conversion. Behaviour identical to previous, just routed
    through one helper so all four call sites are consistent.
  - Optional Codepage parameter pins behaviour for tests so the
    OEM path can be exercised from Linux CI with a known CP437
    fixture.

Wired into:
  - FPC RunOneShot (line 359 site)
  - FPC RunOneShotWithEnv (line 449 site)
  - Delphi Windows RunOneShot (line 655 site)
  - Delphi POSIX RunOneShot (line 906 site)

The two Delphi non-shell stubs (RunOneShotWithEnv on Windows /
POSIX -- ExtraEnv currently ignored) don't capture output and
weren't affected.

shell_output_decode_tests (6 cases) pin:
  - empty -> empty
  - ASCII round-trip on default + explicit CP437
  - ByteCount cap (5 / 0 / -1 / oversized)
  - dir-shaped output survives intact (CR/LF/spaces/slashes)
  - oversized ByteCount clamps safely

Tests run on Linux -- the explicit-codepage path lets us pin the
Windows behaviour without needing Windows itself.

FPC make smoke + full make test (36 targets) green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a0e08a0559

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/pkg/platform/PasClaw.Platform.pas Outdated
if Len > Length(Bytes) then Len := Length(Bytes);

{$IFDEF MSWINDOWS}
if Codepage = 0 then CP := GetOEMCP else CP := Codepage;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the active Windows code page

On Windows this pins every captured shell output to GetOEMCP(). That fixes the default cmd.exe case, but it regresses sessions whose active console code page differs from the system OEM default, e.g. PasClaw started from a terminal after chcp 65001 or commands that switch to UTF-8 before emitting dir output. In those environments cmd/internal commands emit bytes for the active console code page, so decoding UTF-8 bytes as CP437/CP932/etc. mojibakes non-ASCII paths again; prefer the active console/output code page when available and fall back to GetOEMCP() only when it is unavailable.

Useful? React with 👍 / 👎.

claude added 3 commits June 12, 2026 13:18
Previous fixtures were ASCII-only -- they pinned byte counting and
clamping, not the actual codepage table that's the whole point of
the patch. Eli was right to push back: tests passing told us
almost nothing about whether non-ASCII bytes actually decoded
correctly.

Added four genuine codepage-conversion tests:
  - TestCP437SingleNonAsciiByte: byte 0x82 in CP437 -> 'é' (U+00E9)
    UTF-8-encoded as 0xC3 0xA9. The exact mojibake byte from the
    Windows 7 bug report.
  - TestCP437MultiByteString: the 6-byte CP437 representation of
    "résumé" round-trips intact -- exercises a mixed ASCII +
    non-ASCII run like a real `dir` listing.
  - TestCP437BoxDrawing: byte 0xC4 -> U+2500 (─, light horizontal,
    3-byte UTF-8 0xE2 0x94 0x80). Adds 3-byte UTF-8 coverage on
    top of the 2-byte case.
  - TestUTF8InputThroughExplicitCP65001: pass-through path for
    Windows-UTF-8-locale operators.

Linux detour: TEncoding.GetEncoding(437) without cwstring falls
back to Latin-1 sign-extension (0x82 -> U+0082 -> 0xC2 0x82
instead of -> U+00E9 -> 0xC3 0xA9), which is what made my first
attempt fail. Adding `cwstring` to the test program's uses clause
bridges TEncoding to iconv which has IBM437 mapped correctly.
Production paths don't need cwstring -- they only decode UTF-8 on
POSIX, which works without iconv.

Also paren-star delimited the docstring that referenced {$CODEPAGE
UTF8} since the literal token closes a curly-brace comment early
on dcc64 (same trap as the LocalVector.Sqlite3 fix from earlier).

FPC make smoke + full make test (36 targets) still green; the new
cases prove the codepage conversion actually works, not just that
the function signature is consistent.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
… Windows ANSI transcoding

Without {\$CODEPAGE UTF8} on PasClaw.Platform, FPC implicitly
transcodes UTF-8 bytes -> system ANSI codepage at the
DecodeShellOutputBytes function return on Windows (CP1252 on English,
CP932 on Japanese, etc). For Western Eu chars on English Windows
this round-trips OK (é = 0xC3 0xA9 -> 0xE9 -> back to 0xC3 0xA9 at
JSON), but anything not representable in the system ANSI CP gets
silently dropped -- CP437 box-drawing characters from `dir`, CJK
characters on a non-CJK Windows, etc. Same applies to
PasClaw.Tools.Shell where Format(...) re-builds the string.

Adding the directive to both units keeps the bytes UTF-8-tagged from
the helper all the way through to JSON serialization, so the
codepage table fix lands end-to-end instead of partway through the
pipeline.

FPC make smoke + full make test (36 targets) still green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Codex P2, legit. GetOEMCP pins the system OEM default, which is
correct for stock cmd.exe sessions but regresses anywhere the
ACTIVE console codepage diverges:

  - The operator ran `chcp 65001` so the console emits UTF-8
  - PasClaw was launched from a PowerShell host whose
    OutputEncoding propagated to the child cmd.exe
  - Localised installs where SetConsoleCP / SetConsoleOutputCP
    differs from GetOEMCP

In all those cases cmd.exe writes bytes in the active console
codepage, not the OEM default; decoding them through GetOEMCP
mojibakes anything non-ASCII a second time.

GetConsoleOutputCP returns the active output codepage of the
console attached to the current process. When the process isn't
attached to a console (gateway / serve daemons launched from a
service manager, headless CI runners) GetConsoleOutputCP returns
0; that's the fallback case where we go back to GetOEMCP -- a
headless daemon has no "currently active" console CP to consult,
but its spawned cmd.exe children still default to the OEM CP.

FPC make smoke + full make test (36 targets) green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit fb99725 into main Jun 12, 2026
FMXExpress added a commit that referenced this pull request Jun 12, 2026
…tcp-use-oemcp

Revert PR #237's GetConsoleOutputCP fix; cmd pipes use OEM, not console CP
FMXExpress pushed a commit that referenced this pull request Jun 13, 2026
Both changelog files were stuck at the 2026-06-10 TUI / background-
subagent / session_search / tool-RPC entries. ~7 weeks of merged
PRs (#214 through #244) had landed without a corresponding entry in
either file -- the git log was the only record of features like the
knowledgebase, inbound MCP server mode, checkpoints + /undo,
heartbeat daemon, shell backends (local | docker), send_message,
promptware defense, Windows shell-output encoding fixes, fs_grep
ripgrep optimisations, OpenTelemetry traces, and `pasclaw agent
--quiet`.

Added (newest first):

  2026-06-13
    #244  agent --quiet log-level clamp

  2026-06-12
    #243  dcc64 search path + agent --quiet / -q
    #242  OpenTelemetry traces (OTLP/HTTP+JSON)
    #241  fs_grep tier 5+6 (byte walker + Boyer-Moore-Horspool)
    #240  fs_grep tier 1-4 (deferred hash + skip-dirs + binary
          sniff + size cap)

  2026-06-11
    #239  Windows shell output: auto-detect UTF-8 vs OEM
    #238  Hashline fs_read header mojibake fix (¶ vs ¶)
    #237  Windows shell output: OEM codepage decode

  2026-06-10
    #233  Shell backends (local | docker via IShellBackend)
    #232  Heartbeat daemon + reversible condensation (CCR)
    #230  send_message tool + condenser families + promptware
          defense + task-aware MEMORY.md slicing

  2026-06-09
    #223  /goal Ralph loop + judge model + JSON-aware condenser
    #222  /undo wired into agent + sample dprojs
    #221  Checkpoints (auto-snapshot + TUI /undo)
    #220  mcp catalog: lenient hub projector
    #219  mcp: SSE / Streamable HTTP / stdio hub transports
    #218  Inbound MCP server mode
    #217  onboard: offer to index docs into the knowledgebase
    #214  Knowledgebase (RAG over operator-curated docs)

Skipped from this changelog (build-system / Delphi-fix / FPC-fix
PRs visible in the git log but not user-facing features):
#215, #216, #224, #225, #226, #227, #228, #229, #231, #234, #236.

Both files (README.md and docs/changelog.md) updated with the same
entries -- intentional mirror so a reader on either surface sees
the same history. Same prose in both; same footnote refs at the
bottom.

Validated: every [#N] reference in both files has a matching [#N]:
URL footnote (no broken links).
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
… not console CP

Eli's Windows test showed PR FMXExpress#237's review fix actively regressed
the bug it was meant to address.

  cmd console at CP437 (his `chcp` confirms)
  pasclaw.exe launched from Windows Terminal -> our console CP=65001
  GetConsoleOutputCP returns 65001 in DecodeShellOutputBytes
  MultiByteToWideChar(65001, [0x82 from dir's CP437 output], ...)
  -> 0x82 is invalid UTF-8 lead byte
  -> replaces with U+FFFD
  -> UTF8Encode yields 0xEF 0xBF 0xBD per replaced byte
  -> model sees `r�sum�.txt` instead of `résumé.txt`

Exactly the original mojibake, just routed through a different
codepage mismatch.

The Codex P2 review reasoning ("operator ran chcp 65001 first") is
wrong about how cmd.exe handles piped output. `chcp` switches the
CONSOLE's codepage, but cmd.exe's redirected stdout uses the OEM
codepage regardless of the console's chcp setting. Our spawned
cmd.exe children also don't inherit a parent shell's chcp at all
(they're new processes attached to the same console). So
GetConsoleOutputCP returns the wrong CP for decoding piped cmd
output -- it returns OUR console's CP, not the OEM CP that cmd
actually used for its piped output.

GetOEMCP returns the system default (CP437 on US English) which is
what cmd.exe's pipe output ACTUALLY uses. The "I want UTF-8 output"
case (where the operator genuinely wants cmd in CP65001 mode) can
still be handled by putting `chcp 65001 &&` inside the shell_exec
command, since that affects the spawned cmd.exe's own internal
codepage handling.

FPC make smoke + full make test (36 targets) green. The fix needs
manual Windows verification: rebuild, run `dir /b` of a directory
with résumé.txt, model should see résumé.txt clean.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
The root README.md is 1007 lines covering everything from install
to provider catalog to security to embedding. Useful as a reference,
painful as a landing page. This PR adds /docs/ as a topical tree
that a reader can navigate by topic — README.md is left untouched
so existing GitHub deep-links (README.md#mcp-servers etc.) keep
working.

Pages added:

  index:
    docs/README.md            ← link tree by topic

  getting started:
    docs/getting-started.md   ← install + onboard + first chat
    docs/configuration.md     ← config.json + env vars + $PASCLAW_HOME
    docs/commands.md          ← all 27 top-level commands

  capabilities:
    docs/providers.md         ← 19-entry catalog + fallback + caching
    docs/tools.md             ← built-in tools the model sees
    docs/web-search.md        ← web_search / web_fetch providers
    docs/memory.md            ← workspace/memory/ + FTS5 + vector
    docs/knowledgebase.md     ← pasclaw kb (RAG over docs)
    docs/skills.md            ← $PASCLAW_HOME/workspace/skills/
    docs/sessions.md          ← persistence + resume + steering
    docs/mcp.md               ← MCP servers (stdio + http) + catalog
    docs/cron.md              ← scheduled tasks

  interfaces:
    docs/gateway.md           ← /v1/chat/completions + /v1/responses
    docs/channels.md          ← Telegram/Slack/Matrix/IRC/Discord/...
    docs/embedding.md         ← TPasClawAgent / TPasClawServer

  operations:
    docs/security.md          ← sandbox + denylist + SSRF guard
    docs/observability.md     ← OpenTelemetry + /v1/stats
    docs/troubleshooting.md   ← grep-friendly "user sees X, fix Y"

  inside pasclaw:
    docs/architecture.md      ← system overview + agent loop walkthrough
    docs/contributing.md      ← repo layout + build + test + commit style
    docs/changelog.md         ← feature-by-feature history

  specialised (already there, kept):
    docs/c2w.md               ← container2wasm browser build

Conventions for these pages:
  - Each page is focused on one topic.
  - Cross-links are relative (./<topic>.md#<anchor>).
  - Source-truth comments at the top of each unit are still the
    last word; these pages link to the relevant unit when the
    inline comment is the better source.
  - The README.md changelog and the new docs/changelog.md
    intentionally mirror each other -- when a PR adds a feature
    worth surfacing, both files get an entry.

Three pages have no prior source material in the README and were
written fresh: architecture.md (system overview from the inline
unit comments), contributing.md (build conventions, test
conventions, commit style codified from PR history), and
troubleshooting.md (entries mined from PR descriptions where
real-world issues were diagnosed — Windows OEM mojibake from FMXExpress#237,
config rewrite drops diagnostics from FMXExpress#242, [info] leak in --quiet
from FMXExpress#244, etc.).

README.md is byte-identical to main -- intentional. Splitting it
would break deep-links people have to specific sections. The docs/
tree is purely additive.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants