import json import os import re import subprocess import sys import tempfile import unittest from pathlib import Path REPO = Path(__file__).resolve().parents[1] SKILL = REPO / "skills" / "speak-human" CHECK = SKILL / "scripts" / "check.py" RULES = SKILL / "references" / "core-rules.json" EVALS = REPO / "evals" / "trigger_eval.jsonl" PLUGIN = REPO / ".claude-plugin" / "plugin.json" VERSION = "2.1.1" PACKAGE_FILES = { "LICENSE.txt", "SKILL.md", "SKILL.zh-CN.md", "agents/openai.yaml", "assets/review-output-template.md", "references/core-method.md", "references/communication-modes.md", "references/language-signals.md", "references/social-media.md", "references/core-rules.json", "references/voice-profile.schema.json", "scripts/check.py", } MODES = { "general", "status_update", "technical_explanation", "decision_recommendation", "professional_document", "readme_release", "resume_portfolio", "conversation_reply", } PRIVATE_PLACEHOLDERS = re.compile( r"\[(?:INTERNAL_EMPLOYEE|PRIVATE_CORPUS|LOCAL_USERNAME)\]" ) SOCIAL_CONTEXT = re.compile( r"社媒|小红书|微博|抖音|social media|X post|Reddit|Instagram|TikTok", re.IGNORECASE, ) POSITIVE_ACTION = re.compile( r"\$speak-human|speak-human|改写|重写|润色|改得|改成|压短|整理成|帮我回复|" r"写得.{0,10}(?:清楚|自然|像人)|解释.{0,20}(?:给|让)|" r"rewrite|review|make .{0,50}(?:clearer|easier)|turn .{0,50}into", re.IGNORECASE, ) HUMAN_WRITING = re.compile( r"进度|状态更新|汇报|解释|OAuth|技术|decision memo|recommendation|" r"leadership|客户|实施方案|email|vendor|README|release note|" r"简历|portfolio|同事|消息|公告|小红书|项目复盘|报告|文档", re.IGNORECASE, ) EXPLICIT_NON_TRIGGER = re.compile( r"不要改写|不需要润色|逐字翻译|do not draft|do not edit|" r"只报告|只给我|source-code|off-by-one|CSV|JSON|柱状图|头像|" r"重复 PDF|发布时间|不做风格改写", re.IGNORECASE, ) def package_files() -> set[str]: return { path.relative_to(SKILL).as_posix() for path in SKILL.rglob("*") if path.is_file() and "__pycache__" not in path.parts } def parse_frontmatter(path: Path) -> dict[str, str]: text = path.read_text(encoding="utf-8") match = re.match(r"(?s)^---\n(.*?)\n---\n", text) if not match: raise AssertionError(f"missing frontmatter: {path}") fields = {} for line in match.group(1).splitlines(): if ":" in line: key, value = line.split(":", 1) fields[key.strip()] = value.strip() return fields def run_check(*args: str) -> subprocess.CompletedProcess[str]: return subprocess.run( [sys.executable, str(CHECK), *args], text=True, encoding="utf-8", env={**os.environ, "PYTHONIOENCODING": "utf-8"}, capture_output=True, check=False, ) def finding_kinds(result: subprocess.CompletedProcess[str]) -> set[str]: payload = json.loads(result.stdout) return {row["kind"] for row in payload["findings"]} def reference_trigger(prompt: str) -> str: if "$speak-human" in prompt or "speak-human" in prompt: return "TRIGGER" if EXPLICIT_NON_TRIGGER.search(prompt): return "NO_TRIGGER" return ( "TRIGGER" if POSITIVE_ACTION.search(prompt) and HUMAN_WRITING.search(prompt) else "NO_TRIGGER" ) class SpeakHumanContractTests(unittest.TestCase): def test_package_layout_and_frontmatter(self): self.assertEqual(package_files(), PACKAGE_FILES) for filename in ("SKILL.md", "SKILL.zh-CN.md"): fields = parse_frontmatter(SKILL / filename) self.assertEqual(set(fields), {"name", "description"}) self.assertEqual(fields["name"], "speak-human") def test_version_and_core_mode_contract(self): payload = json.loads(RULES.read_text(encoding="utf-8")) plugin = json.loads(PLUGIN.read_text(encoding="utf-8")) self.assertEqual(payload["standard_version"], VERSION) self.assertEqual(payload["package_version"], VERSION) self.assertEqual(plugin["version"], VERSION) self.assertEqual(plugin["name"], "speak-human") self.assertIn("human-facing communication", plugin["description"].lower()) self.assertNotIn("public copy", plugin["description"].lower()) self.assertEqual(set(payload["modes"]), MODES) self.assertNotIn("scenes", payload) def test_social_media_is_an_optional_adapter(self): payload = json.loads(RULES.read_text(encoding="utf-8")) self.assertTrue( all(rule["domain"] == "GENERAL_CORE" for rule in payload["rules"]) ) self.assertNotIn("social_media", payload["modes"]) self.assertTrue((SKILL / "references" / "social-media.md").exists()) helper = CHECK.read_text(encoding="utf-8") for token in ("X 已爆", "小红书", "information_gap_diagnostic"): self.assertNotIn(token, helper) def test_openai_metadata_describes_general_communication(self): metadata = (SKILL / "agents" / "openai.yaml").read_text(encoding="utf-8") lines = [line.rstrip() for line in metadata.splitlines() if line.strip()] self.assertEqual(lines[0], "interface:") self.assertEqual( {line.strip().split(":", 1)[0] for line in lines[1:]}, {"display_name", "short_description", "brand_color", "default_prompt"}, ) self.assertTrue(all(line.startswith(" ") for line in lines[1:])) self.assertIn(' display_name: "Speak Human"', lines) self.assertIn("$speak-human", metadata) self.assertRegex(metadata.lower(), r"communication|沟通") def test_bilingual_skill_keeps_core_contract(self): english = (SKILL / "SKILL.md").read_text(encoding="utf-8") chinese = (SKILL / "SKILL.zh-CN.md").read_text(encoding="utf-8") for token in ( "status updates", "explanations", "recommendations", "emails", "README", "resumes", "replies", "Social media is an adapter, not the default.", "private | internal | external | public", "scripts/check.py", VERSION, "silent obligations", "Do not manufacture a lesson", ): self.assertIn(token, english) for token in ( "进度汇报", "解释说明", "建议与决策", "邮件", "README", "简历", "回复", "社媒只是适配层,不是默认场景。", "private | internal | external | public", "scripts/check.py", VERSION, "内部要遵守的条件", "不要再强行补教训", ): self.assertIn(token, chinese) def test_all_public_version_surfaces_match(self): surfaces = { ".claude-plugin/plugin.json": PLUGIN.read_text(encoding="utf-8"), "CHANGELOG.md": (REPO / "CHANGELOG.md").read_text(encoding="utf-8"), "README.md": (REPO / "README.md").read_text(encoding="utf-8"), "README.zh-CN.md": (REPO / "README.zh-CN.md").read_text( encoding="utf-8" ), "skills/speak-human/SKILL.md": (SKILL / "SKILL.md").read_text( encoding="utf-8" ), "skills/speak-human/SKILL.zh-CN.md": ( SKILL / "SKILL.zh-CN.md" ).read_text(encoding="utf-8"), "skills/speak-human/references/core-rules.json": RULES.read_text( encoding="utf-8" ), } for name, text in surfaces.items(): self.assertIn(VERSION, text, name) def test_readme_relative_links_resolve(self): for name in ("README.md", "README.zh-CN.md", "中文用户看这里.md"): text = (REPO / name).read_text(encoding="utf-8") for target in re.findall(r"\]\(([^)]+)\)", text): if target.startswith(("http://", "https://", "#")): continue path_only = target.split("#", 1)[0] self.assertTrue((REPO / path_only).exists(), f"{name}: {target}") def test_repository_contains_no_private_material(self): old_names = ("human" + "-voice-zh", "Human" + " Voice ZH") hits = [] for path in REPO.rglob("*"): if ( not path.is_file() or ".git" in path.parts or "__pycache__" in path.parts or "tests" in path.parts or path.name in {"LICENSE", "LICENSE.txt"} ): continue text = path.read_text(encoding="utf-8") for old_name in old_names: if old_name in text: hits.append((path.relative_to(REPO).as_posix(), "old_name")) if PRIVATE_PLACEHOLDERS.search(text): hits.append( (path.relative_to(REPO).as_posix(), "private_placeholder") ) self.assertEqual(hits, []) def test_check_local_paths_follow_exposure(self): text = r"Build log: C:\Users\someone\project\output.txt" for exposure in ("external", "public"): result = run_check("--exposure", exposure, "--text", text) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn("local_path", finding_kinds(result)) internal = run_check("--exposure", "internal", "--text", text) self.assertEqual(internal.returncode, 0, internal.stderr) payload = json.loads(internal.stdout) self.assertEqual(payload["exposure"], "internal") self.assertEqual(payload["findings"], []) def test_check_unc_paths_follow_exposure(self): text = r"Build log: \\corp-server\private\draft.md" for exposure in ("external", "public"): result = run_check("--exposure", exposure, "--text", text) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn("unc_path", finding_kinds(result)) self.assertTrue( any( row["kind"] == "unc_path" and row["severity"] == "P0" for row in json.loads(result.stdout)["findings"] ) ) for exposure in ("private", "internal"): result = run_check("--exposure", exposure, "--text", text) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(json.loads(result.stdout)["findings"], []) def test_check_credentials_are_always_flagged(self): samples = ( ('api_token="abcdefghijk"', "credential_assignment", "abcdefghijk"), ("api_token='zyxwvutsrqp'", "credential_assignment", "zyxwvutsrqp"), ( "OPENAI_API_KEY='sk-proj_abcdefghijklmnopqrstuvwxyz123456'", "credential_assignment", "sk-proj_abcdefghijklmnopqrstuvwxyz123456", ), ( "refresh_token=rt_abcdefghijklmnopqrstuvwxyz123456", "credential_assignment", "rt_abcdefghijklmnopqrstuvwxyz123456", ), ( "password='Tr0ub4dor!42'", "credential_assignment", "Tr0ub4dor!42", ), ( "Authorization: Bearer ghp_abcdefghijklmnopqrstuvwxyz123456", "credential_bearer", "ghp_abcdefghijklmnopqrstuvwxyz123456", ), ) for text, expected_kind, secret in samples: for exposure in ("private", "internal", "external", "public"): result = run_check("--exposure", exposure, "--text", text) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn(expected_kind, finding_kinds(result)) self.assertNotIn(secret, result.stdout) self.assertTrue( any( row["kind"] == expected_kind and row["severity"] == "P0" and row["preview"].endswith("[REDACTED]") for row in json.loads(result.stdout)["findings"] ) ) def test_check_credential_discussion_is_not_flagged(self): samples = ( "The API token field accepts at least eight characters.", "Set the Authorization header to use the Bearer scheme.", "Never paste a password or secret into a public post.", "token: authentication", ) for text in samples: result = run_check("--exposure", "public", "--text", text) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(json.loads(result.stdout)["findings"], []) def test_check_internal_markers_follow_exposure(self): text = "【待校正】发布完成" for exposure in ("external", "public"): result = run_check("--exposure", exposure, "--text", text) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn("internal_marker", finding_kinds(result)) internal = run_check("--exposure", "internal", "--text", text) self.assertEqual(internal.returncode, 0, internal.stderr) self.assertEqual(json.loads(internal.stdout)["findings"], []) def test_check_file_input_and_voice_profile(self): with tempfile.TemporaryDirectory() as temp_dir: root = Path(temp_dir) source = root / "draft.txt" source.write_text("No sensitive material here.", encoding="utf-8") profile = root / "profile.json" profile.write_text( json.dumps( { "profile_version": "1.0.0", "languages": ["en"], "global_prefer": ["lead with the conclusion"], } ), encoding="utf-8", ) result = run_check( "--exposure", "internal", "--file", str(source), "--voice-profile", str(profile), ) self.assertEqual(result.returncode, 0, result.stderr) payload = json.loads(result.stdout) self.assertEqual(payload["exposure"], "internal") self.assertTrue(payload["voice_profile_loaded"]) self.assertEqual(payload["findings"], []) invalid = root / "invalid-profile.json" invalid.write_text( json.dumps( { "profile_version": "1.0.0", "languages": ["en"], "mode_preferences": { "status_update": {"prefer": "not-a-list"} }, } ), encoding="utf-8", ) rejected = run_check( "--exposure", "internal", "--text", "No sensitive material here.", "--voice-profile", str(invalid), ) self.assertEqual(rejected.returncode, 1) self.assertIn("must be a string list", rejected.stderr) duplicate_languages = root / "duplicate-languages.json" duplicate_languages.write_text( json.dumps( { "profile_version": "1.0.0", "languages": ["en", "en"], } ), encoding="utf-8", ) rejected_duplicate = run_check( "--exposure", "internal", "--text", "No sensitive material here.", "--voice-profile", str(duplicate_languages), ) self.assertEqual(rejected_duplicate.returncode, 1) self.assertIn("must not contain duplicates", rejected_duplicate.stderr) def test_trigger_and_non_trigger_fixtures(self): rows = [ json.loads(line) for line in EVALS.read_text(encoding="utf-8").splitlines() if line.strip() ] self.assertEqual(len(rows), 24) self.assertEqual(len({row["id"] for row in rows}), 24) self.assertEqual( sum(row["expected"] == "TRIGGER" for row in rows), 12, ) self.assertEqual( sum(row["expected"] == "NO_TRIGGER" for row in rows), 12, ) positive_rows = [row for row in rows if row["expected"] == "TRIGGER"] self.assertLessEqual( sum(bool(SOCIAL_CONTEXT.search(row["prompt"])) for row in positive_rows), 3, "social media must remain an optional adapter, not the core trigger surface", ) for row in rows: self.assertEqual( reference_trigger(row["prompt"]), row["expected"], row["id"], ) def test_published_package_contains_no_private_placeholders(self): hits = [] for path in SKILL.rglob("*"): if not path.is_file() or path.name == "LICENSE.txt": continue text = path.read_text(encoding="utf-8") if PRIVATE_PLACEHOLDERS.search(text): hits.append(path.relative_to(SKILL).as_posix()) self.assertEqual(hits, []) if __name__ == "__main__": unittest.main()