Skip to content

fix(runners): make 5.1 able to read the runners, and to refuse them truthfully - #66

Merged
PhysShell merged 2 commits into
mainfrom
claude/runner-shell-contract
Aug 19, 2026
Merged

PhysShell merged 2 commits into
mainfrom
claude/runner-shell-contract

Conversation

@PhysShell

Copy link
Copy Markdown
Owner

Closes #64.

Что было

Три раннера были pwsh-only по случайности, а не по объявлению. Они несли не-ASCII символы и не имели BOM, поэтому Windows PowerShell 5.1 читал их в системной ANSI-кодировке и умирал на синтаксической ошибке внутри слова, которому не повезло содержать байт выше 127. Человеку, открывшему старую консоль Windows, сообщали, что honouring — синтаксическое преступление.

файл было не-ASCII байт стало
Run-Audit.ps1 67 0
Run-Infersharp.ps1 14 0
Run-Roslyn.ps1 6 0

Всё это была проза: длинные тире, один знак параграфа, одно многоточие, одна средняя точка.

Контракт — намеренно НЕ «раннеры работают под 5.1»

Это другая и гораздо большая задача. Контракт такой:

5.1 способен ПРОЧИТАТЬ файл и сказать о нём правду.

Обе половины несущие. ASCII — то, что делает файл читаемым в любой однобайтовой кодировке. #Requires -Version 7 — то, на что движок затем реагирует, отказывая до единой инструкции тела. Без первого второе недостижимо; без второго первое лишь переносит отказ в место поменьше честное.

Человек, открывший старую консоль, заслуживает хотя бы ошибку, относящуюся к реальности.

Одна правка потребовала осторожности

- $env:PYTHONUTF8 = "1"   # report.py prints '>=' / '·' — crashes on a cp1251 console
+ $env:PYTHONUTF8 = "1"   # report.py prints '>=' and U+00B7 MIDDLE DOT - both crash a cp1251 console

Здесь · цитировался как символ, который печатает report.py. Тупая замена на дефис исказила бы смысл комментария, поэтому символ назван, а не подменён.

Почему не BOM

BOM тоже заставил бы 5.1 декодировать правильно — и намеренно не является решением: он оставляет файл не-ASCII и ставит корректность в зависимость от трёх байт, которые любой редактор может уронить. Набор отвергает BOM отдельной проверкой.

Новый тест — отдельным файлом

scripts/tests/Test-RunnerShellContract.ps1, а не глубже в Test-LineTolPolicy.ps1. Работает на обеих редакциях, потому что редакции проверяют разные половины.

Везде: байты ASCII (читаются именно как БАЙТЫ — чтение как текста и есть тот шаг, который прячет дефект, ведь любая предполагаемая кодировка выдаёт какую-то строку), нет BOM, #Requires -Version 7 присутствует, файл парсится.

Дополнительно под 5.1: каждый раннер запускается с -Out, указывающим на несуществующий каталог, и проверяется, что exit-код ненулевой, что сообщение называет версию, а не слово из комментария, и что каталог по-прежнему не существует — это и есть доказательство, что тело не выполнялось.

Под pwsh раннеры только парсятся, никогда не запускаются: они управляют worktree, WSL и MSBuild. Вместо запуска проверяется, что comment-based help по-прежнему резолвится — именно это сломалось бы, если бы #Requires оторвал его от скрипта.

Скип, который надо было убрать

Test-LineTolPolicy.ps1 терял structural-проверки Run-Audit.ps1 под 5.1 и громко об этом сообщал:

Windows PowerShell 5.1: Run-Audit.ps1 structural checks did not run - the runner is pwsh-only (23 non-ASCII chars, pre-existing) and 5.1 cannot parse it

Этот скип существовал ровно из-за #64. Оставить его значило бы позволить обходному пути пережить то, что он обходил. Снят; проверки идут на всех редакциях.

Как проверено

  • 19 проверок проходят под pwsh 7.4.6
  • Test-LineTolPolicy.ps1: 45 проверок, 0 skipped
  • 5 vacuity-проб, 5/5 кусаются: вернуть не-ASCII байт, удалить требование версии, добавить BOM, сломать синтаксис, оторвать help
  • actionlint чист, Python-sweep (18 наборов) зелёный

Честно о границе: леg под Windows PowerShell 5.1 не может быть выполнена в этом контейнере — здесь нет Windows. Она покрыта только CI. Это ограничение названо, а не замазано: именно эта половина контракта и есть предмет #64.

CI

Две job'ы, обе windows-latest: pwsh и powershell (5.1). Linux не добавлен намеренно — дефект именно в декодировании Windows 5.1, и никакой Linux-раннер его не воспроизводит. Разделены, а не сведены в матрицу, по той же причине, что и linetol-policy-ps51: shell: не принимает выражение.

Тип изменения

  • fix — исправление дефекта
  • test / ci / docs

Чеклист

  • изменение покрыто тестом, тест проверен на непустоту (5 проб)
  • AGENTS.md документирует контракт и запрещает «починку» через BOM
  • коммит в conventional-commit стиле

Generated by Claude Code

…ruthfully

The three runners were pwsh-only by ACCIDENT rather than by declaration. They
carried non-ASCII characters and no BOM, so Windows PowerShell 5.1 decoded them
in the system ANSI codepage and died on a syntax error inside whatever word
happened to contain a byte above 127. Someone opening an old Windows console was
told that `honouring` was a syntax crime.

The contract this fixes is deliberately NOT "the runners work under 5.1" - that
is a different and much larger task. It is:

    5.1 can READ the file, and says the true thing about it.

Both halves are load-bearing. ASCII-only is what makes the file readable under
any single-byte codepage; `#Requires -Version 7` is what the engine then acts on,
refusing before a single statement of the body runs. Without the first the second
is unreachable, and without the second the first only moves the failure somewhere
less honest.

  Run-Audit.ps1       67 non-ASCII bytes -> 0
  Run-Infersharp.ps1  14                 -> 0
  Run-Roslyn.ps1       6                 -> 0

All of it was prose: em dashes, one section sign, one ellipsis, one middle dot.
The middle dot was quoting the character `report.py` prints, so replacing it
would have changed what the comment says; it is named as U+00B7 instead.

A BOM would also make 5.1 decode correctly and is deliberately not the fix - it
leaves the file non-ASCII and makes correctness depend on three bytes any editor
may drop. The suite rejects one.

`scripts/tests/Test-RunnerShellContract.ps1` is new and runs on BOTH editions,
because the two editions can check different halves. Everywhere: bytes are ASCII
(read as BYTES - reading as text is the step that hides the defect, since any
assumed encoding yields SOME string), no BOM, `#Requires -Version 7` present, and
the file parses. Under 5.1 additionally: each runner is invoked with an -Out
directory that does not exist, and the checks are that it exits non-zero, that
the message names the version rather than a word in a comment, and that the
directory STILL does not exist - which is the evidence the body never ran. Under
pwsh the runners are only parsed, never invoked; they drive worktrees, WSL and
MSBuild. What pwsh checks instead is that comment-based help still resolves,
which is what would break if `#Requires` detached it.

Test-LineTolPolicy.ps1 loses its Desktop skip. That skip existed only because of
this defect - it announced that the Run-Audit.ps1 structural checks "did not run"
under 5.1 - so leaving it would have made a workaround outlive the thing it was
working around.

CI gains two Windows jobs, pwsh and Windows PowerShell 5.1. Windows only: the
defect is 5.1 decoding, and no Linux runner reproduces it. Split rather than
matrixed for the same reason as linetol-policy-ps51 - `shell:` accepts no
expression.

Verified: 19 checks pass under pwsh 7.4.6, the LineTol suite reports 45 checks
and 0 skipped, and 5 probes confirm each new check bites - reintroducing a
non-ASCII byte, deleting the requirement, adding a BOM, breaking the syntax, and
detaching the help. The 5.1 leg cannot run in this container and is covered by CI
alone; that is stated rather than glossed. actionlint clean, Python sweep green.

Closes #64

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016Lmcv3X9PoELp8CGDfNc9m
@coderabbitai

coderabbitai Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 76a85403-4ddb-4f2b-af15-6de6c45bca3c

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

The contract worked on the first CI run. Windows PowerShell 5.1 read Run-Audit.ps1
and refused it for the true reason:

    The script 'Run-Audit.ps1' cannot be run because it contained a "#requires"
    statement for Windows PowerShell 7.0.

The suite failed anyway, at the invocation itself. That refusal arrives on
STDERR, and 5.1 turns any stderr write by a native executable into a terminating
NativeCommandError while $ErrorActionPreference is 'Stop' - so the script died on
line 109 without reaching a single assertion. The check was killed by its own
subject at the exact moment that subject started behaving correctly.

$ErrorActionPreference drops to Continue around the call and is restored in a
finally, and the exit code is captured immediately rather than read later, where
an intervening call could clobber $LASTEXITCODE.

pwsh does not exhibit this, which is the point of running the leg at all: the
only reason this was found is that the suite really executes under 5.1 instead of
asserting about it from 7.

Refs #64

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016Lmcv3X9PoELp8CGDfNc9m
@PhysShell
PhysShell marked this pull request as ready for review August 19, 2026 02:28
@PhysShell
PhysShell merged commit d0b0dbd into main Aug 19, 2026
8 checks passed
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