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44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
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()