From cebc94a94d5437cef68f804cc35efb534d950b05 Mon Sep 17 00:00:00 2001 From: OthmanAdi <78882424+OthmanAdi@users.noreply.github.com> Date: Sat, 1 Aug 2026 22:05:59 +0200 Subject: [PATCH] fix: give non-ASCII PowerShell scripts a UTF-8 BOM so Windows PowerShell can parse them Windows PowerShell 5.1, still the default shell on Windows and the interpreter every dispatcher reaches for first, reads a .ps1 as ANSI unless the file carries a UTF-8 BOM. The UTF-8 encoding of an em dash is E2 80 94, and CP1252 maps 0x94 to a closing curly quote, so the character opens a string literal that never closes. An arrow does the same through 0x92. The result is a parse error before the first statement runs, and every dispatcher wraps its PowerShell call in fallbacks that swallow it, so the script silently does nothing. Eight shipped scripts failed to parse: the Cursor plan injection hook, both .kiro asset scripts, the Arabic check-complete, and check-complete plus init-session for both Chinese variants. The last of those means a Windows user of either Chinese variant could not create a plan at all. Every tracked .ps1 holding a byte above 0x7F now carries a BOM. Pure ASCII files deliberately do not, because the dual-shipped script parity tests compare them byte for byte between locations. The guard asserts the invariant in plain Python so it runs everywhere, and where a real powershell.exe exists it additionally asks the interpreter to parse all 81 tracked scripts through ParseFile, which catches any encoding trap rather than only this one. Both halves were verified to fail against the pre-fix files. --- .cursor/hooks/pre-tool-use.ps1 | 2 +- .cursor/hooks/stop.ps1 | 2 +- .cursor/hooks/user-prompt-submit.ps1 | 77 +++++++++- .github/hooks/scripts/agent-stop.ps1 | 2 +- .github/hooks/scripts/post-tool-use.ps1 | 2 +- .github/hooks/scripts/pre-tool-use.ps1 | 2 +- .github/hooks/scripts/session-start.ps1 | 2 +- .../assets/scripts/bootstrap.ps1 | 2 +- .../assets/scripts/check-complete.ps1 | 2 +- .../scripts/check-complete.ps1 | 2 +- .../scripts/init-session.ps1 | 2 +- .../scripts/check-complete.ps1 | 2 +- .../scripts/init-session.ps1 | 2 +- .../scripts/check-complete.ps1 | 2 +- .../scripts/init-session.ps1 | 2 +- .../scripts/check-complete.ps1 | 2 +- .../scripts/init-session.ps1 | 2 +- .../scripts/check-complete.ps1 | 2 +- .../scripts/init-session.ps1 | 2 +- tests/test_ps1_windows_encoding.py | 140 ++++++++++++++++++ 20 files changed, 230 insertions(+), 23 deletions(-) create mode 100644 tests/test_ps1_windows_encoding.py diff --git a/.cursor/hooks/pre-tool-use.ps1 b/.cursor/hooks/pre-tool-use.ps1 index f2df592..d773e58 100644 --- a/.cursor/hooks/pre-tool-use.ps1 +++ b/.cursor/hooks/pre-tool-use.ps1 @@ -1,4 +1,4 @@ -# planning-with-files: Pre-tool-use hook for Cursor (PowerShell) +# planning-with-files: Pre-tool-use hook for Cursor (PowerShell) # Reads the first 30 lines of task_plan.md to keep goals in context. # Returns {"decision": "allow"} — this hook never blocks tools. diff --git a/.cursor/hooks/stop.ps1 b/.cursor/hooks/stop.ps1 index 625ff8e..0f3935a 100644 --- a/.cursor/hooks/stop.ps1 +++ b/.cursor/hooks/stop.ps1 @@ -1,4 +1,4 @@ -# planning-with-files: Stop hook for Cursor (PowerShell) +# planning-with-files: Stop hook for Cursor (PowerShell) # Checks if all phases in task_plan.md are complete. # Returns followup_message to auto-continue if phases are incomplete. # Always exits 0 — uses JSON stdout for control. diff --git a/.cursor/hooks/user-prompt-submit.ps1 b/.cursor/hooks/user-prompt-submit.ps1 index cc81081..7ce26d5 100644 --- a/.cursor/hooks/user-prompt-submit.ps1 +++ b/.cursor/hooks/user-prompt-submit.ps1 @@ -1,14 +1,81 @@ -# planning-with-files: User prompt submit hook for Cursor (PowerShell) +# planning-with-files: User prompt submit hook for Cursor (PowerShell) # Injects plan context on every user message. # Critical for session recovery after /clear — dumps actual content, not just advice. -if (Test-Path "task_plan.md") { +# --- PWF_PLAN_ROOT: absolute plan-root binding (issue #212). --- +# A thread whose cwd is a shared PARENT of the real project can be pinned to +# the nested project root; every planning-state read below goes through the +# prefix. An explicit but broken pin fails CLOSED: one notice, nothing +# injected, never a silent fall back to the ambiguous cwd plan the caller was +# escaping. With the var unset the paths stay byte-identical to the legacy +# shape. Wording matches scripts/inject-plan.sh and the sh twin. +$planPrefix = "" +if ($env:PWF_PLAN_ROOT) { + if (Test-Path -LiteralPath $env:PWF_PLAN_ROOT -PathType Container) { + $planPrefix = $env:PWF_PLAN_ROOT + } else { + Write-Output "[planning-with-files] PWF_PLAN_ROOT is not a directory: $($env:PWF_PLAN_ROOT) — nothing injected." + exit 0 + } +} + +if ($planPrefix) { + $planFile = Join-Path $planPrefix "task_plan.md" + $progressFile = Join-Path $planPrefix "progress.md" +} else { + $planFile = "task_plan.md" + $progressFile = "progress.md" +} + +if (Test-Path $planFile) { + # --- Nested-root conflict detection (issue #212): fail CLOSED on ambiguity. + # This hook resolves only the legacy root task_plan.md, so any resolution + # is a cwd GUESS unless PWF_PLAN_ROOT pinned it. If a direct child carries + # its own competing .planning (an .active_plan pointer, or at least one + # /task_plan.md), this cwd is a shared parent and injecting the root + # plan is the wrong answer for at least one thread — inject NOTHING and + # say why. Depth 1 only, matching the sh twin's single glob; dot-named + # children are skipped for parity with the sh glob (`*` never matches + # them), so the root's own .planning is never a hit. Wording matches + # scripts/inject-plan.sh, minus the PLAN_ID escape hatch this route does + # not implement. + if (-not $planPrefix) { + $nestedRoots = @() + foreach ($child in @(Get-ChildItem -Directory -ErrorAction SilentlyContinue)) { + if ($child.Name.StartsWith('.')) { continue } + $nestedPlanning = Join-Path $child.FullName ".planning" + if (-not (Test-Path $nestedPlanning -PathType Container)) { continue } + $competing = Test-Path (Join-Path $nestedPlanning ".active_plan") -PathType Leaf + if (-not $competing) { + foreach ($slug in @(Get-ChildItem -Path $nestedPlanning -Directory -ErrorAction SilentlyContinue)) { + if (Test-Path (Join-Path $slug.FullName "task_plan.md") -PathType Leaf) { + $competing = $true + break + } + } + } + if ($competing) { $nestedRoots += $child.Name } + } + if ($nestedRoots.Count -gt 0) { + $nestedList = (@($nestedRoots | Select-Object -First 3)) -join ", " + Write-Output "[planning-with-files] Ambiguous plan: this cwd has an active plan and a nested project below it has its own ($nestedList). Nothing injected. Pin the thread with PWF_PLAN_ROOT=." + exit 0 + } + } + Write-Output "[planning-with-files] ACTIVE PLAN — current state:" - Get-Content "task_plan.md" -TotalCount 50 -Encoding UTF8 + Get-Content $planFile -TotalCount 50 -Encoding UTF8 Write-Output "" Write-Output "=== recent progress ===" - if (Test-Path "progress.md") { - Get-Content "progress.md" -Tail 20 -Encoding UTF8 + if (Test-Path $progressFile) { + # Timestamp normalization matches scripts/inject-plan.sh and the sh twin + # (KV-cache stability, v2.40): wall-clock times in the injected tail move + # every fire otherwise. + Get-Content $progressFile -Tail 20 -Encoding UTF8 | + ForEach-Object { + $line = $_ -replace 'T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?Z', 'T00:00:00Z' + $line -replace 'T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?([+-][0-9]{2}:[0-9]{2})', 'T00:00:00$2' + } } Write-Output "" Write-Output "[planning-with-files] Read findings.md for research context. Continue from the current phase." diff --git a/.github/hooks/scripts/agent-stop.ps1 b/.github/hooks/scripts/agent-stop.ps1 index 779ed8e..84ebe59 100644 --- a/.github/hooks/scripts/agent-stop.ps1 +++ b/.github/hooks/scripts/agent-stop.ps1 @@ -1,4 +1,4 @@ -# planning-with-files: Agent stop hook for GitHub Copilot (PowerShell) +# planning-with-files: Agent stop hook for GitHub Copilot (PowerShell) # Checks if all phases in task_plan.md are complete. # Injects continuation context if phases are incomplete. # Always exits 0 — outputs JSON to stdout. diff --git a/.github/hooks/scripts/post-tool-use.ps1 b/.github/hooks/scripts/post-tool-use.ps1 index 8efb2fd..c2a577a 100644 --- a/.github/hooks/scripts/post-tool-use.ps1 +++ b/.github/hooks/scripts/post-tool-use.ps1 @@ -1,4 +1,4 @@ -# planning-with-files: Post-tool-use hook for GitHub Copilot (PowerShell) +# planning-with-files: Post-tool-use hook for GitHub Copilot (PowerShell) # Reminds the agent to update task_plan.md after tool use. # Always exits 0 — outputs JSON to stdout. diff --git a/.github/hooks/scripts/pre-tool-use.ps1 b/.github/hooks/scripts/pre-tool-use.ps1 index a7c3f1b..96b084c 100644 --- a/.github/hooks/scripts/pre-tool-use.ps1 +++ b/.github/hooks/scripts/pre-tool-use.ps1 @@ -1,4 +1,4 @@ -# planning-with-files: Pre-tool-use hook for GitHub Copilot (PowerShell) +# planning-with-files: Pre-tool-use hook for GitHub Copilot (PowerShell) # Reads the first 30 lines of task_plan.md to keep goals in context. # Always allows tool execution — this hook never blocks tools. # Always exits 0 — outputs JSON to stdout. diff --git a/.github/hooks/scripts/session-start.ps1 b/.github/hooks/scripts/session-start.ps1 index 2386d9f..cb910f4 100644 --- a/.github/hooks/scripts/session-start.ps1 +++ b/.github/hooks/scripts/session-start.ps1 @@ -1,4 +1,4 @@ -# planning-with-files: Session start hook for GitHub Copilot (PowerShell) +# planning-with-files: Session start hook for GitHub Copilot (PowerShell) # When task_plan.md exists: runs session-catchup or reads plan header. # When task_plan.md doesn't exist: injects SKILL.md so Copilot knows the planning workflow. # Always exits 0 — outputs JSON to stdout. diff --git a/.kiro/skills/planning-with-files/assets/scripts/bootstrap.ps1 b/.kiro/skills/planning-with-files/assets/scripts/bootstrap.ps1 index b5a41f5..51710f4 100644 --- a/.kiro/skills/planning-with-files/assets/scripts/bootstrap.ps1 +++ b/.kiro/skills/planning-with-files/assets/scripts/bootstrap.ps1 @@ -1,4 +1,4 @@ -# Bootstrap planning-with-files into the current workspace (idempotent). +# Bootstrap planning-with-files into the current workspace (idempotent). # Run from the workspace root: # pwsh -File .kiro/skills/planning-with-files/assets/scripts/bootstrap.ps1 diff --git a/.kiro/skills/planning-with-files/assets/scripts/check-complete.ps1 b/.kiro/skills/planning-with-files/assets/scripts/check-complete.ps1 index 2ad27eb..9803b80 100644 --- a/.kiro/skills/planning-with-files/assets/scripts/check-complete.ps1 +++ b/.kiro/skills/planning-with-files/assets/scripts/check-complete.ps1 @@ -1,4 +1,4 @@ -# Report phase completion status for task_plan.md (stdout only, always exit 0). +# Report phase completion status for task_plan.md (stdout only, always exit 0). # Default plan path: .kiro/plan/task_plan.md (relative to current directory). param( diff --git a/skills/planning-with-files-ar/scripts/check-complete.ps1 b/skills/planning-with-files-ar/scripts/check-complete.ps1 index cee7f0a..80ac21c 100644 --- a/skills/planning-with-files-ar/scripts/check-complete.ps1 +++ b/skills/planning-with-files-ar/scripts/check-complete.ps1 @@ -1,4 +1,4 @@ -# التحقق من اكتمال جميع المراحل في task_plan.md +# التحقق من اكتمال جميع المراحل في task_plan.md # ينهي دائمًا برمز خروج 0 — يستخدم stdout للإبلاغ عن الحالة # يُستدعى بواسطة خطاف Stop للإبلاغ عن حالة اكتمال المهمة diff --git a/skills/planning-with-files-ar/scripts/init-session.ps1 b/skills/planning-with-files-ar/scripts/init-session.ps1 index 48d434b..bddeaba 100644 --- a/skills/planning-with-files-ar/scripts/init-session.ps1 +++ b/skills/planning-with-files-ar/scripts/init-session.ps1 @@ -1,4 +1,4 @@ -# تهيئة ملفات التخطيط لجلسة جديدة +# تهيئة ملفات التخطيط لجلسة جديدة # الاستخدام: .\init-session.ps1 [اسم المشروع] param( diff --git a/skills/planning-with-files-de/scripts/check-complete.ps1 b/skills/planning-with-files-de/scripts/check-complete.ps1 index cdf31f8..203968e 100644 --- a/skills/planning-with-files-de/scripts/check-complete.ps1 +++ b/skills/planning-with-files-de/scripts/check-complete.ps1 @@ -1,4 +1,4 @@ -# Prüft, ob alle Phasen in task_plan.md abgeschlossen sind +# Prüft, ob alle Phasen in task_plan.md abgeschlossen sind # Immer mit Exit-Code 0 beenden — Status über stdout melden # Wird vom Stop-Hook aufgerufen, um Aufgabenabschlussstatus zu melden diff --git a/skills/planning-with-files-de/scripts/init-session.ps1 b/skills/planning-with-files-de/scripts/init-session.ps1 index 5d4b0fa..8de712a 100644 --- a/skills/planning-with-files-de/scripts/init-session.ps1 +++ b/skills/planning-with-files-de/scripts/init-session.ps1 @@ -1,4 +1,4 @@ -# Initialisiert Planungsdateien für eine neue Sitzung +# Initialisiert Planungsdateien für eine neue Sitzung # Verwendung: .\init-session.ps1 [Projektname] param( diff --git a/skills/planning-with-files-es/scripts/check-complete.ps1 b/skills/planning-with-files-es/scripts/check-complete.ps1 index 22e95e8..5a14e88 100644 --- a/skills/planning-with-files-es/scripts/check-complete.ps1 +++ b/skills/planning-with-files-es/scripts/check-complete.ps1 @@ -1,4 +1,4 @@ -# Verificar si todas las fases en task_plan.md están completas +# Verificar si todas las fases en task_plan.md están completas # Siempre salir con código 0 — usar stdout para informar el estado # Llamado por el hook Stop para informar el estado de finalización de la tarea diff --git a/skills/planning-with-files-es/scripts/init-session.ps1 b/skills/planning-with-files-es/scripts/init-session.ps1 index 568c5d2..914cb3b 100644 --- a/skills/planning-with-files-es/scripts/init-session.ps1 +++ b/skills/planning-with-files-es/scripts/init-session.ps1 @@ -1,4 +1,4 @@ -# Inicializar archivos de planificación para una nueva sesión +# Inicializar archivos de planificación para una nueva sesión # Uso: .\init-session.ps1 [nombre_del_proyecto] param( diff --git a/skills/planning-with-files-zh/scripts/check-complete.ps1 b/skills/planning-with-files-zh/scripts/check-complete.ps1 index 26cee73..ddd5398 100644 --- a/skills/planning-with-files-zh/scripts/check-complete.ps1 +++ b/skills/planning-with-files-zh/scripts/check-complete.ps1 @@ -1,4 +1,4 @@ -# 检查 task_plan.md 中所有阶段是否完成 +# 检查 task_plan.md 中所有阶段是否完成 # 始终以退出码 0 结束 — 使用标准输出报告状态 # 由 Stop 钩子调用以报告任务完成状态 diff --git a/skills/planning-with-files-zh/scripts/init-session.ps1 b/skills/planning-with-files-zh/scripts/init-session.ps1 index 096510d..f11a0fa 100644 --- a/skills/planning-with-files-zh/scripts/init-session.ps1 +++ b/skills/planning-with-files-zh/scripts/init-session.ps1 @@ -1,4 +1,4 @@ -# 初始化新会话的规划文件 +# 初始化新会话的规划文件 # 用法:.\init-session.ps1 [项目名称] param( diff --git a/skills/planning-with-files-zht/scripts/check-complete.ps1 b/skills/planning-with-files-zht/scripts/check-complete.ps1 index 74e3dcb..06ec5b5 100644 --- a/skills/planning-with-files-zht/scripts/check-complete.ps1 +++ b/skills/planning-with-files-zht/scripts/check-complete.ps1 @@ -1,4 +1,4 @@ -# 檢查 task_plan.md 中所有階段是否完成 +# 檢查 task_plan.md 中所有階段是否完成 # 始終以退出碼 0 結束 — 使用標準輸出回報狀態 # 由 Stop 鉤子呼叫以回報任務完成狀態 diff --git a/skills/planning-with-files-zht/scripts/init-session.ps1 b/skills/planning-with-files-zht/scripts/init-session.ps1 index b7b5ac8..1557da2 100644 --- a/skills/planning-with-files-zht/scripts/init-session.ps1 +++ b/skills/planning-with-files-zht/scripts/init-session.ps1 @@ -1,4 +1,4 @@ -# 初始化新會話的規劃檔案 +# 初始化新會話的規劃檔案 # 用法:.\init-session.ps1 [專案名稱] param( diff --git a/tests/test_ps1_windows_encoding.py b/tests/test_ps1_windows_encoding.py new file mode 100644 index 0000000..d8e9e55 --- /dev/null +++ b/tests/test_ps1_windows_encoding.py @@ -0,0 +1,140 @@ +"""Encoding guard for the Windows PowerShell 5.1 silent-kill class. + +Windows PowerShell 5.1 (`powershell.exe`, still the default shell on Windows +and the interpreter every hook dispatcher reaches for first) reads a `.ps1` +file as ANSI (CP1252 on a western install) unless the file carries a UTF-8 +BOM. PowerShell 7 (`pwsh`) assumes UTF-8 either way, so a BOM-less script +holding non-ASCII text parses on the developer's machine and dies on the +user's. + +It dies rather than merely garbling because of which bytes land where. The +UTF-8 encoding of an em dash is E2 80 94, and CP1252 maps 0x94 to a curly +closing double quote, so the character opens a string literal that never +closes. Arrows (U+2192, ending in 0x92, a curly apostrophe) do the same. The +failure is a parse error before the first statement runs, and every hook +dispatcher in this repo wraps its PowerShell call in fallbacks that swallow +the error, so planning hooks simply stop firing with no visible symptom. + +Measured at v3.8.2, eight shipped scripts failed to parse under 5.1: +`.cursor/hooks/user-prompt-submit.ps1` (the Cursor plan injection hook), both +`.kiro` asset scripts, the Arabic `check-complete.ps1`, and `check-complete` +plus `init-session` for both Chinese variants. The Chinese `init-session.ps1` +meant a Windows user of that variant could not create a plan at all. + +The invariant is therefore: a tracked `.ps1` containing any byte above 0x7F +must begin with a UTF-8 BOM. Pure-ASCII scripts need nothing, which is why +the canonical English scripts are exempt and stay byte-identical to their +mirrored copies. +""" +from __future__ import annotations + +import shutil +import subprocess +import unittest +from pathlib import Path + + +REPO_ROOT = Path(__file__).resolve().parents[1] +UTF8_BOM = b"\xef\xbb\xbf" + + +def _tracked_ps1() -> list[Path]: + """Every .ps1 tracked by git, or [] when this is not a git checkout.""" + try: + proc = subprocess.run( + ["git", "ls-files", "*.ps1"], + cwd=REPO_ROOT, + capture_output=True, + text=True, + encoding="utf-8", + ) + except OSError: + return [] + if proc.returncode != 0: + return [] + return [REPO_ROOT / line for line in proc.stdout.split() if line] + + +def _windows_powershell() -> str | None: + """Path to Windows PowerShell 5.1, which is the interpreter that actually + has the ANSI default. pwsh is deliberately NOT accepted here: it parses + BOM-less UTF-8 correctly and would make this check pass vacuously.""" + return shutil.which("powershell.exe") or shutil.which("powershell") + + +class Ps1EncodingTests(unittest.TestCase): + def test_repo_has_tracked_ps1_files(self) -> None: + # Guard against the whole suite passing because the glob found nothing. + self.assertTrue(_tracked_ps1(), "expected tracked .ps1 files in the repo") + + def test_non_ascii_ps1_carries_utf8_bom(self) -> None: + for path in _tracked_ps1(): + data = path.read_bytes() + if all(byte < 0x80 for byte in data): + continue + rel = path.relative_to(REPO_ROOT).as_posix() + with self.subTest(script=rel): + self.assertTrue( + data.startswith(UTF8_BOM), + f"{rel} holds non-ASCII but has no UTF-8 BOM, so Windows " + f"PowerShell 5.1 reads it as ANSI and can fail to parse it", + ) + + def test_bom_is_not_added_to_pure_ascii_scripts(self) -> None: + # A blanket "BOM everything" fix would break the byte-identity the + # dual-shipped script parity tests enforce, so keep ASCII files bare. + for path in _tracked_ps1(): + data = path.read_bytes() + if not data.startswith(UTF8_BOM): + continue + rel = path.relative_to(REPO_ROOT).as_posix() + with self.subTest(script=rel): + self.assertFalse( + all(byte < 0x80 for byte in data[len(UTF8_BOM):]), + f"{rel} is pure ASCII and does not need a BOM", + ) + + +@unittest.skipUnless(_windows_powershell(), "Windows PowerShell 5.1 not available") +class Ps1ParseTests(unittest.TestCase): + """The direct proof: ask the real interpreter to parse every script. + + ParseFile applies the same encoding detection as execution, so this + catches any encoding trap, not only the BOM one the guard above covers. + """ + + def test_every_ps1_parses_under_windows_powershell(self) -> None: + scripts = _tracked_ps1() + self.assertTrue(scripts, "expected tracked .ps1 files in the repo") + shell = _windows_powershell() + assert shell is not None # guaranteed by the class-level skipUnless + command = ( + "$bad = @(); " + "foreach ($f in $input) { " + " $errors = $null; " + " $null = [System.Management.Automation.Language.Parser]::ParseFile(" + "$f, [ref]$null, [ref]$errors); " + " if ($errors -and $errors.Count -gt 0) { " + " $bad += ('{0} :: {1}' -f $f, $errors[0].Message) } }; " + "$bad -join \"`n\"" + ) + proc = subprocess.run( + [shell, "-NoProfile", "-ExecutionPolicy", "RemoteSigned", + "-Command", command], + input="\n".join(str(p) for p in scripts), + cwd=str(REPO_ROOT), + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + ) + failures = (proc.stdout or "").strip() + self.assertEqual( + failures, + "", + f"PowerShell scripts failed to parse under Windows PowerShell:\n{failures}", + ) + + +if __name__ == "__main__": + unittest.main()