fix(skill): make skill initialization safe on Windows pipes (#421)

## Summary
- Keep the caller's stdout encoding and escape only characters it cannot
represent. This prevents the normal skill initializer command from
aborting on legacy-encoded Windows pipes and preserves Unicode output on
UTF-8 streams.
- Write all generated skill templates as UTF-8 so the localized content
does not depend on the machine locale.
- Exercise the actual CLI with CP1252 and UTF-8 output in the i18n
validation workflow, including a non-ASCII destination, generated
localized files, and duplicate-directory errors.

## Validation
- Reproduced UnicodeEncodeError with the unmodified CLI and CP1252
stdout; both focused regression tests pass on the change.
- Catalog and i18n validation passed with zero errors; translation
freshness and `git diff --check` passed.
- No new dependencies or metadata changes. A native installed-app
confirmation still belongs to the consuming product after syncing the
bundled Market seed.
This commit is contained in:
yige authored and GitHub committed 2026-12-02 11:39:40 +08:00
1 parent 55588fd33f
commit 39370aba29
3 files changed
+105 -5

No files matched your search

+4
View File
@@ -62,6 +62,10 @@ jobs:
if: steps.changes.outputs.relevant == 'true'
run: uv run --quiet scripts/i18n/test_validate_i18n.py
- name: Run skill-creator CLI encoding tests
if: steps.changes.outputs.relevant == 'true'
run: python3 -B scripts/catalog/test_skill_creator_cli.py
- name: Run Office launcher contract tests
if: steps.changes.outputs.relevant == 'true'
run: python3 -B scripts/office/test_runtime_launcher.py
+91
View File
@@ -0,0 +1,91 @@
"""Regression tests for skill-creator's documented CLI with piped output."""
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "skills" / "skill-creator" / "scripts" / "init_skill.py"
class SkillCreatorCliTest(unittest.TestCase):
def run_initializer(self, encoding, path, skill_format="desirecore", *, locale_env=None):
# Emulate the Windows locale pipe on any CI host. No interpreter encoding
# flags: run the same script entry point as the documented command.
return subprocess.run(
[sys.executable, str(SCRIPT), "sample-skill", "--path", str(path),
"--format", skill_format],
capture_output=True,
env={**os.environ, **(locale_env or {}), "PYTHONIOENCODING": f"{encoding}:strict"},
check=False,
)
def test_cp1252_pipe_creates_utf8_files_under_non_ascii_path(self):
with tempfile.TemporaryDirectory() as tmp:
parent = Path(tmp) / "示例目录"
run = self.run_initializer("cp1252", parent)
self.assertEqual(run.returncode, 0, run.stderr.decode("ascii", "replace"))
stdout = run.stdout.decode("cp1252", "strict")
self.assertIn("Initializing skill: sample-skill", stdout)
self.assertIn("initialized at", stdout)
skill = parent / "sample-skill"
self.assertIn("name: sample-skill", (skill / "SKILL.md").read_text(encoding="utf-8"))
localized = (skill / "SKILL.zh-CN.md").read_text(encoding="utf-8")
self.assertTrue(any(ord(char) > 127 for char in localized))
for name in ("scripts/example.py", "references/api_reference.md", "assets/example_asset.txt"):
self.assertTrue((skill / name).read_text(encoding="utf-8"))
duplicate = self.run_initializer("cp1252", parent)
self.assertEqual(duplicate.returncode, 1)
self.assertIn("Skill directory already exists", duplicate.stdout.decode("cp1252"))
self.assertNotIn(b"UnicodeEncodeError", duplicate.stderr)
@unittest.skipUnless(os.name == "posix", "C locale is a POSIX regression fixture")
def test_template_writes_use_utf8_when_file_default_is_ascii(self):
locale_env = {
"LC_ALL": "C",
"PYTHONUTF8": "0",
"PYTHONCOERCECLOCALE": "0",
}
# PYTHONIOENCODING only affects stdio; independently prove this child
# interpreter's default file encoding is ASCII.
probe = subprocess.run(
[sys.executable, "-c",
"import codecs, os; print(codecs.lookup(open(os.devnull).encoding).name)"],
capture_output=True,
env={**os.environ, **locale_env, "PYTHONIOENCODING": "cp1252:strict"},
check=True,
)
self.assertEqual(probe.stdout.decode("cp1252").strip(), "ascii")
# A missing explicit file encoding must also fail for templates that
# currently happen to contain only ASCII.
locale_env.update(PYTHONWARNDEFAULTENCODING="1", PYTHONWARNINGS="error::EncodingWarning")
with tempfile.TemporaryDirectory() as tmp:
parent = Path(tmp) / "示例目录"
run = self.run_initializer("cp1252", parent, locale_env=locale_env)
diagnostic = run.stdout.decode("cp1252") + run.stderr.decode("cp1252", "replace")
self.assertEqual(run.returncode, 0, diagnostic)
skill = parent / "sample-skill"
self.assertIn("中文一句话简介", (skill / "SKILL.md").read_text(encoding="utf-8"))
self.assertIn("能力描述", (skill / "SKILL.zh-CN.md").read_text(encoding="utf-8"))
self.assertIn("—", (skill / "assets/example_asset.txt").read_text(encoding="utf-8"))
def test_utf8_pipe_preserves_unicode_output(self):
with tempfile.TemporaryDirectory() as tmp:
parent = Path(tmp) / "示例目录"
run = self.run_initializer("utf-8", parent, "basic")
self.assertEqual(run.returncode, 0, run.stderr.decode("utf-8", "replace"))
stdout = run.stdout.decode("utf-8", "strict")
self.assertIn("🚀 Initializing skill: sample-skill", stdout)
self.assertIn("✅", stdout)
self.assertIn(parent.name, stdout)
if __name__ == "__main__":
unittest.main()
+10 -5
View File
@@ -227,7 +227,7 @@ def init_skill(skill_name, path, fmt='desirecore'):
skill_md_path = skill_dir / 'SKILL.md'
try:
skill_md_path.write_text(skill_content)
skill_md_path.write_text(skill_content, encoding='utf-8')
print(f"✅ Created SKILL.md ({fmt} format)")
except Exception as e:
print(f"❌ Error creating SKILL.md: {e}")
@@ -236,7 +236,7 @@ def init_skill(skill_name, path, fmt='desirecore'):
if fmt == 'desirecore':
source_body = DESIRECORE_SOURCE_BODY.format(skill_title=skill_title)
try:
(skill_dir / 'SKILL.zh-CN.md').write_text(source_body)
(skill_dir / 'SKILL.zh-CN.md').write_text(source_body, encoding='utf-8')
print("✅ Created SKILL.zh-CN.md (source locale)")
except Exception as e:
print(f"❌ Error creating SKILL.zh-CN.md: {e}")
@@ -247,20 +247,20 @@ def init_skill(skill_name, path, fmt='desirecore'):
scripts_dir = skill_dir / 'scripts'
scripts_dir.mkdir(exist_ok=True)
example_script = scripts_dir / 'example.py'
example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))
example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name), encoding='utf-8')
example_script.chmod(0o755)
print("✅ Created scripts/example.py")
references_dir = skill_dir / 'references'
references_dir.mkdir(exist_ok=True)
example_ref = references_dir / 'api_reference.md'
example_ref.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title))
example_ref.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title), encoding='utf-8')
print("✅ Created references/api_reference.md")
assets_dir = skill_dir / 'assets'
assets_dir.mkdir(exist_ok=True)
example_asset = assets_dir / 'example_asset.txt'
example_asset.write_text(EXAMPLE_ASSET)
example_asset.write_text(EXAMPLE_ASSET, encoding='utf-8')
print("✅ Created assets/example_asset.txt")
except Exception as e:
print(f"❌ Error creating resource directories: {e}")
@@ -276,6 +276,11 @@ def init_skill(skill_name, path, fmt='desirecore'):
def main():
# Windows pipes can retain a narrow locale encoding even when the filesystem
# supports Unicode. Escape only unrepresentable log characters; keep the
# caller's encoding (and, on UTF-8 terminals, all Unicode output) unchanged.
sys.stdout.reconfigure(errors='backslashreplace')
parser = argparse.ArgumentParser(
description='Initialize a new skill from template',
epilog='Examples:\n'